课后习题 poj 2376 区间贪心

链接:http://poj.org/problem?id=2376
题意:每头牛给出对应打扫卫生的时间区间,要保证每个时间点都有牛打扫,并且求出这样所需要的最少的牛的数量。不能保证就输出-1.
典型的区间贪心,水水来找点信心orz
思路:每头牛的起点升序排列,如果第一头牛的起点不是1,直接不可能。对于每个确定要使用的牛,从下一头开始找,找出区间有重合(此处要小心),并且终点最远的那个,然后确定使用这头,在循环这个操作,直到确定的牛的终点已经是所需要的最远的了。
对于下一头的区间重合要小心,WA了一发,题目中说A cow starts work at the start time and finishes after the end time. 所以只需要下一个牛起点小于等于前一个确定的牛的终点+1,就是可以继续工作了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define M 25009
#define INF 0x3f3f3f3f
typedef struct
{
    int s,e;
}state;
state a[M];
int n,m;
int cmp(state a ,state b)
{
    if(a.s != b.s) return a.s < b.s;
    return a.e < b.e;
}
int main()
{
    while(scanf("%d %d",&n,&m)==2)
    {
        for(int i = 0;i < n;i++)
        {
            scanf("%d %d",&a[i].s,&a[i].e);
        }
        sort(a,a+n,cmp);
        if(a[0].s != 1)
        {
            printf("-1\n");
            continue;
        }
        int cur = 0;
        bool ok = false;
        int ans = 1;
        while(cur < n)
        {
            int k = -1;
            int maxn = -INF;
            int nx = cur+1;
            if(a[cur].e >= m) break;
            while(nx < n && a[nx].s <= a[cur].e+1)  // 要注意a[nx].s <= a[cur].e+1
            {
                if(a[nx].e > maxn) //取出符合条件中的 停止时间最远的一个。
                {
                    k = nx;
                    maxn = a[nx].e;
                }
                nx++;
            }
            if(k == -1)
            {
                ok = true;
                break;
            }
            ans++;
            cur = k;
        }
        if(ok) printf("-1\n");
        else printf("%d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值