标签:code air ati return 数组 ble nes 比较 main
The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.
Each input file contains one test case. For each case, the first line contains an integer N (in [3]), followed by N integer distances D?1?? D?2?? ? D?N??, where D?i?? is the distance between the i-th and the (-st exits, and D?N?? is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (≤), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 1.
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
5 1 2 4 14 9
3
1 3
2 5
4 1
3
10
7
输入一个N:表示有N个出口
输入N个数:D1,D2,....DN,表示第 i 个 与 第 i + 1 个出口之间的距离
输入一个M:表示有M组数据
剩下M行,每行输入2个数 i 和 j:表示 i 与 j 之间的最短距离
Dn[i] :保存第 i 个与第 i + 1 个出口之间的距离
sum :保存总距离(从1到N再到1,形成的一个环)
给出的两个出口: exit1, exit2 ,计算 两个出口之间的距离 s ,再与 sum - s 比较,最小的那个就是最短距离
一开始想着用累加的方式,用D1,D2,DN计算出口之间的距离,但是这样会超时
所以需要对距离进行预处理,得到一个 数组 disc
里面保存了从 1 到 2, 从 1 到 3, 从 1 到 4 的距离
如果要计算从 2 到 4 的距离, 就相当于是 1到4的距离 - 1到2的距离
需要注意的是:第一个出口必须小于第二个出口,否则就交换两个值
#include <iostream> #include <vector> using namespace std; int main() { int N; cin >> N; vector<int> Dn(N + 1); vector<int> disc(N + 1); int sum = 0; for (int i = 1; i <= N; ++i) { cin >> Dn[i]; sum += Dn[i]; disc[i] = sum; } int M; int exit1 = 0, exit2 = 0; cin >> M; for (int i = 0; i < M; ++i) { cin >> exit1 >> exit2; if (exit1 > exit2) { swap(exit1, exit2); } int shortest = 0; int temp = disc[exit2 - 1] - disc[exit1 - 1]; shortest = temp < sum - temp ? temp : sum - temp; cout << shortest << endl; } return 0; }
PAT 甲级 1046.Shortest Distance C++/Java
标签:code air ati return 数组 ble nes 比较 main
原文地址:https://www.cnblogs.com/47Pineapple/p/12264689.html