POJ - 3468(水题)树状数组区间修改区间查询模板

U have N integers, A1, A2, ... , AN
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.

#include
#include
#include
using namespace std;
typedef long long ll;
const ll maxn=100005;
ll delt[maxn],sum[maxn],n,m;
ll lowbit(ll x) {return x&(-x);}
void update(ll *a,ll pos,ll val)
{
    while(pos<=n+1)
    {
        a[pos]+=val;
        pos+=lowbit(pos);
    }
}
ll query(ll *a,ll pos)
{
    ll ans=0;
    while(pos>0)
    {
        ans+=a[pos];
        pos-=lowbit(pos);
    }
    return ans;
}
int main()
{
    #define int ll
    scanf("%lld%lld",&n,&m);
    int x=0,y=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&x);
        update(delt,i,x-y);
        update(sum,i,(i-1)*(x-y));
        y=x;
    }
    //scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        char k[5];
        scanf("%s%lld%lld",k,&x,&y);
        if(k[0]=='C')
        {
            scanf("%lld",&z);
            update(delt,x,z);
            update(delt,y+1,-z);
            update(sum,x,z*(x-1));
            update(sum,y+1,-z*y);
        }
        else
        {
            int sum1=(x-1)*query(delt,x-1)-query(sum,x-1);
            int sum2=y*query(delt,y)-query(sum,y);
            printf("%lld\n",sum2-sum1);
        }
    }
    return 0;
} 

与线段树对比

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
typedef long long ll;
int n,m;
const int maxn=400000+100;
ll a[maxn],delt[maxn];

void pushup(int rt)
{
    a[rt]=a[rt<<1]+a[rt<<1|1];
}

void build(int rt,int l,int r)
{
    if(l==r)
    {
        scanf("%lld",&a[rt]);
        return ;
    }
    int mid=(l+r)>>1;
    build(rt<<1,l,mid);
    build(rt<<1|1,mid+1,r);
    pushup(rt);
}

void pushdown(int rt,int l,int r)
{
    if(delt[rt])
    {
        delt[rt<<1]+=delt[rt];
        delt[rt<<1|1]+=delt[rt];
        int mid=(l+r)>>1;
        a[rt<<1]+=(ll)(mid-l+1)*delt[rt];
        a[rt<<1|1]+=(ll)(r-mid)*delt[rt];
        delt[rt]=0;
    }
}

void update(int rt,int l,int r,int x,int y,ll val)
{
    if(x<=l&&y>=r)
    {
        delt[rt]+=val;
        a[rt]+=val*(ll)(r-l+1);
        return ;
    }
    pushdown(rt,l,r);
    int mid=(l+r)>>1;
    if(mid>=x)
        update(rt<<1,l,mid,x,y,val);
    if(mid=x&&r<=y)
    {
        return a[rt];
    }
    pushdown(rt,l,r);
    int mid=(l+r)>>1;
    ll ans=0;
    if(mid>=x)
        ans+=query(rt<<1,l,mid,x,y);
    if(mid

你可能感兴趣的:(树状数组)