POJ 2376 Cleaning Shifts (贪心,区间覆盖)

时间:2021-05-27 03:34:06

题意:给定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;
}