标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166
线段树中对某一点的值进行改变;
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #define N 50010 #define Lson r<<1 #define Rson r<<1|1 struct SegmentTree { int L, R, k, sum; int Mid() { return (L+R)>>1; } int len() { return R-L+1; } }a[N<<2]; void BuildTree(int r,int L,int R) { a[r].L = L; a[r].R = R; a[r].k = 0; if(L == R) { scanf("%d",&a[r].sum); return ; } BuildTree(Lson, L, a[r].Mid()); BuildTree(Rson, a[r].Mid()+1, R); a[r].sum = a[Lson].sum + a[Rson].sum; } int Query(int r, int L, int R) { if(a[r].R == R && a[r].L == L) return a[r].sum; if(L>a[r].Mid()) return Query(Rson, L, R); else if(R <= a[r].Mid()) return Query(Lson, L, R); else { int sum1=Query(Lson, L, a[r].Mid()); int sum2=Query(Rson, a[r].Mid()+1, R); return sum1 + sum2; } } void Update(int r, int p, int x) { if(a[r].L == p && a[r].R == p) { a[r].sum += x; return ; } if(p<=a[r].Mid()) Update(Lson, p, x); else Update(Rson, p, x); a[r].sum = a[Rson].sum + a[Lson].sum; } int main() { int t=1, T, n, L, R, p, x; char s[10]; scanf("%d", &T); while(T--) { scanf("%d", &n); BuildTree(1, 1, n); printf("Case %d:\n", t++); while(scanf("%s", s)) { if(s[0] == ‘E‘)break; else if(s[0] == ‘Q‘) { scanf("%d %d", &L, &R); printf("%d\n", Query(1, L, R)); } else if(s[0] == ‘A‘) { scanf("%d%d", &p,&x); Update(1, p, x); } else if(s[0] == ‘S‘) { scanf("%d %d", &p, &x); Update(1, p, -x);//减去一个数可以看做加一个负数; } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/zhengguiping--9876/p/4690246.html