题目链接
题目大意
有一条长度为n(n ≤ 105 )的数轴,有T(T ≤ 30)种颜色,有m个操作(m ≤ 105 ),操作有以下两种:
C a b c:把a与中间染成c色
P a b:查询a与b中间有几种颜色
数轴的初始颜色为1
注意:a有可能大于b
分析
这是一道典型的区间覆盖问题,可以用线段树来解决。我们用线段树数组col[]记录区间的颜色信息,若某个区间下含有多种颜色,则col[]值为-1。“C”操作就是普通的线段树区间更新,“P”操作需要用一个全局变量cnt来反馈区间中有几种不同的颜色,并且需要用一个book[i]来记录第i个颜色是否出现过,在查询区间中找到未出现过的颜色让cnt++,最后cnt即为区间中不同颜色数。
这题所给的区间左端点是可以大于右端点的啊!!!这个我一开始没有注意到,所以以后写有关区间的题目也要提防左端点大于右端点的情况。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#define ls (rt<<1)
#define rs (rt<<1|1)
using namespace std;
const int MAXN=100010;
int n,T,m,cnt,col[MAXN<<2],lazy[MAXN<<2],book[35];
//col[]记录颜色信息,lazy[]为懒惰标记,book[]标记颜色是否在区间中被统计
void PushUp(int rt)//如果当结点对应区间中含有多个颜色,则颜色值为-1
{
if (col[ls]==-1||col[rs]==-1)
col[rt]=-1;
else if (col[ls]==col[rs])
col[rt]=col[ls];
else
col[rt]=-1;
}
void Build(int l,int r,int rt)
{
if (l==r)
{
col[rt]=1;// 初始颜色为1
return;
}
int mid=(l+r)>>1;
Build(l,mid,ls);
Build(mid+1,r,rs);
PushUp(rt);
}
void PushDown(int rt)//延迟更新,下推标记
{
if (lazy[rt])
{
col[ls]=col[rs]=lazy[rt];
lazy[ls]=lazy[rs]=lazy[rt];
lazy[rt]=0;
}
}
void Update(int L,int R,int C,int l,int r,int rt)
{
if (L<=l&&r<=R)
{
col[rt]=C;
lazy[rt]=C;
return;
}
int mid=(l+r)>>1;
PushDown(rt);
if (L<=mid)
Update(L,R,C,l,mid,ls);
if (R>mid)
Update(L,R,C,mid+1,r,rs);
PushUp(rt);
}
void Query(int L,int R,int l,int r,int rt)
{
if (col[rt]>0)
{
if (!book[col[rt]]) //当前颜色还没有被统计过
{
cnt++;
book[col[rt]]=1;
}
return;
}
PushDown(rt);
int mid=(l+r)>>1;
if (L<=mid)
Query(L,R,l,mid,ls);
if (R>mid)
Query(L,R,mid+1,r,rs);
}
int main()
{
int i,L,R,C;
char op;
while(scanf("%d%d%d",&n,&T,&m)!=EOF)
{
Build(1,n,1);
memset(lazy,0,sizeof(lazy));
for (i=1;i<=m;i++)
{
getchar();
scanf("%c",&op);
if (op=='C')
{
scanf("%d%d%d",&L,&R,&C);
if (L<R)
Update(L,R,C,1,n,1);
else
Update(R,L,C,1,n,1);
}
if (op=='P')
{
scanf("%d%d",&L,&R);
cnt=0;//统计区间中不同颜色的个数
memset(book,0,sizeof(book));
if (L<R)
Query(L,R,1,n,1);
else
Query(R,L,1,n,1);
printf("%d\n",cnt);
}
}
}
return 0;
}
看了别人的题解知道这道题还可以用位运算来做,但我还没有理解,所以之后再补这种做法吧。