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 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
#include <iostream>
#include <algorithm>
using namespace std;
const int maxN = 100005;
int dis[maxN]; //dis[i] 代表着 1号出口到第 i 个出口的 下一个出口的距离 (顺时针)
int main(){
int n, distance; //n出口个数, distance是i号与i+1号出口之间的距离(用一个数组来保存会更加清晰,但这样可以省去开辟一块数组的内存)
cin >> n;
int sum = 0; //一圈的总距离
for(int i = 1; i <= n; i++){
cin >> distance;
sum += distance; //累加sum
dis[i] = sum; //没累加一次 就是1号出口 到 第i个出口的 下一个出口的距离
}
int m, left, right;
cin >> m;
for(int i = 0; i < m; i++){
cin >> left >> right;
if(left > right) swap(left, right); //要保证left 小于 right
//dis[right - 1]那就是 1号到right号的距离 dis[left - 1]同理
//那么left 到 right 之间的距离 不就是 1到right 减去 1到left的距离嘛
//当然这是只考虑了顺时针的情况
int temp = dis[right - 1] - dis[left - 1];
cout << min(temp, sum - temp) << endl; //那么逆时针好说啊,直接sum - temp 总距离减去顺时针之间的距离 那不就是逆时针之间的距离嘛。
/*
另外,这道题是输入一行输出一行,并不是像之前在最后把所有结果一并输出
pat应该是只要每输出一行 保证这一行的格式结果正确就是对的
类似将结果输出的 一个文档之中 你可以输入过程中 一行一行读进去
也可以输入完毕后 在最后一并将结果 读进去~~~ 个人理解,或许有错误吧QAQ
*/
}
return 0;
}