跳到正文

个人记录

树状数组模板

_wzb_约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
int c[500005],a[5000005],n,m;int x,y,z;
int low(int x) {return x&(-x);}
int get(int x){//求和
	int ans=0;
	while(x>0){
		ans+=c[x];
		x-=low(x);
	}
	return ans;
}
void u(int x,int v){//修改树的值
	a[x]+=v;
	while(x<=n){
		c[x]+=v;
		x+=low(x);
	}
}
signed main(){
	cin>>n>>m;
	std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	for(int i=1;i<=n;i++) cin>>a[i],u(i,a[i]);
	for(int i=1;i<=m;i++){
		cin>>x>>y>>z;
		if(x==1){u(y,z);}
		if(x==2){
			cout<<get(z)-get(y-1)<<"\n";
		}

	}
	return 0;
}
原文