poj 3468 分类: poj templates 2015-04-01 20:20 34人阅读 评论(0) 收藏


线段树区间增值+区间查询模板。


#include<map>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>
const int MAXN = 100005;

int n , q, a[MAXN] = {0};
struct node
{
    long long sum;
    long long add;
}tree[MAXN<<2] = {0};

#define L(x) (x<<1)
#define R(x) ((x<<1)|1)

inline void update(int x){tree[x].sum = tree[L(x)].sum + tree[R(x)].sum;}

inline void build(int ll,int rr,int si)
{
    if(ll == rr)  tree[si].sum = a[ll];
    else
    {
        int mid = (ll+rr)>>1;
        build(ll,mid,L(si));
        build(mid+1,rr,R(si));
        update(si);
    }
}
inline void pushdown(int x,int ll,int rr)
{
    int mid = (ll+rr)>>1;

    if(tree[x].add)
    {
        tree[L(x)].sum += tree[x].add*(mid-ll+1);
        tree[R(x)].sum += tree[x].add*(rr - mid);
        tree[L(x)].add += tree[x].add;
        tree[R(x)].add += tree[x].add;
        tree[x].add = 0;
    }
}
inline void add(int l,int r,int ll,int rr,int si,int val)
{
    if(ll == l && rr == r)
        tree[si].sum += (long long)val*(rr-ll+1), tree[si].add += val;
    else
    {
        int mid = (ll+rr)>>1;

        pushdown(si,ll,rr);
        if(r<=mid) add(l,r,ll,mid,L(si),val);
        else if(l>mid)add(l,r,mid+1,rr,R(si),val);
        else   
        {
            add(l,mid,ll,mid,L(si),val);
            add(mid+1,r,mid+1,rr,R(si),val);
        }
        update(si);
    }
}
inline long long count(int l,int r,int ll,int rr,int si)
{
    if(ll == l && rr == r)return tree[si].sum;
    else
    {
        int mid = (ll+rr)>>1;

        pushdown(si,ll,rr);
        if(r<=mid)    return count(l,r,ll,mid,L(si));
        else if(l>mid)return count(l,r,mid+1,rr,R(si));
        else      return count(l,mid,ll,mid,L(si)) + count(mid+1,r,mid+1,rr,R(si));
        update(si);
    }
}
#undef L
#undef R
int main()
{
#ifndef ONLINE_JUDGE    
    freopen("poj3468.in","r",stdin);
    freopen("poj3468.out","w",stdout);
#endif

    scanf("%d%d",&n,&q);

    for(int i = 1 ; i <= n ;i++)
      scanf("%d",&a[i]);

    build(1,n,1);

    for(int i = 1; i <= q; i++)
    {
        static int a,b,c;
        static char ch[5] = {'\0'};
        scanf("%s",ch);scanf("%d%d",&a,&b);

        switch(ch[0])
        {
            case 'C': scanf("%d",&c); add(a,b,1,n,1,c);   break;
            case 'Q': printf("%I64d\n",count(a,b,1,n,1)); break;    
        }
    }

#ifndef ONLINE_JUDGE    
    fclose(stdin);
    fclose(stdout);
#endif  
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-04-01 20:20  <Dash>  阅读(108)  评论(0编辑  收藏  举报