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,10^5]), followed by N integer distances D1 D2 ⋯ DN, here 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 (≤10^4), 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.
输出格式:
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
解题思路:
根据给出的样例,我们知道顺时针每条有向边的长度。
假定dist[i]存放1号节点到 i+1号节点的距离,sum存放所有有向边的长度总和;则任给节点a到节点b(a>b)的最短距离为min((dist[a-1]-disr[b-1]), sum - (dist[a-1]-disr[b-1])) 。
#include <cstdio>
const int MAXN = 100005;
int dist[MAXN], D[MAXN];
void swap(int &a, int &b);
int main() {
int N, sum = 0;
scanf("%d", &N);
for(int i = 1; i <= N; i++) {
scanf("%d", &D[i]);
sum += D[i];
dist[i] = sum;
}
int M, left, right;
scanf("%d", &M);
for(int i = 0; i < M; i++) {
scanf("%d %d", &left, &right);
if(left > right) swap(left, right);
int temp = dist[right - 1] - dist[left - 1];
printf("%d\n", (temp > (sum-temp) ? (sum - temp) : temp));
}
return 0;
}
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}