The task is really simple: given N N 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
N
N (in [3,
1
0
5
10^5
105]), followed by
N
N
N integer distances
D
1
D
2
⋯
D
N
D_1D_2⋯D_N
D1D2⋯DN, where
D
i
D_i
Di is the distance between the
i
i
i-th and the (
i
i
i+1)-st exits, and DN is between the
N
N
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
M
M (≤
1
0
4
10^4
104), with
M
M
M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to
N
N
N. It is guaranteed that the total round trip distance is no more than
1
0
7
10^7
107.
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
思路:路径为环形,可以顺时针也可以逆时针,两种路径长度之和为环周长,故第二种路径长度=总长度-第一种路径长度,且两者最小值为最短路径。所以我们只需求固定的一种路径就行(这里求的是标号从小到大的路径)。如果直接是把两点之间的长度放入数组,然后再累计求和,遇到数据比较多的情况下会超时。这里采用的方法是前缀和。即读入数据时同时用一个数组记录从1号点到其他所有点的距离,可以降低算法复杂度
#include <cstdio>
#include <algorithm>
using namespace std;
int a[100000], d[100000];//全局变量数组声明时默认元素全为0
int main() {
int n;
while (scanf("%d", &n) != EOF) {//codeup上是多点测试
int sum = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
sum += a[i];
d[i + 1] = sum;//记录从第一个点到第i+1个点之间的距离
}
int m;
scanf("%d", &m);
while (m--) {
int x, y;
scanf("%d%d", &x, &y);
if (x > y) {
swap(x, y);
}
int dis = d[y] - d[x];//
printf("%d\n", min(dis, sum - dis));
}
}
return 0;
}