1046 Shortest Distance (20 分)
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.
Input Specification:
Each input file contains one test case. For each case, the first line contains an integer N (in [3,105]), followed by N integer distances D1 D2⋯ DN , where Di is the distance between the i-th and the (i+1)-st exits, and DN 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 (≤104 ), 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 10
7.
Output Specification:
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
Sample Input:
5 1 2 4 14 9
3
1 3
2 5
4 1
Sample Output:
3
10
7
//本题感觉有点崩,做了半下午……疯狂拉低通过率
//一个环,给环上两点算最短路径长度,即顺时针和逆时针的路径长度最小值
//我们只需计算其中一个方向上的,然后用环的总长度减去它,即得逆向的长度
//时间复杂度有要求,总的时间复杂度是O(N)吧,之前写了两三个算法,都是最后一个测试点超时
#include <cstdio>
#include <cstring>
#include <cmath>
int D[100001] = { 0 };//各地点间的距离
int main()
{
int N = 0, M = 0;
scanf("%d", &N);
for (int i = 1, dis = 0; i <= N; i++)
{
scanf("%d", &dis);
D[i] += D[i - 1] + dis;//累加路程长度
}
scanf("%d", &M);
for (int i = 0; i < M; i++)
{
int a = 0, b = 0, path1 = 0, path2 = 0;
scanf("%d %d", &a, &b);
if (a > b) path1 = D[a-1] - D[b-1];//先计算出正向的长度;这里很巧妙
else path1 = D[b-1] - D[a-1];
path2 = D[N] - path1;//反向长度即总长度减去正向的长度(环形)
printf("%d\n", path1 < path2 ? path1 : path2);//输出较小者即可
}
return 0;
}