Too Many Segments (easy 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≤200) — 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≤200) — 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.

题意: 一个点被超过k个线段覆盖就被称为坏点,给出n条线段,求至少删除几个线段不会出现坏点。

思路: 如果一个点被覆盖超过k次,首先删除区间右端点靠左的,这样对以后的点的影响会最小,所以按照右端点从小到大的方式对所有线段进行排序,然后进行贪心找到所有需要删除的线段。

代码:

#include
#include
#include
#include
using namespace std;
int n,m;
int a,b,p[1010],ans[1010];
struct node
{
	int x,y,id;
}s[1010];
bool cmp(node a,node b)
{
	if(a.y==b.y)
	return a.x<b.x;
	else
	return a.y<b.y;
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		memset(p,0,sizeof p);
		memset(ans,0,sizeof ans);
		for(int i=0;i<n;i++)
		{
			scanf("%d%d",&a,&b);
			s[i].x=a;
			s[i].y=b;
			s[i].id=i+1;
		}
		sort(s,s+n,cmp);
		int k=0;
		for(int i=0;i<n;i++)
		{
			for(int j=s[i].x;j<=s[i].y;j++)
			{
				ans[j]++;
				if(ans[j]>m)
				{
					p[k++]=s[i].id;
					break;
				}
			}
		}
		printf("%d\n",k);
		for(int i=0;i<k;i++)
		printf("%d ",p[i]);
		printf("\n");
	}
	return 0;
}

你可能感兴趣的:(Too Many Segments (easy version)(贪心))