题目描述:
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.
输入描述:
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.
输出描述:
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
输入例子:
5 1 2 4 14 9
3
1 3
2 5
4 1
输出例子:
3
10
7
思路:
题目给了我们N个点之间的距离,这N个点构成了一个环,求给出的几组点之间的最短距离。
一开始我想到的是建立一个N*2的数组,每行表示一个点到上个点和下个点的距离,但后来发现由于这是一个环,所以两点之间有两种走法,只要求出其中一种的距离,即可得另
一个。有了这个想法,写出了很粗糙的第一版
1 #include <iostream>
2 using namespace std;
3
4 int f(int a,int b,int array[],int sum){ //判断两点之间,哪条路径短
5 int m,n,left=0,right=0; //right->从较小序号点向较大序号点的距离,left->另一条路径距离
6 if(a-1<b-1){ //防止a点的序号比b点大
7 m=a-1;
8 n=b-1;
9 }else{
10 m=b-1;
11 n=a-1;
12 }
13 for(int i=m;i<n;++i)
14 {
15 right+=array[i];
16 }
17 left=sum-right;
18 return left<right?left:right;
19 }
20
21 int main()
22 {
23 int N;
24 cin>>N;
25 int array_1[N],sum=0; //array_1->存放每个点到下个点的距离,sum->保存距离和
26 for(int i=0;i<N;++i)
27 {
28 cin>>array_1[i];
29 sum+=array_1[i];
30 }
31 int M; //M->共M组点
32 cin>>M;
33 int array_2[M][2];
34 for(int i=0;i<M;++i)
35 {
36 cin>>array_2[i][0]>>array_2[i][1];
37 }
38 for(int i=0;i<M;++i)
39 {
40 cout<<f(array_2[i][0],array_2[i][1],array_1,sum)<<endl;
41 }
42 }