P3374 【模板】树状数组 1 树状数组优化解法

#include<bits/stdc++.h>
using namespace std;
const int Maxn=500010;
long long a[Maxn];
int n;
int lowbit(int x)
{
	return x&(-x);
}
long long  query(int l,int r)
{
	l--;
	long long sum=0;
	while(r>l) sum+=a[r],r-=lowbit(r);
	while(l>r) sum-=a[l],l-=lowbit(l);
	return sum;
}
void update(int x,long long v)
{
	while(x<=n)
	{
		a[x]+=v;
		x+=lowbit(x); 
	}
}
int main()
{
	int x,m;
	iostream::sync_with_stdio(false);
	cin>>n>>m;
	for (int i=1;i<=n;i++)
	{
		cin>>x;
		a[i]+=x;
		if (i+lowbit(i)<=n) a[i+lowbit(i)]+=a[i]; 
	}
	while(m--)
	{
		int op;
		long long x,y;
		cin>>op>>x>>y;
		if (op==1)
		{
			update(x,y);
		}
		else
		{
			cout<<query(x,y)<<endl;
		}
	}
		
}
posted @ 2022-03-01 08:32  心悟&&星际  阅读(21)  评论(0)    收藏  举报