題目鏈接
題目大意
有一條長度爲n(n
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;
}
看了別人的題解知道這道題還可以用位運算來做,但我還沒有理解,所以之後再補這種做法吧。