【POJ2376】Cleaning Shifts

题目大意:区间最小覆盖问题。

题解:本身是一道贪心水题,但是细节还是比较多的,记录一下。
由于每个奶牛对答案的贡献是一样的,肯定要选择在满足条件的基础上能够拓展最多的那个奶牛。为了满足条件,对区间左端点进行排序,每次决策集合为:满足区间左端点比当前边界 + 1 要小的情况下,右端点最大的那个奶牛。注意,这里一定要 + 1,因为只要覆盖就好。

代码如下

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=25010;

int n,m;
struct node{int st,ed;}t[maxn];
bool cmp(const node &x,const node &y){return x.st<y.st;}

int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d%d",&t[i].st,&t[i].ed);
    
    sort(t+1,t+n+1,cmp);
    
    int now=1,bound=0,ans=0;
    while(now<=n){
        int ret=0;
        while(now<=n&&t[now].st<=bound+1)ret=max(ret,t[now++].ed);
        if(!ret)break;
        ++ans;
        bound=max(bound,ret);
        if(bound>=m)break;      
    }
    
    if(bound<m)puts("-1");
    else printf("%d\n",ans);
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wzj-xhjbk/p/11007038.html