题意:长度为L的板子,初始的颜色都为1,后来对这个板子进行涂色操作,具体就是把一段连续区间涂成同一种颜色,然后询问某个区间内一共有多少种颜色.
分析:将长度L分为L段长度为1的板子作为叶子结点,初始颜色为1,用二进制表示颜色的种类,二进制的第i位为1表示存在2^(i-1)这种颜色,更新的时候用或操作,查询也要用到或操作.
参考代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
#define lson rt<<1
#define rson rt<<1|1
const int maxn = 1e5+10;
int l,t,q;
struct SegTree{
int l,r;
int color;
int tag;
};
SegTree st[maxn<<2];
int ans;
//向上更新
void PushUp( int rt)
{
st[rt].color = st[lson].color | st[rson].color;
}
//向下更新
void PushDown( int rt)
{
if( st[rt].tag)
{
st[lson].tag = st[rson].tag = st[rt].tag;
st[lson].color = st[rson].color = st[rt].color;
st[rt].tag = 0;
}
}
//建树
void Build( int l, int r, int rt)
{
st[rt].l = l;
st[rt].r = r;
st[rt].color = 1;
st[rt].tag = 1;
if( l == r)
return;
int mid = (l+r)>>1;
Build(l,mid,lson);
Build(mid+1,r,rson);
// PushUp(rt);//这里没有要PushUp的内容
}
//区间更新
void Update( int L, int R, int rt, int color)
{
if( L <= st[rt].l && R >= st[rt].r)
{
st[rt].tag = 1;
st[rt].color = color;
return;
}
if( st[rt].color == color)
return;
PushDown(rt);
int mid = (st[rt].l+st[rt].r)>>1;
if( R <= mid)
Update(L,R,lson,color);
else if( L > mid)
Update(L,R,rson,color);
else
{
Update(L,mid,lson,color);
Update(mid+1,R,rson,color);
}
PushUp(rt);
}
//区间查询
void Query( int L, int R, int rt)
{
if( L <= st[rt].l && R >= st[rt].r)
{
ans |= st[rt].color;
return;
}
PushDown(rt);
if( st[rt].tag)
{
ans |= st[rt].color;
return;
}
int mid = (st[rt].l+st[rt].r)>>1;
if( R <= mid)
Query(L,R,lson);
else if( L > mid)
Query(L,R,rson);
else
{
Query(L,mid,lson);
Query(mid+1,R,rson);
}
}
int Get( int tmp)
{
int a = 0;
while( tmp)
{
if( tmp & 1)
a++;
tmp = tmp >> 1;
}
return a;
}
int main()
{
while( ~scanf("%d%d%d",&l,&t,&q))
{
Build(1,l,1);
while( q--)
{
char op[maxn];
scanf("%s",op);
int a,b,color;
if( op[0] == 'C')
{
scanf("%d%d%d",&a,&b,&color);
if( a > b)
swap(a,b);
Update(a,b,1,1<<(color-1));
}
else if( op[0] == 'P')
{
scanf("%d%d",&a,&b);
if( a > b)
swap(a,b);
ans = 0;
Query(a,b,1);
ans = Get(ans);
printf("%d\n",ans);
}
}
}
return 0;
}