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,10
的五次方 ]), 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 (≤10的四次方 ), 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次方 .
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
AC代码如下:
#include <stdio.h>
const int MAXN = 100010;
//dis[i]表示1号节点按顺时针方向到达i号节点的顺时针方向的下一个节点的距离
//A[i]表示i号与i+1号顶点的距离
int main(int argc, char *argv[]) {
int dis[MAXN],A[MAXN];
int sum = 0,query,n,i,t,left,right,temp;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&A[i]);
sum+=A[i]; //累加sum
dis[i]=sum; //预处理dis数组
}
scanf("%d",&query);
for(i=0;i<query;i++){ //query个查询
scanf("%d%d",&left,&right);
if(left>right){ //防止left>right
t=left;
left=right;
right=t;
}
temp=dis[right-1]-dis[left-1];
if(temp<(sum-temp)){
printf("%d\n",temp);
}
else{
printf("%d\n",sum-temp);
}
}
return 0;
}
注意:
1.不能使用暴力无脑算法,那样做会超时。
2.dis[i]表示1号节点按顺时针方向到达i号节点的顺时针方向的下一个节点的距离
3.A[i]表示i号与i+1号顶点的距离
4.dis数组和sum在读入的时候就可以累加得到,这样查询的时候其实就是dis[right-1]-[left-1],这样可以减少算法的时间复杂度。