首页 > 编程语言 > 详细

《算法竞赛进阶指南》0x42树状数组

时间:2020-07-13 22:11:15      阅读:71      评论:0      收藏:0      [点我收藏+]

题目链接:http://poj.org/problem?id=3468

树状数组的区间修改区间查询模式,简单题目。用差分以及维护两个数列。

代码:

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
const int maxn = 100010;
ll c[2][maxn];//分别维护di、i*di 
int lowbit(int x){
    return x&(-x);
}
void update(int k,int x,ll C){
    while(x<maxn){
        c[k][x]+=C;
        x+=lowbit(x);
    }
}
ll query(int k,int x){
    ll ans=0;
    while(x){
        ans+=c[k][x];
        x-=lowbit(x);
    }
    return ans;
}
ll sum[maxn];
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++) {
        scanf("%lld",&sum[i]);
        sum[i]+=sum[i-1];
    }
    for(int i=1;i<=m;i++){
        char s[10];
        int l,r;
        scanf("%s",s);
        if(s[0]==Q){
            scanf("%d%d",&l,&r);
            ll ans=(sum[r]+(r+1)*query(0,r)-query(1,r))-
                    (sum[l-1]+l*query(0,l-1)-query(1,l-1));
            printf("%lld\n",ans);
        }
        if(s[0]==C){
            ll d;
            scanf("%d%d%lld",&l,&r,&d);
            update(0,l,d);
            update(0,r+1,-d);
            update(1,l,l*d);
            update(1,r+1,-(r+1)*d);
        }
    }
}

 

 

《算法竞赛进阶指南》0x42树状数组

原文:https://www.cnblogs.com/randy-lo/p/13295962.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!