标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 78528 Accepted Submission(s): 33171
#include<bits/stdc++.h> #define N 50010 using namespace std; int c[N]; int Case,n; int lowbit(int x) { return x&(-x); } void update(int x,int val) { while(x<=n) { c[x]+=val; x+=lowbit(x); } } int getsum(int x) { int s=0; while(x>0) { s+=c[x]; x-=lowbit(x); } return s; } int main() { //freopen("C:\\Users\\acer\\Desktop\\in.txt","r",stdin); scanf("%d",&Case); string op; for(int l=1;l<=Case;l++) { memset(c,0,sizeof c); printf("Case %d:\n",l); scanf("%d",&n); for(int i=1;i<=n;i++) { int cur; scanf("%d",&cur); update(i,cur); } while(true) { cin>>op; if(op=="End") break; int a,b; scanf("%d%d",&a,&b); if(op=="Add") update(a,b); else if(op=="Sub") update(a,-b); else if(op=="Query") printf("%d\n",getsum(b)-getsum(a-1)); } // for(int i=1;i<=n;i++) // cout<<c[i]<<" "; // cout<<endl; } }
#include<stdio.h> #include<string.h> const int MAXN=50010; struct Node { int l,r; int sum; }segTree[MAXN*3]; void Build(int i,int l,int r)//从节点1开始更新,也就是从树的根节点开始更新,直到左右儿子相等是就到了叶子了,就可以停止更新了 { segTree[i].l=l; segTree[i].r=r; if(l==r) { scanf("%d",&segTree[i].sum); return; } int mid=((l+r)>>1); Build(i<<1,l,mid); Build((i<<1)|1,mid+1,r); segTree[i].sum=segTree[i<<1].sum+segTree[(i<<1)|1].sum; } void add(int i,int t,int s)//给第t个点加s, { segTree[i].sum+=s;//每个节点都需要更新 if(segTree[i].l==segTree[i].r) return;//一直到更新到第t个节点的时候 int mid=((segTree[i].l+segTree[i].r)>>1); if(t<=mid)add(i<<1,t,s); else add((i<<1)|1,t,s); } int sum(int i,int l,int r)//从根节点开始将区间的数值加和 { if(segTree[i].l==l&&segTree[i].r==r) return segTree[i].sum; int mid=((segTree[i].l+segTree[i].r)>>1); int ans=0; if(r<=mid)//当前节点的左儿子 ans=sum(i<<1,l,r); else if(l>mid) //当前节点的右儿子 ans=sum((i<<1)|1,l,r); else ans=sum((i<<1),l,mid)+sum((i<<1)|1,mid+1,r); return ans; } int main() { //freopen("C:\\Users\\acer\\Desktop\\in.txt","r",stdin); int T; int x,y; int n; char str[20]; scanf("%d",&T); int iCase=0; while(T--) { iCase++; scanf("%d",&n); Build(1,1,n); printf("Case %d:\n",iCase); while(scanf("%s",&str)!=EOF) { if(strcmp(str,"End")==0)break; scanf("%d%d",&x,&y); if(strcmp(str,"Add")==0) add(1,x,y); else if(strcmp(str,"Sub")==0) add(1,x,-y); else printf("%d\n",sum(1,x,y)); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/wuwangchuxin0924/p/5867947.html