标签:线段树
1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Case 1: 6 33 59
#include <stdio.h> #include <string.h> struct node { int l, r; int sum; }tree[2000005]; int h[50005]; int sum; void build(int l, int r, int n) //建树 { int mid; tree[n].l = l; tree[n].r = r; if(l==r) { tree[n].sum = h[l]; return ; } mid = (l+r)>>1; build(l, mid, 2*n); build(mid+1, r, 2*n+1); tree[n].sum = tree[2*n].sum + tree[2*n+1].sum; } void add(int a, int b, int n) //计算 { int mid; if(tree[n].l == a && tree[n].r == a) { tree[n].sum += b; //单点时 return ; } mid = (tree[n].l + tree[n].r)>>1; if(mid >= a) { tree[n].sum += b; //区间值应更新 add(a, b, 2*n); } else if(mid < a) { tree[n].sum += b; add(a, b, 2*n+1); } } void query(int l, int r, int n) { int mid; if(tree[n].l==l && tree[n].r==r) { sum += tree[n].sum; return ; } mid = (tree[n].l + tree[n].r)>>1; if(mid >= r) query(l, r, 2*n); else if(mid < l) query(l, r, 2*n+1); else { query(l, mid, 2*n); query(mid+1, r, 2*n+1); } } int main() { int t; int n, i; char ch[20]; int a, b, flag=0; scanf("%d", &t); while(flag < t) { flag++; printf("Case %d:\n", flag); scanf("%d", &n); for(i=1; i<=n; i++) scanf("%d", &h[i]); build(1, n, 1); while(1) { scanf("%s", ch); if(strcmp(ch, "End")==0) break; scanf("%d%d", &a, &b); if(strcmp(ch, "Add")==0) { add(a, b, 1); } else if(strcmp(ch, "Sub")==0) { add(a, -b, 1); } else { sum = 0; query(a, b, 1); printf("%d\n", sum); } } } return 0; }
标签:线段树
原文地址:http://blog.csdn.net/ash_zheng/article/details/38067257