区间贪心 节目安排
//按结束时间早的排序,留下更多的时间给后续节目
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
struct program {
int start;
int end;
};
const int maxn = 1000;
program arr[maxn];
bool compare(program x, program y) {
return x.end < y.end;
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (n == 0) {
break;
}
for (int i = 0; i < n; i++) {
scanf("%d%d", &arr[i].start, &arr[i].end);
}
sort(arr, arr + n, compare);
int current = 0; //记录上个节目结束时间
int answer = 0;
for (int i = 0; i < n; i++) {
if (current <= arr[i].start) { //<=
current = arr[i].end;
answer++;
}
}
printf("%d\n", answer);
}
return 0;
}
本章介绍了常常用来求解最优化问题的贪心策略。读者在考场上遇到求最大、最小、最多 等最值问题时,应优先考虑是否能够用贪心策略求解。若问题满足最优子结构性质,即该问题 具备无后效性,那么全局的最优解便可由求子问题的最优解得到。此时就应该选择使用贪心策 略。尽管贪心策略是一种高效实用的方法,但不适合于求解所有的最优化问题。无法通过贪心 策略求解的最优化问题,将在动态规划一章中介绍。
查看7道真题和解析