1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 using namespace std; 7 const int maxn = 55555; 8 int sum[maxn << 2]; 9 void PushUp(int rt) 10 { 11 sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];//这个按位或就是+1的意思 12 } 13 14 void build(int l, int r, int rt)//建立线段树 15 { 16 if (l == r) 17 { 18 scanf("%d", &sum[rt]); 19 return; 20 } 21 int m = (l + r) >> 1;//相当于加1除以2 22 build(l, m, rt << 1); 23 build(m + 1, r, rt << 1 | 1); 24 PushUp(rt); 25 } 26 27 void update(int p, int add, int l, int r, int rt) 28 { 29 if (l == r) 30 { 31 sum[rt] += add; 32 return; 33 } 34 int m = (l + r) >> 1; 35 if (p <= m) update(p, add, l, m, rt << 1); 36 else update(p, add, m + 1, r, rt << 1 | 1); 37 PushUp(rt); 38 } 39 40 int query(int ll, int rr, int l, int r, int rt)//查询线段树 41 { 42 if (ll <= l && rr >= r) return sum[rt]; 43 int m = (l + r) >> 1; 44 int ret = 0; 45 if (ll <= m) ret += query(ll, rr, l, m, rt << 1); 46 if (rr > m) ret += query(ll, rr, m + 1, r, rt << 1 | 1); 47 return ret; 48 } 49 50 int main() 51 { 52 int t, c; 53 char d[10]; 54 scanf("%d", &t); 55 for (c = 1; c <= t; c++) 56 { 57 printf("Case %d:\n", c); 58 int n; 59 scanf("%d", &n); 60 build(1, n, 1); 61 while (scanf("%s", d) != EOF) 62 { 63 if (d[0] == ‘E‘) break; 64 int x, y; 65 scanf("%d%d", &x, &y); 66 if (d[0] == ‘Q‘) 67 { 68 int ans = query(x, y, 1, n, 1); 69 printf("%d\n", ans); 70 } 71 if (d[0] == ‘S‘) update(x, -y, 1, n, 1); 72 if (d[0] == ‘A‘) update(x, y, 1, n, 1); 73 } 74 } 75 return 0; 76 }
原文:http://www.cnblogs.com/xingkongyihao/p/6523348.html