POJ3468-A Simple Problem with Integers

http://poj.org/problem?id=3468

#include<cstdio>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
using namespace std;
const int maxn=100001;
LL sum[maxn<<2],tmp[maxn<<2];
void pushup(int rt)
{
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void pushdown(int rt,int m)
{
    if(tmp[rt])
    {           
        tmp[rt<<1]+=tmp[rt];
        tmp[rt<<1|1]+=tmp[rt];
        sum[rt<<1]+=(m-(m>>1))*tmp[rt];
        sum[rt<<1|1]+=(m>>1)*tmp[rt];
        tmp[rt]=0;
    }
}
void build(int l,int r,int rt)
{
    tmp[rt]=0;
    if(l==r)
    {
        scanf("%lld",&sum[rt]);
        return;
    }
    int m=l+r>>1;
    build(lson);
    build(rson);
    pushup(rt);
}
void update(int L,int R,int c,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        tmp[rt]+=c;
        sum[rt]+=c*(r-l+1);
        return;
    }
    pushdown(rt,r-l+1);
    int m=l+r>>1;
    if(L<=m)
        update(L,R,c,lson);
    if(R>m)
        update(L,R,c,rson);
    pushup(rt);
}
LL query(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
        return sum[rt];
    pushdown(rt,r-l+1);
    LL ret=0;
    int m=l+r>>1;
    if(L<=m)
        ret+=query(L,R,lson);
    if(R>m)
        ret+=query(L,R,rson);
    return ret;
}
int main(void)
{
    int N,Q,a,b,c;
    char op[2];
    scanf("%d%d",&N,&Q);
    build(1,N,1);
    while(Q--)
    {
        scanf("%s",op);
        if(op[0]=='Q')
        {
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(a,b,1,N,1));
        }
        else
        {
            scanf("%d%d%d",&a,&b,&c);
            update(a,b,c,1,N,1);
        }
    }
    return 0;
}
posted @ 2012-10-30 21:42  Yogurt Shen  阅读(181)  评论(0)    收藏  举报