题目
给你一堆区间染色 保证两两颜色不同
颜色会覆盖 留下的只有上面的颜色
最后问总共有多少种不同区间在表面上
(好吧本来是贴海报 但就是这意思)
思路来源
https://blog.csdn.net/aaaaacmer/article/details/47101899(离散化技巧1)
https://blog.csdn.net/winddreams/article/details/38443761(离散化技巧2)
心得
第一个用到了区间的离散化
比如[1,10][1,4][7,10]三段区间,
把1 4 7 10离散化为1 2 3 4之后就会出现
[1,4][1,2][3,4]即后两个把[1,4]覆盖满,从而使原本[5,6]有颜色的没有了
处理这个就把两个区间中空出来的地方缩成一个点就可以了
第二个的好处在于
hash数组可以开的很小,没有必要像第一个开到1kw
结合二者之长写了如下代码
但开始空间开小了疯狂re也不知道怎么回事(后记:估错了理论下界现在调对了)
以后要学会各种各样的离散化+线段树啊
个人喜欢非结构体的写法
即传ql qr l r一堆参的线段树写法
color=-1时代表该段没颜色或有多种颜色 无法向下pushdown
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e4+10;
int T;
struct node
{
int v,id;
}e[maxn*2];
bool cmp(node a,node b)
{
return a.v<b.v;
}
int Hash[4*maxn],num;//maxv上界4*maxn 两两不同两两插点
int color[16*maxn],ans[maxn],n,cnt;
void pushdown(int p)
{
if(color[p]!=-1)
{
color[p<<1]=color[p<<1|1]=color[p];
color[p]=-1;
}
}
void update(int p,int l,int r,int ql,int qr,int c)
{
if(ql<=l&&r<=qr)
{
color[p]=c;
return;
}
pushdown(p);
int mid=(l+r)>>1;
if(ql<=mid)update(p<<1,l,mid,ql,qr,c);
if(qr>mid)update(p<<1|1,mid+1,r,ql,qr,c);
}
void ask(int p,int l,int r)
{
if(color[p]!=-1)
{
ans[num++]=color[p];
return;
}
if(l==r)return;//不用递归下去了
int mid=(l+r)>>1;
ask(p<<1,l,mid);
ask(p<<1|1,mid+1,r);
}
void init()
{
memset(color,-1,sizeof(color));
memset(Hash,0,sizeof(Hash));
num=0;cnt=1;
}
int main()
{
scanf("%d",&T);
while(T--)
{
init();
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%d%d",&e[i].v,&e[i+n].v);
e[i].id=i;e[i+n].id=i+n;
}
sort(e+1,e+2*n+1,cmp);
Hash[e[1].id]=cnt;//先把值缩成编号 编号对应的值再映射
//只用3W空间 却又考虑了区间的离散化情况
for(int i=2;i<=2*n;++i)
{
if(e[i].v==e[i-1].v)
{
Hash[e[i].id]=Hash[e[i-1].id];//和上一个一样
continue;
}
cnt++;//不一样就新开一个
if(e[i].v>e[i-1].v+1)cnt++;//中间空开一个
Hash[e[i].id]=cnt;
}
for(int i=1;i<=n;++i)
update(1,1,cnt,Hash[i],Hash[i+n],i);
ask(1,1,cnt);
sort(ans,ans+num);
int res=unique(ans,ans+num)-ans;
printf("%d\n",res);
}
return 0;
}