pku3468 A Simple Problem with Integers
http://poj.org/problem?id=3468
线段树,成段更新
注意long long
1 #include <stdio.h> 2 3 #define lson l, m, root<<1 4 #define rson m+1, r, root<<1|1 5 #define N 100100 6 7 long long sum[N<<2], add[N<<2]; 8 9 void push_up(int root) 10 { 11 sum[root] = sum[root<<1] + sum[root<<1|1]; 12 } 13 14 void push_down(int root, int len) 15 { 16 if(add[root]) 17 { 18 add[root<<1] += add[root]; 19 add[root<<1|1] += add[root]; 20 sum[root<<1] += add[root] * (len - (len>>1)); 21 sum[root<<1|1] += add[root] * (len>>1); 22 add[root] = 0; 23 } 24 } 25 26 void build(int l, int r, int root) 27 { 28 int m; 29 add[root] = 0; 30 if(l == r) 31 { 32 scanf("%lld", sum+root); 33 return; 34 } 35 m = (l + r) >> 1; 36 build(lson); 37 build(rson); 38 push_up(root); 39 } 40 41 void update(int L, int R, int x, int l, int r, int root) 42 { 43 int m; 44 if(L <= l && r <= R) 45 { 46 add[root] += x; 47 sum[root] += (r-l+1)*(long long)x; 48 return; 49 } 50 push_down(root, r-l+1); 51 m = (l + r) >> 1; 52 if(L <= m) 53 { 54 update(L, R, x, lson); 55 } 56 if(m+1 <= R) 57 { 58 update(L, R, x, rson); 59 } 60 push_up(root); 61 } 62 63 long long query(int L, int R, int l, int r, int root) 64 { 65 int m; 66 long long result; 67 if(L <= l && r <= R) 68 { 69 return sum[root]; 70 } 71 push_down(root, r-l+1); 72 m = (l + r) >> 1; 73 result = 0; 74 if(L <= m) 75 { 76 result += query(L, R, lson); 77 } 78 if(m+1 <= R) 79 { 80 result += query(L, R, rson); 81 } 82 return result; 83 } 84 85 int main() 86 { 87 int n, q, a, b, c; 88 char c1; 89 scanf("%d%d", &n, &q); 90 build(1, n, 1); 91 getchar(); 92 while(q-- && scanf("%c%d%d%*c", &c1, &a, &b)) 93 { 94 if(c1 == 'C') 95 { 96 scanf("%d%*c", &c); 97 update(a, b, c, 1, n, 1); 98 continue; 99 } 100 printf("%lld\n", query(a, b, 1, n, 1)); 101 } 102 return 0; 103 }