题意:给出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;
}