题目
The task is really simple: given N exits on a highway which forms a simplecycle, you are supposed to tell the shortest distance between any pair ofexits.
Input Specification:
Each input file contains one test case. For each case, the first linecontains an integer N (in [3, 105]), followed by N integer distancesD1 D2 ... DN, where Di is thedistance between the i-th and the (i+1)-st exits, and DN is betweenthe 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 linesfollow, each contains a pair of exit numbers, provided that the exits arenumbered from 1 to N. It is guaranteed that the total round trip distance is nomore than 107.
Output Specification:
For each test case, print your results in M lines, each contains theshortest 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
保存各个点到原点的距离(不考虑环)。
任意两个点间的距离即为min(这个距离的差,总距离减这个距离)
代码:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,*dis,tot_dis=0,temp; //数量,各个点到原点的距离(不考虑环),总距离,临时数据
int i;
cin>>n;
dis=new int[n];
for(i=0;i<n;i++) //输入距离,转换为到第一个点的总距离(不考虑环)
{
dis[i]=tot_dis;
scanf("%d",&temp);
tot_dis+=temp;
}
int m;
cin>>m;
int c1,c2,d_dis;
for(i=0;i<m;i++) //输入测试数据
{
scanf("%d",&c1);
scanf("%d",&c2);
if(c1>c2)
swap(c1,c2);
d_dis=dis[c2-1]-dis[c1-1]; //计算差值
if(tot_dis-d_dis<d_dis) //考虑环线
d_dis=tot_dis-d_dis;
printf("%d\n",d_dis);
}
delete [] dis;
return 0;
}