树状数组模板

本文最后更新于:3 years ago

1.区间更新求区间和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e5+5;
int n,m,a[N];
ll num[N],sum[N];
inline int lowbit(int i){
return i&(-i);
}
inline void update(int i,int k){
int j=i;
while(i<=n){
num[i]+=k;
sum[i]+=k*(j-1);//前缀和
i+=lowbit(i);
}
}
inline ll getsum(int i){
ll res=0;
int j=i;
while(i>0){
res+=num[i]*j-sum[i];//算好这位的值就是到这位的总和减去前缀和
i-=lowbit(i);
}
return res;
}
int main(){
ios::sync_with_stdio(false);
while(cin>>n>>m){
memset(num,0,sizeof(num));
memset(sum,0,sizeof(sum));
a[0]=0;
for(int i=1;i<=n;i++){
cin>>a[i];
update(i,a[i]-a[i-1]);
}
for(int i=0;i<m;i++){
int op;
cin>>op;
if(op==1){
int x,y,k;
cin>>x>>y>>k;
if(y<x)swap(x,y);
update(x,k);
update(y+1,-k);//差分操作更新值
}else if(op==2){
int x;
cin>>x;
ll res=getsum(x)-getsum(x-1);
cout<<res<<endl;
}
}
}
return 0;
}

2.单点更新求区间最值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const int N = 1e5+5;
int a[N],c[N],n;
int lowbit(int r){
return r&(-r);
}
void updata(int i,int res){//单点更新
a[i]=res;
while(i<=n){
c[i]=res;
for(int j=1;j<lowbit(i);j<<=1){
c[i]=c[i]>c[i-j]?c[i]:c[i-j];
}
i+=lowbit(i);
}
}
int query(int l,int r){//查询
int res=INT_MIN;
while(true){
res=res>a[r]?res:a[r];
if(l==r)break;//找完了就退出,在更新数据后再退出防止出错
for(r-=1;r-l>=lowbit(r);r-=lowbit(r))
res=res>c[r]?res:c[r];
}
return res;
}
int main() {
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++){
cin>>a[i];
update(i,a[i]);
}
int m;
cin>>m;
for(int i=1;i<=m;i++){
int c,d;
cin>>c>>d;
cout<<query(c,d)<<endl;
}
}
return 0;
}