Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14531 | Accepted: 4137 |
Description
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
Output
Sample Input
2 2 4 C 1 1 2 P 1 2 C 2 2 2 P 1 2
Sample Output
2 1
Source
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
struct Node
{
int left,right;
int color;
};
Node tree[1000050];
int flag[50];
void buildtree(int id,int l,int r)
{
tree[id].left=l,tree[id].right=r;
if(l!=r)
{
int mid=(l+r)/2;
buildtree(2*id,l,mid);
buildtree(2*id+1,mid+1,r);
}
}
void update(int id,int l,int r,int c)
{
if(tree[id].left==l&&tree[id].right==r)
{
tree[id].color=c;
return ;
}
if(tree[id].color>0)
{
tree[2*id].color=tree[2*id+1].color=tree[id].color;//important
tree[id].color=-1;
}
int mid=(tree[id].left+tree[id].right)/2;
if(r<=mid) update(2*id,l,r,c);
else if(l>=mid+1) update(2*id+1,l,r,c);
else
{
update(2*id,l,mid,c);
update(2*id+1,mid+1,r,c);
}
}
void query(int id,int l,int r)
{
if(tree[id].color>0)
{
flag[tree[id].color]=1;
return ;
}
int mid=(tree[id].left+tree[id].right)/2;
if(r<=mid) query(2*id,l,r);
else if(l>=mid+1) query(2*id+1,l,r);
else
{
query(2*id,l,mid);
query(2*id+1,mid+1,r);
}
}
int main()
{
int n,t,o;
while(scanf("%d%d%d",&n,&t,&o)==3)
{
buildtree(1,1,n);
tree[1].color=1;
while(o--)
{
char ch;cin>>ch;
if(ch=='C')
{
int l,r,c;
scanf("%d%d%d",&l,&r,&c);
if(l>r) swap(l,r);
update(1,l,r,c);
}
else
{
int cnt=0;memset(flag,0,sizeof(flag));
int l,r;
scanf("%d%d",&l,&r);
if(l>r) swap(l,r);
query(1,l,r);
for(int i=1;i<=t;i++) if(flag[i]) cnt++;
printf("%d/n",cnt);
}
}
}
return 0;
}
/*
这题有两个注意的地方,一是因为线段以segment为划分单位,所以右子树的left比左子树
的right要大1。二是给线段树结点增加一个color域,当整个线段为纯色时,color=颜色代
号,当线段内有多种颜色是,color=-1.*/