树状数组

树状数组

P3374 【模板】树状数组 1——树状数组区间和

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0);cout.tie(0);cin.tie(0);
#define endl '\n'
#define int long long 
const int N=5e5+1145;
int tree[N];
int n,m;
int lowbit(int x){
	return x&(-x);
}
int count(int i){
	int sum=0;
	while(i>0){
		sum+=tree[i];
		i-=lowbit(i);
	}
	return sum;
}
void add(int i,int num){
	while(i<=n){
		tree[i]+=num;
		i+=lowbit(i);
	}
}
signed main(){
	IOS
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		int a;
		cin>>a;
		add(i,a);
	}
	for(int i=1;i<=m;i++){
		int opt;
		cin>>opt;
		if(opt==1){
			int x,k;
			cin>>x>>k;
			add(x,k);
		}
		else {
			int x,y;
			cin>>x>>y;
			cout<<count(y)-count(x-1)<<endl;
		}
	}
	return 0;
}

P3368 【模板】树状数组 2——树状数组前缀和

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0);cout.tie(0);cin.tie(0);
#define endl '\n'
#define int long long 
const int N=5e5+1145;
int tree[N];
int n,m;
int lowbit(int x){
	return x&(-x);
}
int count(int i){
	int sum=0;
	while(i>0){
		sum+=tree[i];
		i-=lowbit(i);
	}
	return sum;
}
void add(int i,int num){
	while(i<=n){
		tree[i]+=num;
		i+=lowbit(i);
	}
}
signed main(){
	IOS
	cin>>n>>m;
	int last=0;
	for(int i=1;i<=n;i++){
		int a;
		cin>>a;
		add(i,a-last);
		last=a;
	}
	for(int i=1;i<=m;i++){
		int opt;
		cin>>opt;
		if(opt==1){
			int x,y,k;
			cin>>x>>y>>k;
			add(x,k);
			add(y+1,-k);
		}
		else {
			int x;
			cin>>x;
			cout<<count(x)<<endl;
		}
	}
	return 0;
}
posted @ 2025-11-26 13:56  10mbps_十兆網路  阅读(0)  评论(0)    收藏  举报