AcWing 907. 区间覆盖

思路

令需要覆盖的区间开头为st,结尾为ed
1.将所有的区间按左端点排序
2.找到能覆盖st的区间中右端点最大的哪一个,这一步用了贪心
3.更新st,最后判断ed是否被覆盖就可以了

代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e5+5;
struct Range{
    int r,l;
    bool operator < (const Range& w){
        return l<w.l;
    }
}ranges[N];
int main(){
    int n;
    int st,ed;
    cin >> st >> ed;
    cin  >> n;
    for(int i=0;i<n;i++){
        cin >> ranges[i].l >> ranges[i].r;
    }
    sort(ranges,ranges+n);
    int i=0;
    int r=-2e9;
    int ans=0;
    while(i<n){
        while(i<n&&ranges[i].l<=st){//找到一个能覆盖st并且右端点最长的值
            r=max(ranges[i].r,r);
            i++;
        }
        ans++;
        if(r<=st){//如果最后找到的值没有能覆盖st的就break,如果没有这一步,遇到全部都是大于st的区间就会TLE
            break;
        }
        st=r;//更新st
        if(st>=ed){//如果st已经大于ed了就break
            break;
        }
    }
    if(r>=ed)cout << ans;//判断一下最后覆盖到的区间是否已经过了ed
    else cout << "-1";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值