线段树区间赋值(Lazy)

这个题是区间赋值,刚开始想着像一般的Lazy操作进行从顶向下操作,然后又想了下,这不可能实现啊,这样太复杂了吧,所以只好从底向上进行操作,从底向上操作,底部的Lazy和和同时更新。

附上代码:


//lazyÇø¼ä¸³Öµ
#include<bits/stdc++.h>

using namespace std;

const int maxn=1e5+50;

struct node{
    int l,r,sum;
};
node tree[maxn<<2];
int lazy[maxn<<2];

void push_up(int p)
{
    tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum;
}

void build(int p,int l,int r)
{
    tree[p].l=l;
    tree[p].r=r;
    if(l==r){
        tree[p].sum=1;
        return ;
    }
    int mid=(l+r)>>1;
    build(p<<1,l,mid);
    build(p<<1|1,mid+1,r);
    push_up(p);
}

void push_down(int p)
{
    lazy[p<<1]=lazy[p<<1|1]=lazy[p];
    int mid=(tree[p].l+tree[p].r)>>1;
    tree[p<<1].sum=lazy[p]*(mid-tree[p].l+1);
    tree[p<<1|1].sum=lazy[p]*(tree[p].r-mid);
    tree[p].sum=lazy[p]*(tree[p].r-tree[p].l+1);
    lazy[p]=0;
}

void update(int p,int l,int r,int v)
{
    if(tree[p].l==l&&tree[p].r==r){
        lazy[p]=v;
        tree[p].sum=(tree[p].r-tree[p].l+1)*lazy[p];
        return ;
    }
    if(lazy[p]){
        push_down(p);
    }
    int mid=(tree[p].l+tree[p].r)>>1;
    if(r<=mid){
        update(p<<1,l,r,v);
    }else if(l>mid){
        update(p<<1|1,l,r,v);
    }else{
        update(p<<1,l,mid,v);
        update(p<<1|1,mid+1,r,v);
    }
    push_up(p);
}

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

猜你喜欢

转载自blog.csdn.net/zhouzi2018/article/details/81089816