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 , followed by integer distances , where 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 , with 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 .
Output Specification:
For each test case, print your results in 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
Ω
估计是火星上的高速公路,出口能围成一个圈。
给出相邻出口的距离,然后需要你输出几对指定出口之间的最短距离。
那么显然只有两条路,且路长之和是圆的周长。
首先,如果每次都是对中间所有相邻路长进行相加必然是会超时的,我们必须限制计算量。本质上可以将圈看成一段弯了的数轴,那么计算在 和 上 的出口距离时,只需比较 和 即可( 为圆周长)。而数轴上的坐标计算直接以第一个出口作为原点然后依次相加即可。
“The task is really simple.”
C ☺ D E
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> dist(n + 1);
dist[0] = 0;
for (int i = 1; i < n + 1; ++i)
{
cin >> dist[i];
dist[i] += dist[i - 1];
}
int m, a, b;
cin >> m;
for (int i = 0; i < m; ++i)
{
cin >> a >> b;
int d = dist[(a > b ? a : b) - 1] - dist[(a > b ? b : a) - 1];
if (d > dist[n] / 2)
cout << dist[n] - d << endl;
else
cout << d << endl;
}
}