首先,拉张图
树状数组,相对于线段树来说,空间复杂度更小,但是可以处理的信息具有局限性
常用于处理区间(矩阵)查改(差分转化为单点查改),单点查改
Ac code:
点击查看代码
#include<bits/stdc++.h>
#define lowbit x&-x
using namespace std;
int n,m,s[500005];
void change(int x,int k){
while(x<=n) s[x]+=k,x+=lowbit;
}
int query(int x){
int t=0;
while(x) t+=s[x],x-=lowbit;
return t;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
int op,x,y;
for(int i=1;i<=n;i++){
cin>>y;
change(i,y);
}
for(int i=1;i<=m;i++){
cin>>op>>x>>y;
if(op==1) change(x,y);
else cout<<query(y)-query(x-1)<<"\n";
}
return 0;
}
以及改进(退/奇怪)了马蜂
点击查看代码
//树状数组
#include<bits/stdc++.h>
using namespace std;
#define N 500001
int n,m;
int s[N];
namespace tr{
inline int lowbit(int x){
return x&-x;
}
void change(int nb,int i){
while(i<=n){
s[i]+=nb;
i+=lowbit(i);
}
}
int query(int x){
int sum=0;
while(x){
sum+=s[x],x-=lowbit(x);
}
return sum;
}
}
namespace rw{
inline int read(){
int nb=0,f=1;
char c=getchar();
while(c>'9' || c<'0'){
if(c=='-') f=-f;
c=getchar();
}
while(c>='0' && c<='9'){
nb=(nb<<3)+(nb<<1)+(c^48);
c=getchar();
}
return nb*f;
}
void write(int x){
if(x<0) putchar('-'),x=~x+1;
if(x>9) write(x/10);
putchar(x%10^48);
return ;
}
inline void scan(){
n=read(),m=read();
for(int i=1;i<=n;i++){
int wow=read();
tr::change(wow,i);
}
for(int i=1;i<=m;i++){
int wow=read();
if(wow==1){
int x=read(),y=read();
tr::change(y,x);
}
else{
int x=read(),y=read();
cout<<tr::query(y)-tr::query(x-1)<<"\n";
}
}
}
}
int main(){
rw::scan();
return 0;
}
就酱!
标签:树状,int,upd,namespace,查改,郝玩,void,change From: https://www.cnblogs.com/cathyzro/p/18546773