题目是每只奶牛负责一个时间段,让你求覆盖完全部的时间段最少需要多少只奶牛,如果不能覆盖完输出“-1”,但是很多人理解成把整个区间都覆盖完需要多少个小区间,其实是覆盖完所有点需要多少的小区间,例如:
2 10
1 5
6 10
这样是可以覆盖完所有点的,所以输出2,而不是-1.
这个题目的思路是贪心,按起点由小到大排序,同一起点的,按能够延伸的长度由长到短排序,这样我们从起点开始,每次选择能够延伸的最长的线段,当然这个线段的起点要在前一个区间的范围内,或者就是前一个区间的终点的下一个点(就是上面的例子那样),如果找不到起点在这个范围内或者是下一个点的线段,并且还没覆盖完全,输出“-1”。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int n,t;
struct po
{
int l,r;
int c;
}a[150000];
bool cmp(po x, po y)
{
if(x.l != y.l)
return x.l<y.l;
else return x.c > y.c;
}
int main()
{
scanf("%d%d",&n,&t);int ok=0,ok2=0;
for(int i = 1; i <= n; i ++)
{
scanf("%d%d",&a[i].l,&a[i].r);
a[i].c = a[i].r - a[i].l;
if(a[i].l == 1) ok = 1;
if(a[i].r == t) ok2 = 1;
}
if(!ok||!ok2)
{
puts("-1");
return 0;
}
sort(a+1,a+n+1,cmp);
bool flag = 0;int ans = 0;
int j = 0,st = 1;
int end = 1;
while(end < t)
{
for(int i = st; i <= n; i ++)
{
if(a[i].l <= j+1)
{
end = max(a[i].r,end);
}
else
{
st = i;
break;
}
}
if(end == j)//两次找到的终点是同一个线段的终点,就说明无法继续向前延伸了
{
flag = 1;
break;
}
j = end;
ans ++;
}
if(flag)
puts("-1");
else cout <<ans<<endl;
return 0;
}