线段树成段更新

hdu 1698

n个hook,每个初始化为1,m次操作,更新区间[x,y]的值为z,操作完毕后求所有hook之和。

用g++超时。。。

#include<cstdio>
using namespace std;
#define maxn 100000
#define lson i<<1,l,m
#define rson i<<1|1,m+1,r
int sum[maxn<<2],col[maxn<<2];
void PushUp(int i)
{
    sum[i]=sum[i<<1]+sum[i<<1|1];
}
void PushDown(int i,int x)
{
    if(col[i])
    {
        col[i<<1]=col[i<<1|1]=col[i];
        sum[i<<1]=col[i]*(x-(x>>1));
        sum[i<<1|1]=col[i]*(x>>1);
        col[i]=0;
    }
}
void build(int i,int l,int r)
{
    col[i]=0,sum[i]=1;
    if(l==r) return;
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    PushUp(i);
}
void update(int L,int R,int c,int i,int l,int r)
{
    if(L<=l&&r<=R)
    {
        col[i]=c;
        sum[i]=c*(r-l+1);
        return;
    }
    PushDown(i,r-l+1);
    int m=(l+r)>>1;
    if(L<=m)update(L,R,c,lson);
    if(m<R)update(L,R,c,rson);
    PushUp(i);
}

int main()
{
    int T,n,q;
    scanf("%d",&T);
    for(int i=1;i<=T;++i)
    {
        scanf("%d%d",&n,&q);
        build(1,1,n);
        while(q--)
        {
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            update(x,y,z,1,1,n);
        }
        printf("Case %d: The total value of the hook is %d.\n",i,sum[1]);
    }
    return 0;
}


poj 3468

区间更新,查询,注意数据范围


#include<cstdio>
using namespace std;
#define maxn 100000
#define lson i<<1,l,m
#define rson i<<1|1,m+1,r
#define LL long long
LL sum[maxn<<2];
LL lazy[maxn<<2];
void PushUp(LL i)
{
    sum[i]=sum[i<<1]+sum[i<<1|1];
}
void PushDown(LL i,LL x)
{
    if(lazy[i])
    {
        lazy[i<<1]+=lazy[i];
        lazy[i<<1|1]+=lazy[i];
        sum[i<<1]+=lazy[i]*(x-(x>>1));
        sum[i<<1|1]+=lazy[i]*(x>>1);
        lazy[i]=0;
    }
}
void build(LL i,LL l,LL r)
{
    lazy[i]=0;
    if(l==r) {scanf("%lld",&sum[i]);return;}
    LL m=(l+r)>>1;
    build(lson);
    build(rson);
    PushUp(i);
}
void update(LL L,LL R,LL c,LL i,LL l,LL r)
{
    if(L<=l&&r<=R)
    {
        lazy[i]+=c;
        sum[i]+=c*(r-l+1);
        return;
    }
    PushDown(i,r-l+1);
    LL m=(l+r)>>1;
    if(L<=m)update(L,R,c,lson);
    if(m<R)update(L,R,c,rson);
    PushUp(i);
}
LL query(LL L,LL R,LL i,LL l,LL r)
{
    if(L<=l&&r<=R) return sum[i];
    PushDown(i,r-l+1);
    LL m=(l+r)>>1,ans=0;
    if(m>=L) ans+=query(L,R,lson);
    if(m<R) ans+=query(L,R,rson);
    return ans;
}
int main()
{
    LL n,m;
    scanf("%lld%lld",&n,&m);
    build(1,1,n);
    while(m--)
    {
        char s[2];
        LL a,b,c;
        scanf("%s",s);
        if(s[0]=='Q')
        {
            scanf("%lld%lld",&a,&b);
            printf("%lld\n",query(a,b,1,1,n));
        }
        else
        {
            scanf("%lld%lld%lld",&a,&b,&c);
            update(a,b,c,1,1,n);
        }
    }
    return 0;
}




你可能感兴趣的:(线段树成段更新)