贪心:利用结束时间排序,选择结束时间早的先看,得到最优解
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Time {
int from, to;
};
int cmp(const void *a, const void *b) {
return ((struct Time *)a)->to - ((struct Time *)b)->to;
}
int
main() {
struct Time t[105];
int ncase;
int i, j, cnt;
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
while (scanf("%d", &ncase) == 1 && ncase) {
memset(t, 0, sizeof(t));
cnt = 0;
for (i = 0; i < ncase; ++ i)
scanf("%d%d", &t[i].from, &t[i].to);
qsort(t, ncase, sizeof(struct Time), cmp);
for (i = 1,j = 0; i < ncase; ++ i)
if (t[i].from >= t[j].to) cnt++, j = i;
printf("%d\n", cnt + 1);
}
}