甲级PAT 1046 Shortest Distance (20 分)(动态规划)
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,10^5]), 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 (≤10^4), 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 1
Sample Output:
3
10
7
题目要求:
有N个出站口,他们之间是呈环形连通。给出每两个出站口之间的距离,求两个出站口之间的最小距离。
第一行分别是,N,D1,D2……Di,表示第i个出站口到第i+1个出站口的距离.
解题思路:
由于这里是一个环形,因此从一个出站口到另一个出站口无非两条路径,一个是顺时针,一个是逆时针。两个方向的距离之和为整个环的长度。
用一个数组dis[i]来存储第i+1个出口到第一个出口的距离,这样任意两个出口i,j之间的距离可用dis[j - 1] - dis[i - 1] (j > i)来表示。此时另一条路径的距离用dis[N] - (dis[j - 1] - dis[i - 1] )。最后输出两条路径距离小的那个就可以了。
对于j < i的情况可以首先交换两个的位置用上述公式,因为都是要求两条路径,先求哪个都一样。
随手画了一个比较丑的图。。凑合理解。
完整代码:
#include<iostream>
#include<cstring>
using namespace std;
int main(){
int i,N,M,d,a,b,r1,r2;
int dis[100010];
cin >> N;
memset(dis,0,sizeof(dis));
for(i = 1; i <= N; i++){
cin >> d;
dis[i] = dis[i-1] + d;
}
cin >> M;
for(i = 1; i <= M; i++){
cin >> a >> b;
if(a > b) swap(a,b);
r1 = dis[b-1] - dis[a-1];
r2 = dis[N] - r1;
cout<<min(r1,r2)<<endl;
}
return 0;
}