zoukankan      html  css  js  c++  java
  • 《算法竞赛进阶指南》0x42树状数组

    题目链接: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
    ",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);
            }
        }
    }

     

  • 相关阅读:
    C#
    C#
    SQLServer
    C#
    使用Spring Boot快速构建应用
    mysql (master/slave)复制原理及配置
    Mysql 半同步复制配置
    Mysql+keeplived+lvs
    Mysql实时双备
    mysqlbinlog 用法
  • 原文地址:https://www.cnblogs.com/randy-lo/p/13295962.html
Copyright © 2011-2022 走看看