区间不相交问题

版权声明:copyright©CodeIover reserved https://blog.csdn.net/qq_40073459/article/details/86636963

给出N个开区间(x,y),从中选择尽可能多的开区间,使得这些开区间两两没有交集。

参考代码:

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=110;
struct Inteval{
	int x,y;
}I[maxn];
bool cmp(Inteval a,Inteval b)
{
	if(a.x!=b.x) return a.x>b.x;//按左端点从大到小排序
	else return a.y<b.y;//左端点相同时按右端点从小到大排序
}
int main()
{
	int n;
	while(scanf("%d",&n),n!=0)
	{
		for(int i=0;i<n;i++)
		{
			scanf("%d%d",&I[i].x,&I[i].y);
		}
		sort(I,I+n,cmp);//把区间排序
		int ans=1,lastX=I[0].x;
		for(int i=1;i<n;i++)
		{
			if(I[i].y<=lastX){//如果该区间右端点在lastX左侧
				lastX=I[i].x;//以I[i]作为新选中的区间
				ans++;//不相交区间加1
			}
		}
		printf("%d\n",ans); 
	}
	return 0;
}

结果如下:

猜你喜欢

转载自blog.csdn.net/qq_40073459/article/details/86636963