题目
Problem Description
作为新时代的好青年,你一定会看许多电视节目,比如新闻联播(永远不要忘记关心国家大事)、非常 6+7、超级女生,以及王小丫的《开心辞典》等等,
假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)
Input
输入数据包含多个测试实例,每个测试实例的第一行只有一个整数 n(n<=100),表示你喜欢看的节目的总数,
然后是 n 行数据,每行包括两个数据 Ti_s,Ti_e (1<=i<=n),分别表示第 i 个节目的开始和结束时间,
为了简化问题,每个时间都用一个正整数表示。n=0 表示输入结束,不做处理。
Output
对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。
Sample Input
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
Sample Output
5
题解
方法一
- 把所有节目排序,按开始时间从早到晚排序,如果开始时间相同,按结束时间从早到晚排序
- 初始化,从任意节目开始,能完整观看的节目数量均为 1
- 维护一个变量,最大节目数 maxVal,初始为 1
- 因为最后一个结点开始能完整观看的节目数一定为 1,所以从倒数第二个结点开始向前遍历
- 每遍历一个节点时,将当前结点与后面的结点依次比较,如果有在当前节目结束后开始的节目,并且 program[i].o < program[j].o + 1,比较完成后,即可得到从当前节目开始可以完整观看的最大节目数量
- 每得到一个最大节目数,就和 maxVal 取最大值
- 遍历完所有结点,maxVal 即为所求
#include <cstdio>
#include <algorithm>
using namespace std;
struct pro {
int s;
int e;
int o;
}program[100];
bool cmp(const pro& a, const pro& b) {
if (a.s != b.s) {
return a.s < b.s;
} else {
return a.e < b.e;
}
}
int main() {
int n, maxVal;
while (scanf("%d", &n), n) {
maxVal = 1;
for (int i = 0;i < n;i++) {
scanf("%d%d", &program[i].s, &program[i].e);
program[i].o = 1;
}
sort(program, program + n, cmp);
for (int i = n - 2;i >= 0;i--) {
for (int j = i + 1;j < n;j++) {
if (program[i].e <= program[j].s && program[i].o < program[j].o + 1) {
program[i].o = program[j].o + 1;
maxVal = max(program[i].o, maxVal);
}
}
}
printf("%d\n", maxVal);
}
}
方法二
- 把所有节目按结束时间从早到晚排序
- 初始化结束时间为 0,count 为 0
- 从第一个节目开始,按顺序寻找从当前结束时间之后开始的节目,找到之后,更新结束时间,并且 count++
- 最后一个节目找完后,count 即为所求
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 定义节目结构体
struct Program {
int start;
int end;
};
// 根据节目的结束时间进行排序的比较函数
bool cmp(const Program& a, const Program& b) {
return a.end < b.end;
}
int main() {
int n;
while (cin >> n && n != 0) {
vector<Program> programs(n);
for (int i = 0; i < n; ++i) {
cin >> programs[i].start >> programs[i].end;
}
// 根据节目的结束时间进行排序
sort(programs.begin(), programs.end(), cmp);
int count = 0; // 完整观看的节目数量
int lastEnd = 0; // 上一个观看的节目的结束时间
for (const auto& program : programs) {
if (program.start >= lastEnd) {
// 如果当前节目的开始时间晚于上一个节目的结束时间,则可以观看当前节目
++count;
lastEnd = program.end;
}
}
cout << count << endl;
}
return 0;
}