题目链接:http://poj.org/problem?id=2777
读完题观察一下数据范围,因为之前做过hdu上一道类似的线段树+lazy优化的题目,所以很容易想到lazy,不过最后还是超时了,在Query操作中遍需要历到所有的节点,这样的做法会超时,还是需要继续用lazy优化,加上位运算是为了统计颜色数。
具体解释一下位运算的部分:因为T的大小只有30,每个颜色用2^C表示,最多2^30次方刚好在int范围内,每个颜色又恰好占据一个二进制位,最后只需要通过异或运算,数中1的个数即为区间的所有颜色数。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=100010;
int L,T,O;
int lazy[4*maxn],color[4*maxn];
int ans;
struct segmentTree{
int l;
int r;
}node[4*maxn];
void PushUp(int rt){
color[rt]=color[rt<<1]|color[rt<<1|1];
}
void PushDown(int rt){
lazy[rt<<1]=lazy[rt<<1|1]=lazy[rt];
color[rt<<1]=color[rt<<1|1]=color[rt];
lazy[rt]=-1;
}
void build(int rt,int l,int r){
node[rt].l=l;
node[rt].r=r;
color[rt]=(1<<1);
if(l==r) return ;
int mid=(l+r)>>1;
build(rt<<1,l,mid);
build(rt<<1|1,mid+1,r);
}
void Update(int rt,int L,int R,int l,int r,int c){
if(l<=L&&R<=r){
color[rt]=(1<<c);
lazy[rt]=1;
return ;
}
if(lazy[rt]!=-1) PushDown(rt);
int mid=(L+R)>>1;
if(l<=mid) Update(rt<<1,L,mid,l,r,c);
if(r>mid) Update(rt<<1|1,mid+1,R,l,r,c);
PushUp(rt);
}
int Query(int rt,int L,int R,int l,int r){
if(L==l&&r==R){
return color[rt];
}
if(lazy[rt]!=-1) PushDown(rt);
int mid=(L+R)>>1;
if(l>mid) return Query(rt<<1|1,mid+1,R,l,r);
else if(r<=mid) return Query(rt<<1,L,mid,l,r);
else{
return Query(rt<<1,L,mid,l,mid)|Query(rt<<1|1,mid+1,R,mid+1,r);
}
}
int fun(int x){
int ans=0;
while(x){
ans+=x%2;
x/=2;
}
return ans;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
#endif
while(~scanf("%d%d%d",&L,&T,&O)){
build(1,1,L);
memset(lazy,-1,sizeof(lazy));
char ch;
int a,b,c;
while(O--){
getchar();
scanf("%c",&ch);
switch(ch){
case 'C':
scanf("%d%d%d",&a,&b,&c);
Update(1,1,L,min(a,b),max(a,b),c);
break;
case 'P':
scanf("%d%d",&a,&b);
ans=Query(1,1,L,min(a,b),max(a,b));
ans=fun(ans);
printf("%d\n",ans);
break;
}
}
}
return 0;
}