HDU 2037 今年暑假不AC (区间贪心)

题意:又是中文题。。。

析:先说一下区间贪心的一个定理,选择不相交的区间:数轴上有n个开区间(ai, bi)。选择尽量多的区间,使得这些区间两两不相交,贪心策略是,一定是选bi小的。(想一下为什么)。

知道这个的话,这个问题还不so easy!先对每个节目结束的时间排序,然后一个一个的选,保证没有相交,也就是说当前的开始时间一定要是上一个后面或者上一个刚结束当前就开始就OK了。

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
typedef long long LL;
struct node{
    int s, e;
    node() { }
    node(int ss, int ee) : s(ss), e(ee) { }
    bool operator <(const node &p) const {
        return e < p.e;
    }
};
node a[110];

int main(){
    int n;
    while(scanf("%d", &n) && n){
        for(int i = 0; i < n; ++i)
            scanf("%d %d", &a[i].s, &a[i].e);
        sort(a, a+n);
        int cnt = 0;
        int ss = a[0].e;
        for(int i = 1; i < n; ++i){
            if(a[i].s >= ss){  ++cnt;  ss = a[i].e; }
        }
        printf("%d
", cnt+1);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/5525451.html