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> #include<math.h> int a[50005]; int n; int lowbit(int t) { return t&(-t); } void insert(int t,int d) { while(t<=n) { a[t]+=d; t+=lowbit(t); } } int getsum(int t) { int sum=0; while(t>0) { sum+=a[t]; t-=lowbit(t); } return sum; } int main() { int T,i,j,k,t; scanf("%d",&T); t=0; while(T--) { memset(a,0,sizeof(a)); scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&k); insert(i,k); } char str[10]; scanf("%s",str); printf("Case %d:\n",++t); while(str[0]!='E') { int x,y; scanf("%d%d",&x,&y); if(str[0]=='Q') printf("%d\n",getsum(y)-getsum(x-1)); else if(str[0]=='A') insert(x,y); else if(str[0]=='S') insert(x,(-1)*y); scanf("%s",str); } } return 0; }
线段树:
#include<iostream> #include<cstring>] #include<cstdio> using namespace std; struct Node { int left,right; int sum; }node[4*50005]; int a[50005]; void build(int l,int r,int i) { node[i].left=l; node[i].right=r; if(l==r) { node[i].sum=a[l]; return ; } int m=(l+r)/2; build(l,m,i*2); build(m+1,r,i*2+1); node[i].sum=node[i*2].sum+node[i*2+1].sum; } void update(int i,int x,int y) { int l=node[i].left; int r=node[i].right; int m=(l+r)/2; if(x==l && x==r) { node[i].sum += y; return ; } if(x<=m) update(i*2,x,y); else update(i*2+1,x,y); node[i].sum += y; } int query(int l,int r,int i) { if(node[i].left==l && node[i].right==r) return node[i].sum; //if(node[i].left==node[i].right) //return 0; int m=(node[i].left+node[i].right)/2; if(r<=m) return query(l,r,i*2); else if(l>m) return query(l,r,i*2+1); else return query(l,m,i*2)+query(m+1,r,i*2+1); } int main() { int T; scanf("%d",&T); for(int k=1;k<=T;k++) { memset(a,0,sizeof(a)); int i,n; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&a[i]); build(1,n,1); char str[10]; int x,y; printf("Case %d:\n",k); scanf("%s",str); while(str[0]!='E') { scanf("%d%d",&x,&y); if(str[0]=='Q') printf("%d\n",query(x,y,1)); else if(str[0]=='A') update(1,x,y); else update(1,x,-y); scanf("%s",str); } } return 0; }
原文:http://blog.csdn.net/hyccfy/article/details/38397563