POJ 2777 Count Color(区间覆盖和区间查询)

来源:互联网 发布:java md5加密 编辑:程序博客网 时间:2024/05/22 05:14
这题很巧,要用位运算。
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1const int maxm=1e5+10;int add[maxm<<2];int sum[maxm<<2];char s[3];int cnt;void pushup(int rt){    sum[rt]=sum[rt<<1]|sum[rt<<1|1];}void pushdown(int rt){    if(add[rt])    {        add[rt<<1]=add[rt];        add[rt<<1|1]=add[rt];        sum[rt<<1]=sum[rt];        sum[rt<<1|1]=sum[rt];        add[rt]=0;    }}void build(int l,int r,int rt){    add[rt]=0;    if(l==r)    {        sum[rt]=1;        return;    }    int m=(l+r)>>1;    build(lson);    build(rson);    pushup(rt);}void updata(int L,int R,int c,int l,int r,int rt){    if(L<=l&&R>=r)    {        add[rt]=c;        sum[rt]=1<<(c-1);//表示从末尾开始数,第n位,代表有第n个颜色        return;    }    pushdown(rt);    int m=(l+r)>>1;    if(L<=m)        updata(L,R,c,lson);    if(R>m)        updata(L,R,c,rson);    pushup(rt);}void querty(int L,int R,int l,int r,int rt){    if(L<=l&&R>=r)    {        cnt|=sum[rt];//代表,颜色的覆盖(比如100|101就成了111代表,这三个区间都有颜色了,可以理解成颜色都合并了        return;    }    pushdown(rt);    int m=(l+r)>>1;    if(L<=m)        querty(L,R,lson);    if(R>m)        querty(L,R,rson);}int does(int n){    int s=0;    while(n)    {        if(n&1)            s++;        n>>=1;    }    return s;}int main(){    int L,T,O;    while(scanf("%d%d%d",&L,&T,&O)!=EOF)    {        int x,y,z;        build(1,L,1);        for(int i=0; i<O; i++)        {            scanf("%s",s);            if(s[0]=='C')            {                scanf("%d%d%d",&x,&y,&z);                if(x>y)                {                    swap(x,y);                }                updata(x,y,z,1,L,1);            }            if(s[0]=='P')            {                scanf("%d%d",&x,&y);                if(x>y)                {                    swap(x,y);                }                cnt=0;                querty(x,y,1,L,1);                printf("%d\n",does(cnt));            }        }    }    return 0;}

0 0