线段树 (单点修改+区间查询)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166

tip:记录一下线段树的入门题吧~~

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=5e5+10;
int a[maxn],tree[maxn];
int n,m;
void build(int node,int start,int end){
	if(start==end){
		tree[node]=a[start];return;
	}
	int mid=(start+end)/2;
	build(node*2,start,mid);
	build(node*2+1,mid+1,end);
	tree[node]=tree[node*2]+tree[node*2+1];
}
void update(int node,int start,int end,int idx,int x){
	if(start==end){
		a[idx]+=x;tree[node]+=x;return;
	}
	int mid=(start+end)/2;
	if(idx<=mid) update(node*2,start,mid,idx,x);
	else update(node*2+1,mid+1,end,idx,x);
	tree[node]=tree[node*2]+tree[node*2+1];
}
int query(int node,int start,int end,int l,int r){
	if(l>end||r<start) return 0;		//若没有交集则直接返回0 
	if(start>=l&&end<=r) return tree[node];  //若当前的区间在访问的区间内则直接返回该节点的值 
	if(start==end) return tree[node];		//访问到叶子节点直接返回 
	int mid=(start+end)/2;
	return query(node*2,start,mid,l,r)+query(node*2+1,mid+1,end,l,r);
}

int main()
{
	int t;int c=1;int f=0;
	cin>>t;
	while(t--){
		cin>>n;
		for(int i=1;i<=n;i++) cin>>a[i];
		build(1,1,n);
		while(1){
			int x,y;string s;cin>>s;
			if(s!="End") cin>>x>>y;
			if(s=="Query"){
				if(!f){
					f=1;cout<<"Case "<<c<<":"<<endl;
				}
				cout<<query(1,1,n,x,y)<<endl;
			} 
			else if(s=="Add") update(1,1,n,x,y);
			else if(s=="Sub") update(1,1,n,x,-y);
			else{
				f=0;c++;break;
			}
		}
	}
	return 0;	
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值