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. Input
First line of input contains L (1 <= L <= 100000), T (1 <= T <= 30) and O (1 <= O <= 100000). Here O denotes the number of operations. Following O lines, each contains "C A B C" or "P A B" (here A, B, C are integers, and A may be larger than B) as an operation defined previously.
Output
Ouput results of the output operation in order, each line contains a number.
Sample Input 2 2 4 C 1 1 2 P 1 2 C 2 2 2 P 1 2 Sample Output 2 1 Source |
题意:
L T Q,L代表数量,T代表颜色种类数量,Q代表操作次数。
C操作为 (A-B)区间内所有颜色变为C。
P操作为输出(A-B)区间内所有颜色的种类。
POINT:
用线段树,保存每个区间的颜色种类,用状态压缩来存颜色,2的30次-int。
之后用位运算合起来就行。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
const int N = 100000*10;
int num[N],add[N];
void pushdown(int x)
{
add[2*x]=add[x];
num[2*x]=add[x];
add[2*x+1]=add[x];
num[2*x+1]=add[x];
add[x]=0;
}
void change(int x,int l,int r,int ll,int rr,int c)
{
if(add[x]) pushdown(x);
if(ll<=l&&rr>=r)
{
num[x]=1<<(c-1);
add[x]=num[x];
}
else
{ int mid=(r+l)>>1;
if(ll<=mid) change(2*x,l,mid,ll,rr,c);
if(rr>mid) change(2*x+1,mid+1,r,ll,rr,c);
num[x]=num[x*2+1]|num[x*2];
}
}
int output(int x,int l,int r,int ll,int rr)
{
int ans=0;
if(add[x]) pushdown(x);
if(ll<=l&&rr>=r) ans=ans|num[x];
else
{
int mid=(r+l)>>1;
if(ll<=mid) ans=ans|output(2*x,l,mid,ll,rr);
if(rr>mid) ans=ans|output(2*x+1,mid+1,r,ll,rr);
}
return ans;
}
int main()
{
int l,t,o;
while(~scanf("%d %d %d",&l,&t,&o))
{
for(int i=1;i<=6*l;i++)
{
num[i]=1;
}
memset(add,0,sizeof add);
while(o--)
{
char q;
getchar();
scanf("%c",&q);
if(q=='C')
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
change(1,1,l,a,b,c);
}
else
{
int a, b;
scanf("%d %d",&a,&b);
if(a>b) swap(a,b);
int now=output(1,1,l,a,b);
int ans=0;
while(now)
{
ans+=now&1;
now>>=1;
}
printf("%d\n",ans);
}
}
}
}