1046. Shortest Distance (20)
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 1Sample Output:
3 10 7
本題由於圖形簡單,任意兩點之間只有兩條路可以選擇,而且所有的點又組成了環,這兩條路徑的和總是等於環的周長,當輸入完畢時,我們就可以知道整個環的“周長”,同時在輸入時記錄每個點到起點(第一個點)的距離,測試時,用兩點到起點的距離相減就是兩點之間的距離dis,同時,用周長減去dis就是第二條路徑的長度,輸出兩者中較小者即可。
#include <cstdio>
using namespace std;
#define BIG 100001
int min(int a,int b){
if(a >= b)
return b;
else
return a;
}
int main(){
int sum = 0, toFirst[BIG];
int m,n,a,b,temp = 0,to;
scanf("%d",&n);
toFirst[1] = 0;
for (int i = 2; i <= n; ++i)
{
scanf("%d",&temp);
toFirst[i] = toFirst[i-1] + temp;//每個點到第一個點的距離
sum += temp;
}
scanf("%d",&temp);
sum += temp;//周長
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%d %d",&a,&b);
if(a > b){
a ^= b ^= a ^= b;//交換a和b的值
}
printf("%d\n", min(toFirst[b]-toFirst[a], sum-(toFirst[b]-toFirst[a]) ) );
}
return 0;
}