PAT A1046 Shortest Distance

PAT A1046 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,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

 

参考代码:

 1 /***********************************************
 2 PAT A1046 Shortest Distance
 3 ***********************************************/
 4 #include <iostream>
 5 #include <algorithm>
 6 #include <vector>
 7 
 8 using namespace std;
 9 
10 int main() {
11     int n = 0, m = 0, sum = 0;
12     
13     cin >> n;
14 
15     vector<int> Distance(n + 1, 0);
16 
17     int temp = 0;
18     for (int i = 1; i <= n; ++i) {
19         cin >> temp;
20         sum += temp;
21         Distance[i] = sum;    //从0到i的距离
22     }
23 
24     cin >> m;
25     for (int i = 0; i < m; ++i) {
26         int beg = 0, end = 0, shortDist = 0;
27 
28         cin >> beg >> end;
29 
30         if (beg > end) swap(beg, end);
31 
32         shortDist = Distance[end - 1] - Distance[beg - 1];
33 
34         cout << (shortDist < Distance[n] - shortDist ? shortDist : Distance[n] - shortDist);
35 
36         if (i != m - 1) cout << endl;
37     }
38 
39     return 0;
40 }

 

注意事项:

  1:提前计算好从起始点到每个点之间的距离有利于后续的计算。

posted @ 2019-08-21 18:36  多半是条废龙  阅读(130)  评论(0)    收藏  举报