树状数组模板

区间修改区间查询

#include<bits/stdc++.h>
using namespace std;
#define int long long

const int N=1e6+10;
const int M=3e4+3e3;
int n,t,m;
char c;
int sum1[N],sum2[N];

int lowbit(int x)
{
	return x&(-x);
}

void update(int sum[],int id,int x)
{
	for(int i=id;i<=n;i+=lowbit(i))
	sum[i]+=x;
}

int getx(int sum[],int x)
{
	int k=0;
	for(int i=x;i;i-=lowbit(i))
	k+=sum[i];
	return k;
}

signed main()
{
	int x,y,z,s;
	ios::sync_with_stdio(0);
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y>>z>>s;
		if(x==1)
		{
			update(sum1,y,s);
			update(sum2,z,s);
		}
		else
		{
			cout<<getx(sum1,z)-getx(sum2,y-1)<<endl;
		}
	}
}

单点修改区间查询

#include<bits/stdc++.h>
using namespace std;

const int N=1e6+10;
const int M=3e4+3e3;
int n,t,m;
char c;
int sum[N];

int lowbit(int x)
{
	return x&(-x);
}

void update(int id,int x)
{
	for(int i=id;i<=n+1;i+=lowbit(i))
	sum[i]+=x;
}

int getx(int x)
{
	int k=0;
	for(int i=x;i;i-=lowbit(i))
	k+=sum[i];
	return k;
}

signed main()
{
	int x,y;
	ios::sync_with_stdio(0);
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		cin>>c;
		if(c=='B')//单点增加 
		{
			cin>>x>>y;
			update(x,y);
		}
		else if(c=='A')//求0-x的和
		{
			cin>>x;
			cout<<getx(x)<<endl;
		}
		else
		{
			cin>>x>>y;
			update(x,-y);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值