【POJ】3468 A Simple Problem with Integers

线段树。段区间,终于完全自己A掉的。

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 #define MAXN 100005
 5 #define lson l, mid, rt<<1
 6 #define rson mid+1, r, rt<<1|1
 7 
 8 __int64 sums[MAXN<<2];
 9 __int64 adds[MAXN<<2];
10 
11 inline void PushUP(int rt) {
12     sums[rt] = sums[rt<<1] + sums[rt<<1|1];
13 }
14 
15 inline void PushDown(int len, int rt) {
16     if ( adds[rt] ) {
17         adds[rt<<1] += adds[rt];
18         adds[rt<<1|1] += adds[rt];
19         sums[rt<<1|1] += adds[rt] * (len>>1);
20         sums[rt<<1] += adds[rt] * (len-(len>>1));
21         adds[rt] = 0;
22     }
23 }
24 
25 void build(int l, int r, int rt) {
26     int mid;
27     adds[rt] = 0;
28     if (l == r) {
29         scanf("%I64d", &sums[rt]);
30         return ;
31     }
32     mid = (l+r)>>1;
33     build(lson);
34     build(rson);
35     PushUP(rt);
36 }
37 
38 void update(int ll, int rr, int c, int l, int r, int rt) {
39     int mid;
40     if (ll<=l && rr>=r) {
41         sums[rt] += c*(r-l+1);
42         adds[rt] += c;
43         return ;
44     }
45     PushDown(r-l+1, rt);
46     mid = (l+r)>>1;
47     if (ll <= mid)
48         update(ll, rr, c, lson);
49     if (rr > mid)
50         update(ll, rr, c, rson);
51     PushUP(rt);
52 }
53 
54 __int64 query(int ll, int rr, int l, int r, int rt) {
55     int mid;
56     __int64 ret = 0;
57     if (ll<=l && rr>=r)
58         return sums[rt];
59     PushDown(r-l+1, rt);
60     mid = (l+r)>>1;
61     if (ll <= mid)
62         ret += query(ll, rr, lson);
63     if (rr > mid)
64         ret += query(ll, rr, rson);
65     //PushUP(rt);
66     return ret;
67 }
68 
69 int main() {
70     int n, m;
71     int x, y, c;
72     char cmd[3];
73 
74     while (scanf("%d %d", &n, &m) != EOF) {
75         build(1, n, 1);
76 
77         while (m--) {
78             scanf("%s %d %d", cmd, &x, &y);
79             if (cmd[0] == 'C') {
80                 scanf("%d", &c);
81                 update(x,y,c,1,n,1);
82             } else {
83                 printf("%I64d\n", query(x,y,1,n,1));
84             }
85         }
86     }
87 
88     return 0;
89 }

 

posted on 2014-06-03 12:20  Bombe  阅读(171)  评论(0编辑  收藏  举报

导航