树状数组模板1(单点修改,区间和查询)

切记树状数组不能处理为0的情况(lowbit无法计算,所以遇到这种情况别忘了+1)



#include<cstdio>
#include<iostream>
using namespace std;
int a[500005],b[500005];
int n;
int lowbit(int x)
{
	return x&(-x);
}
void add(int x,int y)
{
	for(int i=x;i<=n;i+=lowbit(i))
	b[i]+=y;
}
int sum(int x)
{
	int ans=0;
	for(int i=x;i;i-=lowbit(i))
	ans+=b[i];
	return ans;
}
int main()
{
	int m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		add(i,a[i]);//切记初始化!!! 
	} 
	char pd;
	int x,y;
	for(int i=1;i<=m;i++)
	{
		cin>>pd>>x>>y;
		//scanf("%d%d%d",&pd,&x,&y);
		if(pd=='x')
		{
			add(x,y);
		}
		else
		{
			printf("%d\n",sum(y)-sum(x-1));//注意不是sum(x,y) 
		}
	}
	return 0;
} 
posted @ 2019-07-23 19:44  ShineEternal  阅读(145)  评论(0编辑  收藏  举报