hdu2037 贪心

题目大意:给定n(<=100),再给定n个区间的左端点和右端点,从中选择若干个完整的区间,求最多能选择多少完整的区间

贪心,策略:优先选择右端点最考左的区间

#include <cstdio>
#include <algorithm>

using namespace std;
typedef struct node
{
    int s, e;
}Time;
Time time[110];

bool cmp(Time a, Time b)
{
    if(a.e != b.e) return a.e < b.e;
    return a.s < b.s;
}

int main()
{
    int n;
    while(~scanf("%d", &n) && n)
    {
        for(int i = 1; i <= n; ++i)
            scanf("%d %d", &time[i].s, &time[i].e);
        sort(time+1, time+1+n, cmp);
        int now = time[1].e;
        int cnt = 1;
        for(int i = 2; i <= n; ++i)
            if(time[i].s >= now)
            {
                ++cnt;
                now = time[i].e;
            }
        printf("%d\n", cnt);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jay__bryant/article/details/81189249