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 D1D2 ... 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 <iostream>
  2. #include <vector>
  3. #include <stdio.h>
  4. #pragma warning(disable:4996)
  5. using namespace std;
  6. vector<int> num;
  7. int main(void) {
  8. int n,sum = 0;
  9. cin >> n;
  10. for (int i = 0; i < n; i++) {
  11. int roadtemp;
  12. scanf("%d", &roadtemp);
  13. sum += roadtemp;
  14. num.push_back(sum);
  15. }
  16. int m;
  17. cin >> m;
  18. for (int i = 0; i < m; i++) {
  19. int start, end, change;
  20. // cin >> start >> end;
  21. scanf("%d %d", &start, &end);
  22. if (start > end) {
  23. change = end;
  24. end = start;
  25. start = change;
  26. }
  27. int road = 0;
  28. if (start == 1) {
  29. road = num[end-2];
  30. }
  31. else {
  32. road = num[end-2] - num[start-2];
  33. }
  34. if (road > num[n-1] - road)
  35. road = num[n-1] - road;
  36. //cout << road << endl;
  37. printf("%d\n", road);
  38. }
  39. return 0;
  40. }





posted @ 2015-12-06 10:58  白夜行zz  阅读(140)  评论(0)    收藏  举报