POJ P2777 Count Color——线段树状态压缩

Description

Chosen Problem Solving and Program design as an optional course, you are required to solve all kinds of problems. Here, we get a new problem.

There is a very long board with length L centimeter, L is a positive integer, so we can evenly divide the board into L segments, and they are labeled by 1, 2, ... L from left to right, each is 1 centimeter long. Now we have to color the board - one segment with only one color. We can do following two operations on the board:

1. "C A B C" Color the board from segment A to segment B with color C. 
2. "P A B" Output the number of different colors painted between segment A and segment B (including).

In our daily life, we have very few words to describe a color (red, green, blue, yellow…), so you may assume that the total number of different colors T is very small. To make it simple, we express the names of colors as color 1, color 2, ... color T. At the beginning, the board was painted in color 1. Now the rest of problem is left to your.

          --by POJ
http://poj.org/problem?id=2777


题目大意:
区间染色,统计区间颜色数;
解法,线段树维护区间颜色情况,开桶;
因为颜色种类少,故压成二进制,应该快些;
挺水的题,代码也短;
代码如下:
#include<cstdio>
using namespace std;
const int MAXN=;
int tree[MAXN<<];
int lz[MAXN<<];
int n,t,o,L,R;
void up(int );
void down(int ,int ,int );
void col(int ,int ,int ,int );
int ask(int ,int ,int );
int ans(int );
int main()
{
int i,j,k;
char s[];
scanf("%d%d%d",&n,&t,&o);
lz[]=;
tree[]=;
for(i=;i<=o;i++){
scanf("%s",s);
if(s[]=='C'){
scanf("%d%d%d",&L,&R,&j);
if(L>=R)
k=L,L=R,R=k;
col(,n,,j);
}
else{
scanf("%d%d",&L,&R);
if(L>=R)
k=L,L=R,R=k;
j=ask(,n,);
printf("%d\n",ans(j));
}
}
}
void up(int nu){
tree[nu]=tree[nu<<]|tree[nu<<|];
}
void down(int l,int r,int nu){
if(!lz[nu])return ;
tree[nu<<]=lz[nu];
tree[nu<<|]=lz[nu];
lz[nu<<]=lz[nu<<|]=lz[nu];
lz[nu]=;
}
void col(int l,int r,int nu,int x){
if(L<=l&&r<=R){
tree[nu]=lz[nu]=(<<(x-));
return ;
}
down(l,r,nu);
int mid=(l+r)>>;
if(L<=mid)
col(l,mid,nu<<,x);
if(R>mid)
col(mid+,r,nu<<|,x);
up(nu);
}
int ask(int l,int r,int nu){
if(L<=l&&r<=R)
return tree[nu];
down(l,r,nu);
int ans=,mid=(l+r)>>;
if(L<=mid)
ans|=ask(l,mid,nu<<);
if(R>mid)
ans|=ask(mid+,r,nu<<|);
return ans;
}
int ans(int x){
int re=;
while(x){
if(x&)
re++;
x>>=;
}
return re;
}

  

上一篇:VS 编辑并继续(转载)


下一篇:iOS开发:在Xcode中用Pods管理第三方库