HDU 5023 A Corrupt Mayor's Performance Art 线段树 区间染色

题意:给出区间1-N。每个区间的初始颜色为2.有两种操作:1.修改区间[a,b]内的颜色为c。2.查询区间[a,b]内区间的颜色有哪几个?

思路:很直接的线段树的操作。对于每个节点,如果它管辖的区间为同一种颜色,我们就记录其颜色。否则记录为混合色。

注意:如果将染成的色和现在的区间的颜色相同,我们是不需要改变的。

         其实对于区间操作,都其实会有个lazy,down,up操作,需要记住。

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int MAX = 1000100;

int N,M;
int a,b,c;
bool used[40];
char Q[2];

#define lson(o) (o<<1)
#define rson(o) ((o<<1)|1)

struct node{
    int l, r;
    int color;
} tree[MAX<<3];

void build(int L, int R, int o)
{
    tree[o].l = L;
    tree[o].r = R;
    tree[o].color = 2;
    if(L == R) return;

    int m = (L + R) >>1;
    build(L,m,lson(o));
    build(m+1,R,rson(o));
}

void down(int o)
{
    tree[lson(o)].color = tree[rson(o)].color = tree[o].color;
}

void update(int L, int R, int o, int cover)
{
    //printf("%d %d %d %d\n",o,tree[o].l,tree[o].r,cover);
    if(tree[o].color == cover)
        return;
    if(L <= tree[o].l && tree[o].r <= R){
        tree[o].color = cover;
        return;
    }
    if(tree[o].color > 0)
        down(o);

    tree[o].color = 0;
    int m = (tree[o].l + tree[o].r) >>1;
    if(L <= m)
        update(L,R,lson(o),cover);
    if(R > m)
        update(L,R,rson(o),cover);
}

void query(int L, int R, int o)
{
    if(tree[o].color > 0){
        used[tree[o].color] = true;
        return;
    }

    int m = (tree[o].l + tree[o].r) >> 1;
    if(L <= m)
        query(L,R,lson(o));
    if(R > m)
        query(L,R,rson(o));
}

int main(void)
{
    //freopen("input.txt","r",stdin);
    while(scanf("%d %d",&N,&M),N||M){
        build(1,N,1);
        for(int i = 0; i < M; ++i){
            scanf("%1s",Q);
            if(Q[0] == 'P'){
                scanf("%d %d %d",&a,&b,&c);
                update(a,b,1,c);
            }
            else{
                scanf("%d %d",&a,&b);
                memset(used,0,sizeof(used));
                query(a,b,1);

                bool sig = true;
                for(int i = 1; i <= 30; ++i){
                    if(used[i]){
                        if(sig) sig = false;
                        else putchar(' ');
                        printf("%d",i);
                    }
                }
                puts("");
            }
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值