区间覆盖问题 例题 POJ 2376

题意:给出N个区间[Li,Ri],选最少数量的区间使得给定区间[l,r]被覆盖。

分析:

贪心经典例题。

将区间按左端点(相同则按右端点)排序,直接用pair就可以。

curR表示当前已经覆盖到的区间右端点,已经讨论到i号区间。

那么  求出满足s[i].x <= R+1 (如果区间是实数区间,这里要注意精度差) 的 s[i].y的最大值Max。

如果Max<=curR表示不能再移动,也就是无解了

curR移动到Max,ans++(表示用了一个新区间)。

如果curR>=R,就表示覆盖完毕。


代码如下:

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>

#define PII pair<int,int>
#define xx first
#define yy second

using namespace std;
const int maxn=30000+5,inf=0x3f3f3f3f;

int n,T;
PII s[maxn];

template <typename T>
inline void _read(T &x){
    char ch=getchar(); bool mark=false;
    for(;!isdigit(ch);ch=getchar())if(ch=='-')mark=true;
    for(x=0;isdigit(ch);ch=getchar())x=x*10+ch-'0';
    if(mark)x=-x;
}

int main(){
    int i;
    _read(n);_read(T);
    for(i=1;i<=n;i++)
    	_read(s[i].xx),_read(s[i].yy);
    sort(s+1,s+1+n);
    int R=0,ans=0;
    i=1;
    while(true){
    	int Max=-1;
    	while(i<=n && s[i].xx<=R+1)
    		Max=max(Max,s[i].yy),i++;
    	if(Max<=R){
    		puts("-1");
    		return 0;
    	}
    	else R=Max,ans++;
    	if(R>=T){
    		cout<<ans<<endl;
    		return 0;
    	}
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值