点击这里查看原题
第一问简单,贪心即可,难在第二问如何求字典序最小的。可以考虑,按字典序尝试所有区间,若加入该区间后总的区间数不变,则一定加入该区间,因此需要实现的就是logn查询区间内的区间数。
我们用getans函数来求区间内的区间数,如果要加入一个[l0,r0]的区间,那么需要满足getans(l,r)=getans(l,l0-1)+getans(r0+1,r)+1,其中l为之前加入的区间中小于l0的最大的区间右端点,r为大于r0的最小的区间左端点。
然后就是写getans函数了,为了在logn内完成,需要使用倍增法。
最后一步,使用set维护加入的区间的端点值,方便每次查询前驱和后继。
/*
User:Small
Language:C++
Problem No.:1178
*/
#include<bits/stdc++.h>
#define ll long long
#define inf 999999999
using namespace std;
const int M=4e5+5;
int cnt,L[M],tot,n,f[M][19],ed;
bool vis[M];
set<int> s;
struct no{
int l,r;
bool operator<(const no b)const{
return l==b.l?r>b.r:l<b.l;
}
}a[M],b[M];
void compress(){//离散化
for(int i=1;i<=n;i++){
L[++tot]=a[i].l;
L[++tot]=a[i].r;
}
sort(L+1,L+tot+1);
ed=unique(L+1,L+tot+1)-L-1;
for(int i=1;i<=n;i++){
a[i].l=lower_bound(L+1,L+ed+1,a[i].l)-L;
a[i].r=lower_bound(L+1,L+ed+1,a[i].r)-L;
}
}
void work(){//得到有序化+去重的区间
for(int i=1;i<=n;i++) b[i]=a[i];
sort(b+1,b+n+1);
b[++cnt]=b[1];
for(int i=2;i<=n;i++){
while(cnt&&b[i].r<=b[cnt].r) cnt--;//对于有包含关系的区间,只保留最小的区间
b[++cnt]=b[i];
}
}
void build(){//倍增法,f[i][j]表示在第i个区间向右走2^j个区间到达的区间
for(int i=0;i<=18;i++) f[cnt+1][i]=cnt+1;
tot=0;
for(int i=1;i<=cnt;i++) L[++tot]=b[i].l;
L[++tot]=inf;
for(int i=1;i<=cnt;i++) f[i][0]=upper_bound(L+1,L+tot+1,b[i].r)-L;
for(int j=1;j<=18;j++)
for(int i=1;i<=cnt;i++)
if(f[i][j-1]&&f[f[i][j-1]][j-1]) f[i][j]=f[f[i][j-1]][j-1];
}
int getans(int l,int r){//求[l,r]范围内最多的区间数
if(l>r||l>ed) return 0;
int res=1,head=lower_bound(L+1,L+tot+1,l)-L;
if(head>cnt||r<b[head].r) return 0;
for(int i=18;~i;i--){
if(f[head][i]==cnt+1||f[head][i]==0) continue;
if(b[f[head][i]].r>r) continue;
head=f[head][i];
res+=(1<<i);
}
return res;
}
int main(){
freopen("data.in","r",stdin);//
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i].l,&a[i].r);
compress();
work();
build();
printf("%d\n",getans(1,ed));
s.insert(-inf);
s.insert(inf);
bool flag=0;
for(int i=1;i<=n;i++){
int now=*s.lower_bound(a[i].l);
if(now==inf||!vis[now]){
if(now<=a[i].r) continue;
int nowl=*--s.lower_bound(a[i].l),nowr=*s.lower_bound(a[i].r);//找前驱和后继
now=getans(nowl+1,a[i].l-1)+getans(a[i].r+1,nowr-1)+1;//计算加入该区间后[nowl,nowr]范围内的区间数是否减小
if(now<getans(nowl+1,nowr-1)) continue;
s.insert(a[i].l);
s.insert(a[i].r);
if(a[i].l!=a[i].r) vis[a[i].r]=1;
if(flag) printf(" ");
printf("%d",i);
flag=1;
}
}
return 0;
}