题目
有一些奶牛,每只奶牛负责一个时间段。问覆盖完全部的时间段最少需要多少只奶牛。若不能全部覆盖,输出-1
样例
分析
- 按着开始时间升序排序
- 找寻开始时间(
a[i].begin
)在当前结束时间(pos
)前的结束时间(a[i].end
)最后的奶牛。
坑
- 时间可以是一只牛[2,3],一只牛[4,5],也算覆盖了。
- 循环时注意下 i pos 的取值范围(小于 n 和 t)不然会WA。
AC 代码
#include<iostream>
#include<algorithm>
#define N 25005
using namespace std;
struct node {
long long start;
long long end;
};
bool cmp(const node&l,const node&r) {
if(l.start!=r.start)
return l.start<r.start;
return l.end<r.end;
}
node a[N];
int main() {
long long n,t;
scanf("%lld%lld",&n,&t);
for(int i=0; i<n; i++)
cin>>a[i].start>>a[i].end;
sort(a,a+n,cmp);
if(a[0].start!=1) {
cout<<"-1";
return 0;
}
long long sum=0,temp=0,pos=0,i=0;
while(i<n&& pos<t) {
if(a[i].start>pos+1) {//可以是 [1,5][6,7]
break;
}
while(a[i].start<=pos+1 && i<n) {
temp=max(temp,a[i].end);//满足条件的最后的位置
i++;
}
pos=temp;//pos:当前最后的已被安排的位置
sum++;
}
if(pos<t)
cout<<"-1\n";
else
cout<<sum<<endl;
}