zoukankan      html  css  js  c++  java
  • 树状数组——POJ

    题目含义

    给出一堆数,和一系列操作

    Q是求区间的值,C是区间每个数都增加一个数

    题目分析

    可以用线段树做,但这里就用树状数组做了

    题目代码

    #include<stdio.h>
    #include<iostream>
    #include<math.h>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    typedef long long LL;
    const int maxn=1e5+7;
    LL a[maxn],sum[maxn],c[2][maxn],d;
    int n,q,l,r;
    char s[2];
    int lowbit(int x){
        return x&(-x);
    }
    LL ask(int x,int k){
        LL ans=0;
        while(x){
            ans+=c[k][x];
            x-=lowbit(x);
        }
        return ans;
    }
    void add(int x,LL d,int k){
        while(x<=n){
            c[k][x]+=d;
            x+=lowbit(x);
        }
    }
    int main(){
        scanf("%d%d",&n,&q);
        for(int i=1;i<=n;i++)
            scanf("%I64d",&a[i]),sum[i]=sum[i-1]+a[i];
        for(int i=1;i<=q;i++){
            scanf("%s%d%d",&s,&l,&r);
            if(s[0]=='Q'){
                LL ans=sum[r]+(r+1)*ask(r,0)-ask(r,1);
                ans-=sum[l-1]+l*ask(l-1,0)-ask(l-1,1);
                printf("%I64d
    ",ans);
            }
            else{
                scanf("%lld",&d);
                add(l,d,0),add(l,l*d,1);
                add(r+1,-d,0),add(r+1,-d*(r+1),1);
            }
        }
        return 0;
    }

    一次过了,开心

  • 相关阅读:
    透过书本了解HTML5
    Seam性能讨论
    Maven依赖管理
    Tapestry
    为HTML5的未来制定学习计划
    后缀数组
    HDU 1042(大数)
    教你理解复杂的C/C++声明
    编程修养
    平衡二叉树
  • 原文地址:https://www.cnblogs.com/helman/p/11222513.html
Copyright © 2011-2022 走看看