思路:
就是书中的区间贪心,不过我觉得对本题中的区间的排序按时间先后比较符合直观,所以排序方法的方向是与书中相反的。
解答:
#include <cstdio>
#include <algorithm>
using namespace std;
const int max_num = 100;
struct show {
int start_time, end_time;
} show_arr[max_num]; // 此处声明了show_arr[]
int cmp(show a, show b) {
if(a.end_time != b.end_time)
return a.end_time < b.end_time; // 先按结束时间从早到晚排序
else
return a.start_time > b.start_time; // 结束时间相同的按开始时间从晚到早排序,使两者间时长较短者排前面
}
int main() {
int show_num;
while(scanf("%d", &show_num) != EOF) {
if(show_num == 0)
break;
for(int i = 0; i <= show_num - 1; i++) {
scanf("%d %d", &show_arr[i].start_time, &show_arr[i].end_time);
}
sort(show_arr, show_arr + show_num, cmp); // 区间排序
int ans = 1; // 时间不重叠的节目个数
int last_end = show_arr[0].end_time; // 上一个被选中的节目的结束时间
for(int i = 1; i <= show_num - 1; i++) { // 从排序后的第二个节目开始向后遍历
if(show_arr[i].start_time >= last_end) { // 如果当前节目开始时间在上一个被选中节目结束时间之后,则
last_end = show_arr[i].end_time; // 选中当前节目
ans++; // 时间不重叠的节目个数加1
}
}
printf("%d\n", ans);
}
return 0;
}
坑:
绝大部分的代码是对的,但少写了“接收到输入0就跳出循环”,于是在正确的输出(下图倒数第三行的5)之后,还会会接收0并输出1。