1. 程式人生 > >pat 1046 Shortest Distance(20 分) (線段樹)

pat 1046 Shortest Distance(20 分) (線段樹)

ns2 imp turn for lse struct any ner max

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,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 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4
#include <cstring> 5 #include <map> 6 #include <stack> 7 #include <vector> 8 #include <queue> 9 #include <set> 10 #define LL long long 11 using namespace std; 12 const int MAX = 4e5 + 10; 13 14 int N, D[MAX], pre[MAX], M, ans, a, b, ans2; 15 struct node 16 {
17 int L, R, val; 18 }P[MAX]; 19 20 void build(int dep, int l, int r) 21 { 22 P[dep].L = l, P[dep].R = r, P[dep].val = 0; 23 if (l == r) 24 { 25 pre[l] = dep; 26 return; 27 } 28 int mid = (l + r) >> 1; 29 build(dep << 1, l, mid); 30 build((dep << 1) + 1, mid + 1, r); 31 } 32 33 void update(int r, int b) 34 { 35 P[r].val += b; 36 if (r == 1) return ; 37 update(r >> 1, b); 38 } 39 40 void query(int dep, int l, int r) 41 { 42 if (P[dep].L == l && P[dep].R == r) 43 { 44 ans += P[dep].val; 45 return ; 46 } 47 int mid = (P[dep].L + P[dep].R) >> 1; 48 if (r <= mid) query(dep << 1, l, r); 49 else if (l > mid) query((dep << 1) + 1, l, r); 50 else 51 { 52 query(dep << 1, l, mid); 53 query((dep << 1) + 1, mid + 1, r); 54 } 55 } 56 57 int main() 58 { 59 // freopen("Date1.txt", "r", stdin); 60 scanf("%d", &N); 61 build(1, 1, N); 62 for (int i = 1; i <= N; ++ i) 63 { 64 scanf("%d", &D[i]); 65 update(pre[i], D[i]); 66 } 67 68 scanf("%d", &M); 69 while (M --) 70 { 71 ans = 0; 72 scanf("%d%d", &a, &b); 73 if (b < a) swap(a, b); 74 if (a == b - 1) ans += D[a]; 75 else query(1, a, b - 1); 76 ans2 = ans, ans = 0; 77 78 if (a - 1 == 1) ans += D[1]; 79 else if (a - 1 > 1) query(1, 1, a - 1); 80 if (b == N) ans += D[N]; 81 else query(1, b, N); 82 printf("%d\n", min(ans, ans2)); 83 } 84 return 0; 85 }

pat 1046 Shortest Distance(20 分) (線段樹)