树状数组——POJ - 3468

题目含义

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

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\n",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;
}

一次过了,开心

猜你喜欢

转载自www.cnblogs.com/helman/p/11222513.html