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:
- “C A B C” Color the board from segment A to segment B with color C.
- “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.
染色问题,30个颜色,所以可以用一个int类的数字表示所有颜色。那么就可以把所有的颜色状态都表示出来了。但是要注意输入的左右值不一定那个大,所以要是l>r的时候要交换一下。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5+5;
struct node
{
int l, r;
int color, lazy;
}tree[maxn<<2];
inline void PushUp(int cur)
{
tree[cur].color = tree[cur<<1].color|tree[cur<<1|1].color;
}
inline void PushDown(int cur)
{
if(tree[cur].lazy == 0) return ;
tree[cur<<1].lazy = tree[cur<<1|1].lazy = tree[cur].lazy;
tree[cur<<1].color = tree[cur<<1|1].color = tree[cur].lazy;
tree[cur].lazy = 0;
}
void build(int l, int r, int cur)
{
tree[cur].l = l, tree[cur].r = r; tree[cur].lazy = 0;
if(l == r)
{
tree[cur].color = (1<<1);
return ;
}
int mid = (l+r)>>1;
build(l, mid, cur<<1);
build(mid+1, r, cur<<1|1);
PushUp(cur);
}
void update(int l, int r, int cur, int val)
{
if(l <= tree[cur].l && tree[cur].r <= r)
{
tree[cur].lazy = tree[cur].color = (1<<val);
return ;
}
PushDown(cur);
int mid = (tree[cur].l+tree[cur].r)>>1;
if(l <= mid) update(l, r, cur<<1, val);
if(r > mid) update(l, r, cur<<1|1, val);
PushUp(cur);
}
int query(int l, int r, int cur)
{
if(l <= tree[cur].l && tree[cur].r <= r)
return tree[cur].color;
PushDown(cur);
int mid = (tree[cur].l+tree[cur].r)>>1;
int result = 0;
if(l <= mid) result |= query(l, r, cur<<1);
if(r > mid) result |= query(l, r, cur<<1|1);
return result;
}
int main()
{
int n, color_num, op_num;
char op[5];
cin >> n >> color_num >> op_num;
build(1, n, 1);
for(int i = 1; i <= op_num; i++)
{
int l, r, val;
scanf("%s", op);
if(op[0] == 'C')
{
scanf("%d%d%d", &l, &r, &val);
if(l > r) swap(l, r);
update(l, r, 1, val);
}
else
{
scanf("%d%d", &l, &r);
if(l > r) swap(l, r);
int ans = 0, temp = query(l, r, 1);
while(temp)
{
if(temp&1) ans++;
temp >>= 1;
}
printf("%d\n", ans);
}
}
return 0;
}