标签:
#include<stdio.h> #include<string.h> #define N 50010 int A[N]; struct node { int left, right, sum; } no[4*N]; //存放左端点,右端点,和 void Bulid(int left, int right, int root) //建立线段树 { int mid; no[root].left = left; no[root].right = right; if (left == right) { no[root].sum = A[left]; return ; } mid = (left+right)/2; Bulid(left, mid, 2*root); Bulid(mid+1, right, 2*root+1); no[root].sum = no[2*root].sum + no[2*root+1].sum; } int Query(int left, int right, int root) //查找左端点到右端点的和 { int mid; if (no[root].left == left && no[root].right == right) return no[root].sum; mid = (no[root].left+no[root].right)/2; if (right <= mid) return Query(left, right, root*2); else if (left > mid) return Query(left, right, root*2+1); else return Query(left, mid, root*2)+Query(mid+1, right, root*2+1); } void Update(int k, int num, int root) //更新sum中的值 { if (no[root].left == no[root].right) { no[root].sum += num; return ; } else { no[root].sum += num; if (k <= no[root*2].right) Update(k, num, root*2); else Update(k, num, root*2+1); } } int main () { int T, n, i, L, R, Sum, num, k, ans = 0; char s[10]; scanf("%d", &T); while (T--) { ans++; scanf("%d", &n); for (i = 1; i <= n; i++) scanf("%d", &A[i]); Bulid(1, n, 1); printf("Case %d:\n", ans); while (scanf("%s", s), strcmp(s, "End")) { if (s[0] == ‘Q‘) { scanf("%d%d", &L, &R); Sum = Query(L, R, 1); printf("%d\n", Sum); } else { scanf("%d%d", &k, &num); if (s[0] == ‘A‘) Update(k, num, 1); else if (s[0] == ‘S‘) Update(k, -num, 1); } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/syhandll/p/4689336.html