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
Sample Output:
3 10 7
环形图中求两点间最短距离。无非两条路,取最小即可。
注:distance 内置函数?
dis[i]表示1号结点按顺时针方向到达"i号结点顺时针方向的下一个结点"的距离
1 #include<cstdio> 2 #include <algorithm> //用到了swap(), min() 3 using namespace std; 4 5 const int MAXN=100005; 6 int dis[MAXN],A[MAXN]; 7 8 9 int main() 10 { 11 int n,left,right,query;int sum=0; 12 scanf("%d",&n); 13 for(int i=1;i<=n;i++)//输入数据并记录 14 { 15 scanf("%d",&A[i]);//依次输入各节点间距离 16 sum+=A[i]; //累加 17 dis[i]=sum; //累加一次得到一个 两节点间距离 18 } 19 printf("请输入你的查询次数"); 20 scanf("%d",&query); 21 for(int i=1;i<=query;i++) 22 { 23 printf("请输入查询的两个结点"); 24 scanf("%d%d",&left,&right); 25 if(left>right) swap(left,right); 26 int temp=dis[right-1]-dis[left-1]; 27 printf("the shortest distance:");printf("%d ",min(temp,sum-temp));//两个方向取最小即可 28 } 29 return 0; 30 }
运行结果: