问题 H: 看电视
时间限制: 1 Sec 内存限制: 32 MB
http://192.168.8.233/problem.php?cid=1061&pid=7
题目描述
暑假到了,小明终于可以开心的看电视了。但是小明喜欢的节目太多了,他希望尽量多的看到完整的节目。
现在他把他喜欢的电视节目的转播时间表给你,你能帮他合理安排吗?
现在他把他喜欢的电视节目的转播时间表给你,你能帮他合理安排吗?
输入
输入包含多组测试数据。每组输入的第一行是一个整数n(n<=100),表示小明喜欢的节目的总数。
接下来n行,每行输入两个整数si和ei(1<=i<=n),表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。
当n=0时,输入结束。
接下来n行,每行输入两个整数si和ei(1<=i<=n),表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。
当n=0时,输入结束。
输出
对于每组输入,输出能完整看到的电视节目的个数。
样例输入
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
解题思路
贪心的典型例题,可以发现,将每次的结束时间从小到大排列,然后从第一个开始遍历,如果头大于等于尾的话就+1。
代码如下
# include <stdio.h> struct time { int tail; int head; }; int main(void) { int n, i, sum, c, j; struct time a[101], b; while (~ scanf("%d", &n)) { if (n == 0) break; for (i = 0; i < n; i ++) scanf("%d %d", &a[i].tail, &a[i].head); //以结束时间进行排列 for (i = 0; i < n-1; i ++) for (j = i+1; j < n; j ++) if (a[i].head > a[j].head) { b = a[i]; a[i] = a[j]; a[j] = b; } sum = 1;//第一个时间成立,所以初始为1 c = 0; //比较头和尾的大小。 for (i = 1; i < n; i ++) { if(a[c].head <= a[i].tail) { sum ++; c = i; } } printf("%d\n", sum); } return 0; }
# include <stdio.h> # include <algorithm> using namespace std; struct qwe { int head; int tail; }; bool cmp(struct qwe a, struct qwe b) { return a.head < b.head; } int main(void) { int n, i, c, k, j; struct qwe a[110], t; while (~ scanf("%d", &n)) { if (n == 0) break; for (i = 1; i <= n; i ++) scanf("%d %d", &a[i].tail, &a[i].head); sort(a+1, a+n+1, cmp); c = 1; k = 1; for (i = 2; i <= n; i ++) { if (a[k].head <= a[i].tail) { c ++; k = i; } } printf("%d\n", c); } return 0; }