pat Shortest Distance (20)
阿新 • • 發佈:2018-11-21
題目描述:
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 }