[题解/经典模板]POJ_2376_线段覆盖经典贪心

给定一些线段,要求覆盖1~m最少线段数

按左端点排序,易知我们选起点在目前选的线段范围内的并且右端点最远的线段最优,然而我们没必要每次都从头开始扫,因为前面扫过的就没用了,只要维护一个指针不断右移即可

细节需要积累

也可用dp做

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=25009;
int n,m;
struct node{
    int l,r;
    bool operator <(const node&t)const{
        return l<t.l;
    }
}e[maxn];
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&e[i].l,&e[i].r);
    }
    sort(e+1,e+1+n);
    int pos=1,now=1,ans=0;
    while(now<=n&&pos<=m){
        int far=-1;
        while(now<=n&&e[now].l<=pos)far=max(far,e[now].r),now++;
        if(far<=pos-1)break;
        pos=far+1;ans++;
    }
    if(pos>m)printf("%d",ans);
    else printf("-1");
}

猜你喜欢

转载自www.cnblogs.com/superminivan/p/11739145.html