1. 程式人生 > >甲級PAT 1046 Shortest Distance (20 分)(動態規劃)

甲級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 D​1​​ D​2​​ ⋯ D​N​​, where D​i​​ is the distance between the i-th and the (i+1)-st exits, and D​N​​ 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 10​7​​.

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;
}