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
分析:
这题主要描述了一个环形高速路,有N个出口,告诉你的是相邻出口之间距离,问你的是任意两个出口间的最短距离。
注意到,求反向距离只要用圆周长减去正向距离就可以了(有点地球是个圆的意思)。比较短的那个就是结果。
避坑:我做的时候完全按照题设数组D,后面求两点距离的时候用for求,遇到了TLE。原因是嵌套了一个for。所以设一个数组dis存储阶段和(距离),起点是1,避免嵌套。for里面用scanf或cin都可以,当时为了解决超时,以为是cin比scanf慢的缘故所以把for里的cin都改了。
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int M,N,dis[100001],D,a,b,tmp,sum,distance;
cin>>N;
sum=0;
for(int i=1;i<=N;i++){//提前求和并保存,以减少可能的循环嵌套
scanf("%d",&D);
sum+=D;
dis[i]=sum;
}
cin>>M;
for(int j=0;j<M;j++){
distance=0;
scanf("%d%d",&a,&b);
if(a>b){
tmp=a;
a=b;
b=tmp;
}
distance+=dis[b-1]-dis[a-1];
cout<<(distance*2<sum?distance:sum-distance)<<endl;
}
return 0;
}