题意
定义一个区间(l,r)的长度为r-l,空区间的长度为0。
给定数轴上n个区间,请选择其中恰好k个区间,使得交集的长度最大。
题解
明显地,一个极大区间的两个端点肯定是给出区间的端点
于是你就可以对左端点排序
考虑一个和发的右端点r
明显是有至少k个区间的r在他右边
这个的话有两种方法写,一个是建立线段树,在线段树上二分
第二个是维护一个只有k个元素的堆
CODE:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
const int N=1000005;
struct qq
{
int l,r,id;
bool operator < (const qq &x) const {return r>x.r;}
}s[N];
priority_queue<qq> q;
int n,k;
bool cmp (qq x,qq y){return x.l<y.l;}
int main()
{
scanf("%d%d",&n,&k);
for (int u=1;u<=n;u++)
{
scanf("%d%d",&s[u].l,&s[u].r);
s[u].id=u;
}
sort(s+1,s+1+n,cmp);
int ans=0;
for (int u=1;u<=n;u++)
{
q.push(s[u]);
if (u>k) q.pop();
if (u>=k) ans=max(ans,q.top().r-s[u].l);
}
while (!q.empty()) q.pop();
printf("%d\n",ans);
for (int u=1;u<=n;u++)
{
q.push(s[u]);
if (u>k) q.pop();
if (u>=k&&ans==q.top().r-s[u].l)
{
while (!q.empty())
{
printf("%d ",q.top().id);
q.pop();
}
return 0;
}
}
return 0;
}