标签:线段树
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<cstdio> #include<cstring> #include<iostream> #include<string> #include<algorithm> using namespace std; #define lson l, mid, root<<1 #define rson mid+1, r, root<<1|1 const int N = 50000 + 20; struct node { int l, r, sum; } a[N<<2]; void PushUp(int root) //把当前节点的信息更新到父节点 { a[root].sum = a[root<<1].sum + a[root<<1|1].sum; } void build_tree(int l, int r, int root) { a[root].l = l; a[root].r = r; if(l == r) { scanf("%d",&a[root].sum); return ; } int mid = (l + r) >> 1; build_tree(lson); build_tree(rson); PushUp(root); } void update(int l, int r, int root, int k) { if(l == a[root].l && r == a[root].r) { a[root].sum += k; return ; } int mid = (a[root].l + a[root].r) >> 1; if(r <= mid) update(l, r, root<<1, k); else if(l > mid) update(l, r, root<<1|1, k); else { update(lson, k); update(rson, k); } PushUp(root); } int Query(int l, int r, int root) { if(l == a[root].l && r == a[root].r) return a[root].sum; int mid = (a[root].l + a[root].r) >> 1; int ans = 0; if(r <= mid) ans += Query(l, r, root<<1); else if(l > mid) ans += Query(l, r, root<<1|1); else ans += Query(lson) + Query(rson); return ans; } int main() { int T, n, l, r, cas = 0; string op; scanf("%d",&T); while(T--) { scanf("%d",&n); build_tree(1, n, 1); printf("Case %d:\n", ++cas); while(cin >> op) { if(op == "End") break; if(op == "Query") { scanf("%d%d",&l,&r); printf("%d\n", Query(l, r, 1)); } else if(op == "Add") { scanf("%d%d",&l, &r); update(l, l, 1, r); } else if(op == "Sub") { scanf("%d%d",&l,&r); update(l, l, 1, -r); } } } return 0; }
hdu 1166 敌兵布阵(线段树之 单点更新+区间求和),布布扣,bubuko.com
标签:线段树
原文地址:http://blog.csdn.net/lyhvoyage/article/details/38412737