线段树

// SegmentTree
struct SegNode{
	int lst,rst;
	int sum,val;
	int lazy;
};
SegNode node[maxn];
void BuiSegTree(int idx,int lst,int rst,int a[]){
	node[idx].lst=lst; node[idx].rst=rst;
	int mid=(lst+rst)<<1;
	if(rst==lst){
		node[idx].val=a[lst];
		node[idx].sum=a[lst];
		node[idx].lazy=0;
		return;
	}
	BuiSegTree(idx<<1,lst,mid,a);
	BuiSegTree((idx)<<1+1,mid+1,rst,a);
	node[idx].sum=node[idx<<1]+node[(idx<<1)+1];
	node[idx].lazy=0;
}
void Update(int cur,int lst,int rst,int num){
	int mid=(node[i].lst+node[i].rst)<<1;
	int lhd=cur<<1,rhd=(cur<<1)+1;
	if(node[idx.lst]==lst && node[idx].rst==rst){
		node[cur].sum+=(rst-lst+1)*(node[cur].lazy+num);
		node[lhd].lazy+=node[cur].lazy+num;
		node[rhd].lazy+=node[cur].lazy+num;
		node[cur].lazy=0;
		return;
	}
	// .............
}

 

// 线段树
#include<iostream>
#include<string>
using namespace std;
int in[200000];                        //40000开太小,越界
int lowbit(int a){
	return a&-a;
}
void plus(int i,int num,int n){
	while(i<=n){ 
		in[i]+=num;
		i+=lowbit(i);
	}
	return;
}
void add(int i,int j,int n){
	while(i<=n){
		in[i]+=j;
		i+=lowbit(i);
	}

}
int sum(int i){
	int ssum=0;
	while(i>0){
		ssum+=in[i];
		//cout<<i<<" "<<in[i]<<" "<<ssum<<endl;//
		i-=lowbit(i);
	}
	return ssum;
}
int query(int l,int r){
	//cout<<sum(r)<<" "<<sum(l-1)<<endl;//
	return(sum(r)-sum(l-1));
}
int main()
{
	int t,n,k,i,j,ai;
	string cmd;
	cin>>t;
	for(k=1;k<=t;k++){
		cin>>n;
		cout<<"Case "<<k<<":"<<endl;
		for(i=1;i<=n;i++){
			scanf("%d",&ai);                         //cin超时
			plus(i,ai,n);
		}
		cmd="";
		for(;cmd!="End";){
			cin>>cmd;
			if(cmd=="Add"){
				scanf("%d%d",&i,&j);       //cin超时
				//cout<<"a";//
				add(i,j,n);
			}
			if(cmd=="Sub"){
				scanf("%d%d",&i,&j);        //cin超时
                //cout<<"s";//
				add(i,-j,n);
			}
			if(cmd=="Query"){
				scanf("%d%d",&i,&j);         //cin超时
				//cout<<"q";//
				printf("%d\n",query(i,j));
			}
		}
		for(i=1;i<=n;i++)    in[i]=0;             //数据未清零,wa
	}
	return 0;
}

  

posted on 2013-08-13 12:53  Amyc  阅读(168)  评论(0编辑  收藏  举报