POJ 2777 Count Color

来源:互联网 发布:成功的网络促销 编辑:程序博客网 时间:2024/06/16 11:11

给出一个长为L的板,分成L个区域,一开始板的颜色是1,现在有T种颜色,O个操作,操作有两种,一种是把区间[l,r]的板涂成颜色c,一个操作是求区间[l,r]里不同颜色的个数。
解法:线段树,因为颜色只有不到30种,可以用int状压,线段树就用来维护这个状压值。区间更改,用lazy;

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1const int maxn = 100100;int sum[maxn<<2],col[maxn<<2];using namespace std;void pushup(int rt){    sum[rt] = sum[rt<<1] | sum[rt<<1|1];}void pushdown(int rt){    if(col[rt])//lazy标记    {        col[rt<<1] = col[rt<<1|1] = col[rt];        sum[rt<<1] = sum[rt<<1|1] = col[rt];        col[rt] = 0;    }}void build(int l,int r ,int rt){    col[rt] = 0;    if(l == r)    {        sum[rt] = 1;        return ;    }    int m = (r+l)>>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)    {        col[rt] = c;        sum[rt] = c;        return ;    }    pushdown(rt);    int m = (r+l)>>1;    if(L <= m) update(L,R,c,lson);    if(R > m) update(L,R,c,rson);    pushup(rt);}int query(int L,int R,int l,int r,int rt){    if(L <= l && r <= R)    {        return sum[rt];    }    pushdown(rt);    int m = (r+l)>>1;    int ans = 0;    if(L <= m) ans |= query(L,R,lson);    if(R > m) ans |= query(L,R,rson);    return ans;}int count1(int x)//状压后求有几种颜色。{    int ans = 0 ;    while(x)    {        if(x&1) ans++;        x>>=1;    }    return ans;}int main(){    int l,t,o;    while(~scanf("%d%d%d",&l,&t,&o))    {        build(1,l,1);        while(o--)        {            char op[2];            scanf("%s",op);            if(op[0] == 'C')            {                int a,b,c;                scanf("%d%d%d",&a,&b,&c);                if(a>b) swap(a,b);                update(a,b,1<<(c-1),1,l,1);            }            else            {                int a,b;                scanf("%d%d",&a,&b);                if(a>b) swap(a,b);                int ans = count1(query(a,b,1,l,1));                printf("%d\n",ans);            }        }    }    return 0;}
0 0
原创粉丝点击