http://poj.org/problem?id=2777
题意:
区间1到n,起始颜色都为1,每次更新一段区间的颜色(C left right val),问区间内的颜色有几种(P left right)
思路:
这题给的颜色种类最多30,可以想到用位运算来求解,颜色是1到n那么,我们用二进制1<<(n-1)来表示颜色,
比如颜色1 :1,2:10,3:100,4:1000
然后关键是怎么求区间颜色的种类数,
可以发现一段区间的颜色是1 2
那么我们用或运算|,来把这段区间的颜色值都或起来,得到11,这时候,1的个数就是区间颜色的种类
在比如1 2 =》1 1
1 3 =》1 0 1
那么1 2 1 3=》1 1 1(3种颜色)
(感觉这题对lazy思想又进一步的理解了,总结如下图:)
(还有一个坑,就是输入的时候要判断left和right,保证left<right……)
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<cmath>
#include<set>
#define ll long long
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N=1000005;
int sum[N<<2],flag[N<<2];
void push_up(int rt){
sum[rt]=sum[rt<<1]|sum[rt<<1|1];
}
void build(int l,int r,int rt){
sum[rt]=1;
if(l==r)return ;
int m=(l+r)>>1;
build(lson);
build(rson);
}
void push_down(int rt){
if(flag[rt]){
int C=flag[rt];
flag[rt<<1]=C;
flag[rt<<1|1]=C;
sum[rt<<1]=1<<(C-1);
sum[rt<<1|1]=1<<(C-1);
flag[rt]=0;
}
}
void update(int L,int R,int C,int l,int r,int rt){
if(L<=l&&r<=R){
sum[rt]=1<<(C-1);
flag[rt]=C;
return ;
}
int m=(l+r)>>1;
push_down(rt);
if(L<=m)update(L,R,C,lson);
if(R>m)update(L,R,C,rson);
push_up(rt);
}
int query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return sum[rt];
}
int m=(l+r)>>1;
push_down(rt);
int ans=0;
if(L<=m)ans|=query(L,R,lson);
if(R>m)ans|=query(L,R,rson);
return ans;
}
int main(){
int n,T,O,a,b,c;
scanf("%d%d%d",&n,&T,&O);
char s[5];
build(1,n,1);
memset(flag,0,sizeof(flag));
while(O--){
scanf("%s",s);
if(s[0]=='C'){
scanf("%d%d%d",&a,&b,&c);
if(a>b)swap(a,b);
update(a,b,c,1,n,1);
}
else{
scanf("%d%d",&a,&b);
if(a>b)swap(a,b);
int tmp=query(a,b,1,n,1);
int res=0;
while(tmp){
if(tmp&1)res++;
tmp>>=1;
}
printf("%d\n",res);
}
}
}