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
后来百度了下别人的做法,http://www.2cto.com/kf/201311/254357.html,感觉很受用,我的问题就在于没有在输入的时候就存储从1开始到各点之间的距离值,导致后来还要用for循环计算temp。如果顶点数n值很大的话,似乎确实很耗时。
自己错误在:我用数组存储相邻边的距离,如1-2的距离,2-3的距离,3-4的距离等,而不是1-2,1-3,1-4的距离,导致后来需要使用for循环累加求解temp。
下面贴上代码:
#include<iostream> #include<cstdlib> #include<cstdio> #include<cmath> using namespace std; int main() { int n,m; //n表示边数,m表示求最短路的测试个数 while(cin>>n) { int *a=new int[n+3]; //动态生成 int temp=0; //临时存储边值,初始化 int sum=0; //所有边值之和,初始化 a[1]=0; for(int i=1;i<=n;i++) { cin>>temp; sum+=temp; a[i+1]=a[i]+temp; } cin>>m; int beg,en; //起点beg和终点en for(int i=1;i<=m;i++) { cin>>beg>>en; temp=abs(a[beg]-a[en]); cout<<min(temp,sum-temp)<<endl; } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。