Too Many Segments (hard version)

The only difference between easy and hard versions is constraints.

You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [li;ri] (li≤ri) and it covers all integer points j such that li≤j≤ri.

The integer point is called bad if it is covered by strictly more than k segments.

Your task is to remove the minimum number of segments so that there are no bad points at all.

Input
The first line of the input contains two integers n and k (1≤k≤n≤2⋅105) — the number of segments and the maximum number of segments by which each integer point can be covered.

The next n lines contain segments. The i-th line contains two integers li and ri (1≤li≤ri≤2⋅105) — the endpoints of the i-th segment.

Output
In the first line print one integer m (0≤m≤n) — the minimum number of segments you need to remove so that there are no bad points.

In the second line print m distinct integers p1,p2,…,pm (1≤pi≤n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.

intput

7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9

output

3
4 6 7

题意:

题目给n条线段,每条线段覆盖其所含的点。问使得所点覆盖次数不超过k次最少需要删除的线段条数。

思路:

先把所有线段按照右端点的顺序从小到大进行排序,然后遍历每个点,发现有点的个数超过k,就把覆盖到这个点的最长多余线段删除即可,因为删除最长的能降低对后面的影响。

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
const int N=2e5+5;
int n,k;
struct node
{
	int y;    //线段右端点
	int id;   //第几条线段
};
bool operator<(node a,node b)
{
	if(a.y!=b.y) return a.y<b.y; //按照右端点从小到大排序
	return a.id<b.id;
}
vector<node> g[N];
vector<int> a;
node q;
int main()
{
	int x,y;
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++){
		scanf("%d%d",&x,&y);
		q.y=y;q.id=i;
		g[x].push_back(q);
	}
	set<node> s;
	for(int i=1;i<N;i++){
		while(s.size()&&(*s.begin()).y<i) //如果线段的最右边的值比i小,就删掉
			s.erase(*s.begin());
		for(int j=0;j<g[i].size();j++)   //遍历以i为左端点的所有线段
			s.insert(g[i][j]);
		while(s.size()>k){ //超过k时删掉最长的那一条。
			a.push_back((*s.rbegin()).id);
			s.erase(*s.rbegin());
		}
	}
	printf("%d\n",a.size());
	int len=a.size();
	for(int i=0;i<len;i++)
    printf("%d%c",a[i],i==len-1?'\n':' '); //!控制格式,精简!
	return 0;
}


发布了85 篇原创文章 · 获赞 10 · 访问量 5260

猜你喜欢

转载自blog.csdn.net/riversuer/article/details/102883430
今日推荐