1. 程式人生 > 其它 >JavaScript 10.25

JavaScript 10.25

1. 題目

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 (≤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

2. 題意

有一條環形公路上n個站點,題目給出了相鄰兩個站點之間的距離,計算任意兩個站點之間的最短距離。

3. 思路——字首和

  1. 建立兩個陣列:dist中表示i到i+1的距離;sum為字首和,表示從1到i的距離。
  1. 計算兩個站點之間距離,兩個站點分別為x,y;這裡保證x<y(判斷大小,如果x>y,則兩個數交換即可),然後計算”x到y的距離“和“y到x的距離”:
    1. (x到y的距離)=(1到y的距離sum[y])-(1到x的距離sum[x])
    2. (y到x的距離)=(y到n的距離sum[n]-sum[y])+(y到1的距離dist[y])+(1到x的距離dist[x])
  2. 比較(x到y的距離)和(x到y的距離),兩個中的較小值為x和y之間的最短距離。

4. 程式碼

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

int main()
{
	LL n;
	cin >> n;
	LL dist[n + 1];	// 表示從i到(i+1)的距離 
	LL sum[n + 1];	// 字首和,表示從1到i的距離
	memset(dist, 0, sizeof dist);
	memset(sum, 0, sizeof sum);
	for (int i = 1; i <= n; ++i)
	{
		cin >> dist[i];
		// 字首和計算,(1到i的距離)=(1到i-1的距離)+(i-1到i的距離) 
		sum[i] += sum[i - 1] + dist[i - 1];
	}
	
	int m;
	cin >> m;
	int x, y;
	for (int i = 0; i < m; ++i)
	{
		cin >> x >> y;
		if (x > y) swap(x, y);	// 如果x座標大於y,則交換兩個數
		// x到y的距離 
		int dist1 = sum[y] - sum[x];
		// y到x的距離(因為公路為迴圈)=(y到n的距離)+(y到1的距離dist[n])+(1到x的距離sum[x]) 
		int dist2 = sum[n] - sum[y] + dist[n] + sum[x];
		// 判斷(x到y的距離)和(y到x的距離)大小,輸出距離較小值 
		cout << (dist1 < dist2 ? dist1 : dist2) << endl;
	}
	return 0;
}