一道关于区间的贪心问题。基本上涉及区间贪心的问题,都会经过排序。这道题也不例外。
这道题关键就是。
排序就是两种,要么根据开始时间排序,要么根据结束时间排序。
而根据开始时间排序是很显然不成立的。
比如
1 100
2 10
10 11
11 12
…
99 100
根据开始时间排序可能就只有1个了。而我们根据结束时间排序的话。很显然能安排更多的节目。为什么呢?
假设我们现在只讨论前2个节目。一个是1 5一个是2 3,我们是选择结束时间5 的还是3的呢?很明显,为了能够安排更多的节目
我们应该选择结束时间早的那个节目
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n;
struct node {
int start;
int end;
} a[N];
bool cmp(node x, node y) {
if (x.end < y.end)
return true;
else if (x.end == y.end && x.start > y.start)
return true;
return false;
}
int main() {
while (cin >> n && n) {
for (int i = 0; i < n; i ++ )
cin >> a[i].start >> a[i].end;
sort(a, a + n, cmp);
int res = 1;
for (int i = 1; i < n; i ++ )
if (a[i].start >= a[i - 1].end)
res ++ ;
else
a[i].end = min(a[i].end, a[i - 1].end);
cout << res << endl;
}
return 0;
}