概述:输入若干个节目的起始时间,选出能完整观看的节目的最大数。
思路:贪心算法问题,解题的关键是在有限的时间内安排尽量多的节目。所以将节目按开始的时间排序,然后遍历所有节目,将前一个的结束时间与下一个节目开始时间冲突的节目排除,随后统计结果。
感想:第一个AC的题,非常简单。
#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
using namespace std;
struct Info
{
int start, end;
bool flag;
};
bool cmp(const Info &a, const Info &b)
{
return a.end < b.end;
}
int main()
{
//ifstream cin("aaa.txt");
int n;
vector<Info>v;
while (cin >> n&&n != 0)
{
v.clear();
int sum = 1;
Info a;
while (n--)
{
cin >> a.start >> a.end;
a.flag = 0;
v.push_back(a);
}
stable_sort(v.begin(), v.end(),cmp);
vector<Info>::iterator it1=v.begin();
it1->flag = 1;
for (vector<Info>::iterator it = v.begin()+1; it != v.end() ; ++it)
{
if (it1->flag && it->start >= it1->end)
{
it->flag = 1;
it1 = it;
++sum;
}
}
cout << sum << endl;
}
return 0;
}