树状数组标程
P3374 树状数组板子题
树状数组通过位运算lowbit,将元素修改和区间求和的时间复杂度平均地降低到很小的程度。
#include<bits/stdc++.h>
using namespace std;
int a[500001],T[500001],n,m;;
int lowbit(int k){
return k & -k;
}
void update(int k,int d){
while(k<=n){
T[k]+=d;
k+=lowbit(k);
}
}
int getsum(int x){
int sum=0;
while(x){
sum+=T[x];
x-=lowbit(x);
}
return sum;
}
void RSQ(int a,int b){
cout<<getsum(b)-getsum(a-1)<<endl;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
int x;
cin>>x;
update(i,x);
}
for(int i=1;i<=m;i++){
int x,a,b;
cin>>x>>a>>b;
if(x-1){
RSQ(a,b);
}
else{
update(a,b);
}
}
return 0;
}

浙公网安备 33010602011771号