题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=1166
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
AC代码:
#include<stdio.h> #include<string.h> #include<iostream> #define max(a,b) return a>b?a:b #define min(a,b) return a<b?a:b using namespace std; int value[50010]; struct Node { int L,R; int sum; }; Node tree[150010]; void buildtree(int L,int R,int root) { tree[root].L=L; tree[root].R=R; if(L==R) { tree[root].sum=value[L]; return; } buildtree(L,(L+R)/2,root*2); buildtree((L+R)/2+1,R,2*root+1); tree[root].sum=tree[2*root].sum+tree[2*root+1].sum; } void add(int id,int num,int root) { if(tree[root].L==tree[root].R) { tree[root].sum=tree[root].sum+num; return; } else{ tree[root].sum=tree[root].sum+num; if(id<=tree[root*2].R) add(id,num,2*root); else add(id,num,2*root+1); } } int query(int left,int right,int root) { if(tree[root].L==left&&tree[root].R==right) return tree[root].sum; int mid; mid=(tree[root].L+tree[root].R)/2; if(right<=mid) return query(left,right,2*root); else if(left>mid) return query(left,right,2*root+1); else return query(left,mid,2*root)+query(mid+1,right,2*root+1); } int main() { int Case; int n; char str[10]; scanf("%d",&Case); int id,num; int i; int k=1; while(Case--) { scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&value[i]); } buildtree(1,n,1); printf("Case %d:\n",k++); while(1) { scanf("%s",str); if(strcmp(str,"End")==0) break; scanf("%d%d",&id,&num); if(strcmp(str,"Query")==0) { printf("%d\n",query(id,num,1)); } if(strcmp(str,"Add")==0) { //scanf("%d%d",&id,&num); add(id,num,1); } if(strcmp(str,"Sub")==0) { //scanf("%d%d",&id,&num); add(id,-num,1); } } } return 0; }