【BZOJ5102】[POI2018]Prawnicy 堆

【BZOJ5102】[POI2018]Prawnicy

Description

定义一个区间(l,r)的长度为r-l,空区间的长度为0。
给定数轴上n个区间,请选择其中恰好k个区间,使得交集的长度最大。

Input

第一行包含两个正整数n,k(1<=k<=n<=1000000),表示区间的数量。
接下来n行,每行两个正整数l,r(1<=l<r<=10^9),依次表示每个区间。

Output

第一行输出一个整数,即最大长度。
第二行输出k个正整数,依次表示选择的是输入文件中的第几个区间。
若有多组最优解,输出任意一组。

Sample Input

6 3
3 8
4 12
2 6
1 10
5 9
11 12

Sample Output

4 1 2 4

题解:假如我们已经确定了最终区间的左端点L,那么我们选择的区间一定是左端点在L左边,且右端点最右的K个点。所以我们将所有区间按左端点排序,用小根堆维护左端点在左边,且右端点最大的K个点。每次用第K大值更新答案即可。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=1000010;
int n,k,ans;
struct node
{
	int l,r,org;
	node() {}
	node(int a,int b) {r=a,org=b;}
	bool operator < (const node &a) const {return r>a.r;}
}p[maxn];
priority_queue<node> q;
bool cmp(const node &a,const node &b)
{
	return a.l<b.l;
}
inline int rd()
{
	int ret=0,f=1;	char gc=getchar();
	while(gc<'0'||gc>'9')	{if(gc=='-')	f=-f;	gc=getchar();}
	while(gc>='0'&&gc<='9')	ret=ret*10+(gc^'0'),gc=getchar();
	return ret*f;
}
int main()
{
	n=rd(),k=rd();
	int i;
	for(i=1;i<=n;i++)	p[i].l=rd(),p[i].r=rd(),p[i].org=i;
	sort(p+1,p+n+1,cmp);
	for(i=1;i<=n;i++)
	{
		q.push(p[i]);
		if(i>k)	q.pop();
		if(i>=k)	ans=max(ans,q.top().r-p[i].l);
	}
	while(!q.empty())	q.pop();
	printf("%d\n",ans);
	for(i=1;i<=n;i++)
	{
		q.push(p[i]);
		if(i>k)	q.pop();
		if(i>=k&&ans==q.top().r-p[i].l)
		{
			while(!q.empty())	printf("%d ",q.top().org),q.pop();
			return 0;
		}
	}
}
posted @ 2017-12-02 14:33  CQzhangyu  阅读(622)  评论(0编辑  收藏  举报