• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
dwtfukgv
博客园    首页    新随笔    联系   管理    订阅  订阅
POJ 2376 Cleaning Shifts (贪心,区间覆盖)

题意:给定1-m的区间,然后给定n个小区间,用最少的小区间去覆盖1-m的区间,覆盖不了,输出-1.

析:一看就知道是贪心算法的区间覆盖,主要贪心策略是把左端点排序,如果左端点大于1无解,然后,

忽略小于1的部分(如果有的话),再找最长的区间,然后把这个区间的右端点作为下次寻找的起点,

再找最大区间,直到覆盖到最后。

注意:首先要判断好能不能覆盖,不能覆盖就结束,有可能会提前结束,也要做好判断,我就在这WA了好几次,

悲剧。。。其他的就比较简单了,不用说了。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;
const int maxn = 25000 + 10;
struct node{
    int l, r;
    bool operator < (const node &p) const {
        return l < p.l;
    }
};
node a[maxn];

int main(){
    int n, m;
    scanf("%d %d", &n, &m);
    for(int i = 0; i < n; ++i)  scanf("%d %d", &a[i].l, &a[i].r);
    sort(a, a+n);

    bool ok = true;
    int s = 1, e = 1, cnt = 1;
    if(a[0].l > 1){  printf("-1\n");  return 0; }

    for(int i = 0; i < n; ++i){
        if(a[i].l <= s)  e = max(e, a[i].r);
        else{
            ++cnt;
            s = e + 1;
            if(a[i].l > s){ ok = false;  break; }
            else e = max(e, a[i].r);
        }
        if(e >= m)  break;
    }

    if(!ok || e < m)  printf("-1\n");
    else  printf("%d\n", cnt);
    return 0;
}

 

posted on 2016-05-29 21:32  dwtfukgv  阅读(315)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3