HDU1166 敌兵布阵

解题思路:线段树模板题,好久没写线段树了,练练手,发现不像以前那么迷茫了,

    脑海中已经可以有清晰的图像了。这样,比较科学。上代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 #define lson l,m,rt<<1
 6 #define rson m+1,r,rt<<1 | 1
 7 const int maxn = 50005;
 8 int A[maxn<<2], t, n, kase = 1;
 9 char str[10];
10 
11 void Sum(int rt)
12 {
13     A[rt] = A[rt<<1] + A[rt<<1 | 1];
14 }
15 
16 void Build(int l, int r, int rt)
17 {
18     if(l == r)
19     {
20         scanf("%d", &A[rt]);
21         return ;
22     }
23     int m = (l + r) >> 1;
24     Build(lson);
25     Build(rson);
26     Sum(rt);
27 }
28 
29 void Update(int p, int add, int l, int r, int rt)
30 {
31     if(l == r)
32     {
33         A[rt] += add;
34         return ;
35     }
36     int m = (l + r) >> 1;
37     if(p <= m) Update(p, add, lson);
38     else Update(p, add, rson);
39     Sum(rt);
40 }
41 
42 int Query(int ll, int rr, int l, int r, int rt)
43 {
44     if(ll <= l && rr >= r) return A[rt];
45     int m = (l + r) >> 1;
46     int ret = 0;
47     if(ll <= m) ret += Query(ll, rr, lson);
48     if(rr > m) ret += Query(ll, rr, rson);
49     return ret;
50 }
51 
52 
53 
54 int main()
55 {
56     int a, b;
57     scanf("%d", &t);
58     while(t--)
59     {
60         scanf("%d", &n);
61         Build(1, n, 1);
62         printf("Case %d:\n",kase++);
63         while(1)
64         {
65             scanf("%s", str);
66             if(str[0] == 'E') break;
67             if(str[0] == 'Q')
68             {
69                 scanf("%d %d", &a, &b);
70                 int ans = Query(a, b, 1, n, 1);
71                 printf("%d\n", ans);
72             }
73             if(str[0] == 'A')
74             {
75                 scanf("%d %d", &a, &b);
76                 Update(a, b, 1, n, 1);
77             }
78             if(str[0] == 'S')
79             {
80                 scanf("%d %d", &a, &b);
81                 Update(a, -b, 1, n, 1);
82             }
83         }
84     }
85     return 0;
86 }
View Code

 

posted on 2015-10-27 23:35  改写历史,倾尽天下  阅读(144)  评论(0编辑  收藏  举报

导航