首页 > 代码库 > 【HDOJ】1166 敌兵布阵

【HDOJ】1166 敌兵布阵

线段树。

 1 #include <stdio.h>
 2 
 3 #define maxn 55555
 4 
 5 int sums[maxn<<2];
 6 
 7 void PushUP(int rt) {
 8     sums[rt] = sums[rt<<1] + sums[rt<<1|1];
 9 }
10 
11 void build(int l, int r, int rt) {
12     int m;
13     if (l == r) {
14         scanf("%d", &sums[rt]);
15         return ;
16     }
17     m = (l+r)>>1;
18     build(l, m, rt<<1);
19     build(m+1, r, rt<<1|1);
20     PushUP(rt);
21 }
22 
23 void update(int des, int delta, int l, int r, int rt) {
24     int m;
25     if (l == r) {
26         sums[rt] += delta;
27         return ;
28     }
29     m = (l+r)>>1;
30     if (des <= m)
31         update(des, delta, l, m, rt<<1);
32     else
33         update(des, delta, m+1, r, rt<<1|1);
34     PushUP(rt);
35 }
36 
37 int query(int ll, int rr, int l, int r, int rt) {
38     int m, val = 0;
39     if (ll<=l && rr>=r)
40         return sums[rt];
41 
42     m = (l+r)>>1;
43     if (ll <= m)
44         val += query(ll, rr, l, m, rt<<1);
45     if (m < rr)
46         val += query(ll, rr, m+1, r, rt<<1|1);
47 
48     return val;
49 }
50 
51 int main() {
52     int case_n, n;
53     char cmd[10];
54     int i, j, k;
55 
56     scanf("%d", &case_n);
57 
58     for (k=1; k<=case_n; ++k) {
59         scanf("%d", &n);
60         build(1, n, 1);
61         printf("Case %d:\n", k);
62         while (1) {
63             scanf("%*c%s", cmd);
64             if (cmd[0] == E)
65                 break;
66             scanf("%d %d", &i, &j);
67             if (cmd[0] == Q)
68                 printf("%d\n", query(i,j,1,n,1));
69             else if (cmd[0] == A)
70                 update(i, j, 1, n, 1);
71             else
72                 update(i, -j, 1, n, 1);
73         }
74     }
75 
76     return 0;
77 }