树状数组

单点修改,区间查询:

int n,m;
int E[maxn];
void add(int x,int v){
    while(x<=n){
        E[x]+=v;
        x+=lowbit(x);
    }
}
int query(int x){
    int ans=0;
    while(x>0){
        ans+=E[x];
        x-=lowbit(x);
    }
    return ans;
}
int main(){
    fio;
    cin>>n>>m;
    memset(E,0,sizeof(E));
    int x;
    for(int i=1;i<=n;i++){
        cin>>x;
        add(i,x);
    }
    int op,y;
    while(m--){
        cin>>op>>x>>y;
        if(op==1){
            add(x,y);
        }
        else if(op==2){
            cout<<query(y)-query(x-1)<<endl;
        }
    }
}

区间修改,单点查询:

LL c[maxn],a[maxn];
int n,m;
void update(int x,int y,LL add){
    while(x<=n){
        c[x]+=add;
        x+=lowbit(x);
    }
    while(y<=n){
        c[y]-=add;
        y+=lowbit(y);
    }
}
void update(int x,LL add){
    while(x<=n){
        c[x]+=add;
        x+=lowbit(x);
    }
}
LL query(int x){
    LL ans=0;
    while(x>0){
        ans+=c[x];
        x-=lowbit(x);
    }
    return ans;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        update(i,a[i]-a[i-1]);
    }
    int opt,x,y;
    LL z;
    for(int i=0;i<m;i++){
        scanf("%d",&opt);
        if(opt==1){
            scanf("%d%d%lld",&x,&y,&z);
            update(x,y+1,z);
        }
        else if(opt==2){
            scanf("%d",&x);
            printf("%lld\n",query(x));
        }
    }

}

 区间修改,区间查询

LL c1[maxn],c2[maxn],a[maxn];
int n,m;
void add(int x,int y){
    while(x<=n) {
        c1[i]+=y,c2[i]+=(long long)x*y;
        x+=lowbit(x);
    }
}
int query(int x){
    int ans=0;
    for(x>=0){
        ans+=(x+1)*c1[i]-c2[i];
        x-=lowbit(x);
    }
    return ans;
}

 

转载于:https://www.cnblogs.com/Profish/p/9737679.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值