POJ 2777 Count Color

来源:互联网 发布:趣头条提现是骗局 知乎 编辑:程序博客网 时间:2024/04/30 19:56

题意:L的长度,从1~L,在区间上添加颜色(1~T),颜色初始全为1。输入P A B :查询A~B区间不同颜色的数目;输入C A B C:更新A~B区间的颜色为C;

运用线段树的延时标记。

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cmath>#define MAXN 100010using namespace std;struct node{    int l,r;    int color;}a[MAXN<<2];int vis[40];int ans = 0;void build(int l,int r,int index){    a[index].l = l;    a[index].r = r;    a[index].color = 1;//一定要初始为1;    if(l == r){        return ;    }    int mid = (l+r)>>1;    build(l,mid,index<<1);    build(mid+1,r,index<<1|1);}void updata(int l,int r,int index,int color){    if(l <= a[index].l && r >= a[index].r){        a[index].color = color;        return ;    }    if(a[index].color){        a[index<<1].color = a[index].color;        a[index<<1|1].color = a[index].color;        a[index].color = 0;    }    int mid = (a[index].l+a[index].r)>>1;    if(l <= mid){        updata(l,r,index<<1,color);    }    if(r > mid){        updata(l,r,index<<1|1,color);    }}void query(int l,int r,int index){    if(r < a[index].l || l > a[index].r){        return ;    }    //L 为a[index].l    //R 为a[index].r    //1: l L r R    //2: L l R r    //3: L l r R    //4: l L R r    if((l >= a[index].l || r <= a[index].r || (l <= a[index].l && r >= a[index].r))&& a[index].color){        if(!vis[a[index].color]){            ans++;            vis[a[index].color] = 1;        }        return ;    }    int mid = (a[index].l+a[index].r)>>1;    if(l <= mid){        query(l,r,index<<1);    }    if(r > mid){        query(l,r,index<<1|1);    }    return ;}int main(){    int l,t,o;    int a,b,c;    char s[2];    scanf("%d %d %d",&l,&t,&o);    build(1,l,1);    for(int i = 0; i < o; i++){        scanf("%s",s);        if(!strcmp(s,"C")){            scanf("%d %d %d",&a,&b,&c);            if(a > b){                swap(a,b);            }            updata(a,b,1,c);        }        else{            scanf("%d %d",&a,&b);            if(a > b){                swap(a,b);            }            memset(vis,0,sizeof(vis));            ans = 0;            query(a,b,1);            printf("%d\n",ans);        }    }    return 0;}


0 0
原创粉丝点击