题目大意
给出N个格子和T种颜色
操作1对区间[L,R]进行涂色
操作2询问[L,R]中不同颜色的数量
做法
由于颜色最多只有三十种,2^30可以在int整型范围内表示,所以可以把每一种颜色定义为一个”位“,如果这个位是1表示这个颜色在这个区间内涂过,0则没有
若要表示9(1001) 和 12(1100)的push_up合成
则可以取位运算或”|“得到13(1101)
这样既容易理解也很容易实现
AC代码
/**
* Author1: low-equipped w_udixixi
* Author2: Sher丶lock
* Date :2019-08-19
**/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x<b;x++)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=4e5+7;
const int INF=1e9;
const ll INFF=1e18;
int tree[maxn<<2];
int lazy[maxn<<2];
int ans;
int SUM(int x)
{
int sum=0;
while(x)
{
if (x%2==1)sum++;
x>>=1;
}
return sum;
}
void pu(int rt)
{
tree[rt]=tree[rt<<1]|tree[rt<<1|1];
}
void pd(int rt)
{
tree[rt<<1]=tree[rt<<1|1]=0;
tree[rt<<1]=(1<<(lazy[rt]-1));//***
tree[rt<<1|1]=(1<<(lazy[rt]-1));//***
lazy[rt<<1]=lazy[rt<<1|1]=lazy[rt];
lazy[rt]=0;
}
void build(int rt,int l,int r)
{
tree[rt]=1;//我是以第0位为起点,定义为2也可以,但打星处得对应修改
lazy[rt]=0;
if (l==r)return ;
int mid=(l+r)>>1;
build(lson);
build(rson);
pu(rt);
}
void update(int L,int R,int x,int rt,int l,int r)
{
if (L<=l&&r<=R)
{
lazy[rt]=x;
tree[rt]=0;
tree[rt]|=(1<<(x-1));//***
return;
}
if (lazy[rt]!=0)pd(rt);
int mid=(l+r)>>1;
if (L<=mid)update(L,R,x,lson);
if (R>mid)update(L,R,x,rson);
pu(rt);
}
void query(int L,int R,int rt,int l,int r)
{
if (L<=l&&r<=R)
{
ans|=tree[rt];
return;
}
if (lazy[rt])pd(rt);
int mid=(l+r)>>1;
if (L<=mid)query(L,R,lson);
if (R>mid)query(L,R,rson);
}
int main()
{
int n,T,m,x,y,z;
scanf("%d%d%d",&n,&T,&m);
build(1,1,n);
while(m--)
{
char s;
cin>>s;
if (s=='C')
{
scanf("%d%d%d",&x,&y,&z);
if (x>y)//如果给的区间范围反过来会RE
{
int tmp=y;
y=x;
x=tmp;
}
update(x,y,z,1,1,n);
}
else if (s=='P')
{
scanf("%d%d",&x,&y);
if (x>y)
{
int tmp=y;
y=x;
x=tmp;
}
ans=0;
query(x,y,1,1,n);
cout<<SUM(ans)<<endl;
}
}
return 0;
}