看电视
题目链接:http://codeup.cn/problem.php?cid=100000584&pid=0
思路
- 贪心算法
- 区间不相交类型
- 按左端点从大到小排序,左端点相同,则按照右端点小到大排序
- 判断条件是tvShow[i].e<=lastX
代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct TvShow {
int s;
int e;
} tvShow[110];
struct Rule {
bool operator () (const TvShow &a1,const TvShow &a2)const {
if (a1.s!=a2.s)
return a1.s>a2.s;
else
return a1.e<a2.e;
}
};
int main() {
int n;
while (scanf("%d",&n),n!=0) {
for (int i = 0; i < n; i++) {
scanf("%d%d",&tvShow[i].s,&tvShow[i].e);
}
sort(tvShow,tvShow+n,Rule());
// for (int i = 0; i < n; i++) {
// printf("%d %d\n",tvShow[i].s,tvShow[i].e);
// }
int ans = 1;
int lastX = tvShow[0].s;
for (int i = 1; i < n; i++) {
if (tvShow[i].e<=lastX){
lastX = tvShow[i].s;
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}