您的位置:首页 > 其它

poj3468 线段树成段更新模板

2012-08-21 15:42 274 查看
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>

using namespace std;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define clear(a) memset(a,0,sizeof(a))

const int N=101000;

__int64 col[N<<2],sum[N<<2];

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

void pushdown(int l,int r,int rt)
{
    int m;
    __int64 k;
    if (col[rt])
    {
        k=col[rt];
        m=(l+r)>>1;
        sum[rt<<1]+=(m-l+1)*k;
        sum[rt<<1|1]+=(r-m)*k;
        col[rt<<1]+=k;
        col[rt<<1|1]+=k;
        col[rt]=0;
    }
} 

void build(int l,int r,int rt)
{
    if (l==r)
    {
        scanf("%I64d",&sum[rt]);
        col[rt]=0;
        return;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushup(rt);
}

__int64 query(int L,int R,int l,int r,int rt)
{
    //pushdown(l,r,rt);
    if (L<=l&&r<=R)
    {
        return sum[rt];
    }
    pushdown(l,r,rt);
    int m=(l+r)>>1;
    __int64 res=0;
    if (L<=m) res+=query(L,R,lson);
    if (R>m) res+=query(L,R,rson);
    return res; 
}

void update(int L,int R,int add,int l,int r,int rt)
{
    //pushdown(l,r,rt);
    if (L<=l&&r<=R)
    {
        sum[rt]+=(r-l+1)*add;
        col[rt]=add;
        return;
    }
    pushdown(l,r,rt);
    int m=(l+r)>>1;
    if (L<=m) update(L,R,add,lson);
    if (R>m) update(L,R,add,rson);
    pushup(rt);
}

int main()
{
    int n,m,i,x,y,z;
    while (scanf("%d%d",&n,&m)!=EOF)
    {
        clear(sum);
        clear(col);
        build(1,n,1);
        while (m--)      
        {
            char c[3],ch;
            scanf("%s",c);
            ch=c[0];
            scanf("%d%d",&x,&y);
            if (ch=='Q')
            {
                __int64 res=query(x,y,1,n,1);
                printf("%I64d\n",res);
            }
            else
            {
                scanf("%d",&z);
                update(x,y,z,1,n,1);
            }
        }
    }
    return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: