区间覆盖问题【贪心】【双指针】

https://www.acwing.com/activity/content/problem/content/1114/1/
贪心思路:
把所有区间按照起点排序
遍历每个区间,找到可以进过st的最远距离,用双指针算法

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
typedef pair<int,int> pll;
pll p[N];
int main(){
    int st,se;
    cin>>st>>se;
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>p[i].first>>p[i].second;

    }
    sort(p,p+n);
    int res=0;
    for(int i=0;i<n;i++){
        int j=i,r=-2e9;
       //找到最远的点;
        while(j<n&& p[j].first<=st){
            r=max(r,p[j].second);
            j++;
        }
        //如果最远的点没有经过st 无解;
        if(r<st){
            res=-1;
            break;
        }
        res ++ ;
        if (r >= se) break;
        st = r;

        i = j -1;
    }
    cout<<res<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值