PAT (Advanced Level) Practice 1046 Shortest Distance (20 分)(C++)(甲級)

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 D2⋯ DN​​ , 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



//本題感覺有點崩,做了半下午……瘋狂拉低通過率
//一個環,給環上兩點算最短路徑長度,即順時針和逆時針的路徑長度最小值
//我們只需計算其中一個方向上的,然後用環的總長度減去它,即得逆向的長度
//時間複雜度有要求,總的時間複雜度是O(N)吧,之前寫了兩三個算法,都是最後一個測試點超時

#include <cstdio>
#include <cstring>
#include <cmath>

int D[100001] = { 0 };//各地點間的距離

int main()
{
	int N = 0, M = 0;
	scanf("%d", &N);
	for (int i = 1, dis = 0; i <= N; i++)
	{
		scanf("%d", &dis);
		D[i] += D[i - 1] + dis;//累加路程長度
	}
	scanf("%d", &M);
	for (int i = 0; i < M; i++)
	{
		int a = 0, b = 0, path1 = 0, path2 = 0;
		scanf("%d %d", &a, &b);
		if (a > b) path1 = D[a-1] - D[b-1];//先計算出正向的長度;這裏很巧妙
		else path1 = D[b-1] - D[a-1];
		path2 = D[N] - path1;//反向長度即總長度減去正向的長度(環形)
		printf("%d\n", path1 < path2 ? path1 : path2);//輸出較小者即可
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章