Sum up--RMQ--线段树

Description

Given an array a[] with N elements,you areasked to perform several operations,each of them is one of the two kinds:

1.      a[i]=j;

2.      calculate sum(a[x]) wherei<=x<=j;

Input Description
Two integers in the first line:n and m.n(1<=n<=100000) implies the number of the elements,m means the number of operations.And then following m(1<=m<=100000) lines each contain three integers o i j.
Output Description
For each operation with o==2,output sum(a[x]) where i<=x<=j.
Sample Input
3 4
1 1 1
1 2 2
1 3 3
2 1 3
Sample Output
6
#include <iostream>
#include <cstdio>
using namespace std;
#define maxn 100008
struct ST
{
	int l,r,key;
}st[4*maxn];
int A[maxn];
void buildtree(int id,int l,int r)
{
	st[id].l=l;
	st[id].r=r;
	if(l==r)
	{
		st[id].key=A[l];
		return;
	}
	int mid=(l+r)/2;
	buildtree(2*id,l,mid);
	buildtree(2*id+1,mid+1,r);
	st[id].key=st[2*id].key+st[2*id+1].key;
}
void update(int id,int u,int newkey)
{
	if(st[id].l==u&&st[id].r==u)
	{
		st[id].key=newkey;
		return;
	}
	if(st[2*id+1].l<=u)
	{
		update(2*id+1,u,newkey);
		st[id].key=st[2*id].key+st[2*id+1].key;
		return;
	}
	if(st[2*id].r>=u)
	{
		update(2*id,u,newkey);
		st[id].key=st[2*id].key+st[2*id+1].key;
		return;
	}
	update(2*id+1,u,newkey);
	update(2*id,u,newkey);
	st[id].key=st[2*id].key+st[2*id+1].key;
}
int find(int id,int l,int r)
{
	if(st[id].l==l&&st[id].r==r)
	{
		return st[id].key;
	}
	if(st[2*id].r>=r)
	{
		return find(2*id,l,r);
	}
	if(st[2*id+1].l<=l)
	{
		return find(2*id+1,l,r);
	}
	int m1=find(2*id,l,st[2*id].r);
	int m2=find(2*id+1,st[2*id+1].l,r);
	return m1+m2;
}
int main()
{
	int n,m,operate,u,v;
	scanf("%d%d",&n,&m);
	buildtree(1,1,n);
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d%d",&operate,&u,&v);
		if(operate==1)
		{
			update(1,u,v);
		}
		else printf("%d\n",find(1,u,v));
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值