标签:count str 目的 贪心算法 pre 总数 描述 include 导入
12
1 3
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
5 10
4 14
2 9
0
5
code:
/*算法:使用贪心算法,时间按照开始时间从小到大的顺序排列,
*如果开始时间相同,那么按照结束时间从小到大的顺序排列。之
*后使用lastTV保留上一个最优解,如果下一个区间的开始时间大
*于lastTV的结束时间,那么更新lastTV,直至所有区间被遍历完
*/
#include <iostream>
#include <algorithm>
/*节目结构*/
struct program {
	int si, ei;
};
program TV[1000];
bool cmp(program a, program b) {
	if (a.ei != b.ei)
	{
		return a.ei < b.ei;	//返回开始时间小的
	}
	else
	{
		return a.si < b.si;	//返回结束时间小的
	}
}
int main()
{
	using namespace std;
int n;
 while (cin >> n)
	{
		if (!n)
		{
			break;
		}
 for (int i = 0; i < n; i++)
		{
			cin >> TV[i].si >> TV[i].ei;
		}
 /*根据开始时间从小到大排序,如果相等,那么结束时间小的在前*/
		sort(TV, TV + n, cmp);
 /*for (int i = 0; i < n; i++)
		{
			cout << TV[i].si <<" "<< TV[i].ei<<endl;
		}*/
 int lastTV = TV[0].ei, count = 1;
		//cout << lastTV<<endl;
		for (int i = 1; i < n; i++)
		{
			if (TV[i].si >= lastTV)
			{
				count++;
				lastTV = TV[i].ei;
			}
		}
		cout << count << endl;
}
 // system("pause");
	return 0;
}
 标签:count str 目的 贪心算法 pre 总数 描述 include 导入
原文地址:https://www.cnblogs.com/yangyalong/p/10610278.html