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, 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 (<=104), 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 107.

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 #include <cstdio>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int exitDst[100000];
 7 int sumDst[100001];
 8 
 9 int main()
10 {
11     int exitNum, totalDst=0;
12     cin >> exitNum;
13     for (int i = 0; i < exitNum; i++)
14         scanf("%d", &exitDst[i]);
15     for (int i = 1; i < exitNum; i++)
16         sumDst[i] = sumDst[i - 1] + exitDst[i - 1];
17     totalDst= sumDst[exitNum-1] + exitDst[exitNum-1];
18 
19     int queryNum;
20     cin >> queryNum;
21     for (int i = 0; i < queryNum; i++)
22     {
23         int start, end, Dst=0;
24         scanf("%d%d", &start, &end);
25         Dst = sumDst[end - 1] - sumDst[start - 1];
26         Dst = Dst >0 ? Dst : -Dst;
27         if (totalDst - Dst < Dst)
28             printf("%d\n", totalDst - Dst);
29         else
30             printf("%d\n", Dst);
31     }
32 }

 

posted @ 2015-08-11 18:59  JackWang822  阅读(176)  评论(0编辑  收藏  举报