算法笔记_区间贪心

即所谓的区间不相交问题:给出N个开区间(x,y),从中选择尽可能多的开区间,使得这些开区间两两没有交集,问最多找到多少个区间?

思路:总选择左端点最大的区间,若左端点一样,就选右端点最小的.

给出如下实例代码:

#include<iostream>
#include<stdlib.h>
#include<algorithm>//algorithm意为"算法",是C++的标准模版库(STL)中最重要的头文件之一,提供了大量基于迭代器的非成员模板函数。
using namespace std;
const int maxn = 110;
class Inteval
{
public:
	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(void)
{
	int n;
	while (cin >> n, n != 0)
	{
		for (int i = 0; i < n; i++)
		{
			cin >> I[i].x >> I[i].y;
		}
		sort(I, I + n, cmp);//头文件algorithm所包含,用途是把区间排序
		int ans = 1, lastX = I[0].x;//ans记录不相交区间个数,lastX记录上一个被选中区间的左端点
		for (int i = 1; i < n; i++)
		{
			if (I[i].y <= lastX)//如果该区间右端点在lastX左边
			{
				lastX = I[i].x;//就以I[i]作为新选中的区间
				ans++;//不相交,区间个数就加1
			}
		}
		cout << ans << endl;
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/81021984