Luogu P3374 [Template] Tree-like array 1 (single point update + single point evaluation)

Portal

topic:

Insert picture description here

Code:

#include<bits/stdc++.h>
using namespace std;
const int N=5*1e5+100;
int n,m,tree[N];
int lowbit(int i)
{
    
    
	return i&(-i);
}
void updata(int i,int k)
{
    
    
	while(i<=n)
	{
    
    
		tree[i]+=k;
		i+=lowbit(i);
	}
}
int quiry(int i)
{
    
    
	int res=0;
	while(i>0)
	{
    
    
		res+=tree[i];
		i-=lowbit(i);
	}
	return res;
}
int main()
{
    
    
	cin>>n>>m;
	for(int i=1;i<=n;i++){
    
    
		int k;
		cin>>k;
		updata(i,k);
	}
	while(m--)
	{
    
    
		int t,x;
		cin>>t>>x;
		if(t==1){
    
    
			int k;
			cin>>k;
			updata(x,k);
			/*for(int i=1;i<=n;i++) cout<<tree[i]<<" ";
			cout<<endl;*/
		}
		else{
    
    
			int y;
			cin>>y;
			cout<<quiry(y)-quiry(x-1)<<endl;
		}
	}
	return 0;
}
 

#to sum up:

This type of question is similar to the sum of prefixes. Every update or evaluation needs to start from x and modify it by decrementing lowbit(x).

Guess you like

Origin blog.csdn.net/Lzhzl211/article/details/114802800