1046 Shortest Distance

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]), followed by N integer distances D​1​​ D​2​​ ⋯ D​N​​, where D​i​​ is the distance between the i-th and the (-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 (≤), 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 1.

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

题意:

  给出由数字组成的环,以及环中相邻两点间的距离,求出任意两结点间的最小距离。

思路:

  任意两节点间的最小距离包括两种情况,即顺时针方向上有一个距离,逆时针方向上有一个距离。我们用两个数组sum1和sum2来分别存储由起点(1)开始依次向两个方向上的各个点的距离和。当求a, b两点间的最小距离的时候,我们只需要求min(sum1[a] - sum1[b], sum1[b] + sum2[a])即可(确保a > b)。

Code :

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 int main() {
 6     int n;
 7     cin >> n;
 8     vector<int> dist(n + 1, 0);
 9     vector<int> sum1(n + 1, 0);
10     vector<int> sum2(n + 1, 0);
11     for (int i = 1; i <= n; ++i) cin >> dist[i];
12     for (int i = 1; i <= n; ++i) sum1[i] = sum1[i - 1] + dist[i - 1];
13     for (int i = n; i >= 1; --i) {
14         if (i == n)
15             sum2[i] = dist[i];
16         else if (i == 1)
17             sum2[i] = 0;
18         else
19             sum2[i] = sum2[i + 1] + dist[i];
20     }
21     int m, a, b;
22     cin >> m;
23     for (int i = 0; i < m; ++i) {
24         cin >> a >> b;
25         if (a < b) swap(a, b);
26         int temp = min(sum1[a] - sum1[b], sum1[b] + sum2[a]);
27         cout << temp << endl;
28     }
29     return 0;
30 }
永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/12857298.html