标签:
线段树节点的左儿子[a,(a+b)/2]右儿子[(a+b)/2,b]
这个很重要
把线段树当成完全二叉树算,开到3*N就可以,但最好是4*N
#include<bits/stdc++.h> using namespace std; int a[50005]; struct { int sum; int left,right; }b[50005*4]; void build(int left,int right,int i){ int mid; b[i].left=left;b[i].right=right; if(left==right) { b[i].sum=a[left]; return ; } mid = (left+right)/2; build(left,mid,2*i); build(mid+1,right,2*i+1); b[i].sum=b[2*i].sum+b[2*i+1].sum; } int Query(int left,int right,int i){ int mid; if(b[i].left==left&&b[i].right==right) return b[i].sum; mid=(b[i].left + b[i].right)/2; if(right <= mid) return Query(left,right,2*i); else if(left > mid ) return Query(left,right,2*i+1); else return Query(left,mid,2*i) + Query(mid+1,right,2*i+1); } void Add(int id,int num,int i){ if(b[i].left == b[i].right){ b[i].sum = b[i].sum + num; return ; } else { b[i].sum = b[i].sum + num; if(id<=b[i*2].right) Add(id,num,2*i); else Add(id,num,2*i+1); } } int main(){ int t,kase=1; scanf("%d",&t); while(t--){ memset(b,0,sizeof(b)); int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); build(1,n,1); string s;int x,y; printf("Case %d:\n",kase++); while(cin>>s){ if(s[0]=='E') break; scanf("%d%d",&x,&y); if(s[0]=='Q'){ printf("%d\n",Query(x,y,1)); } if(s[0]=='A'){ Add(x,y,1); } if(s[0]=='S') Add(x,-y,1); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/a197p/article/details/47617787