链接:http://poj.org/problem?id=2376
题意:每头牛给出对应打扫卫生的时间区间,要保证每个时间点都有牛打扫,并且求出这样所需要的最少的牛的数量。不能保证就输出-1.
典型的区间贪心,水水来找点信心orz
思路:每头牛的起点升序排列,如果第一头牛的起点不是1,直接不可能。对于每个确定要使用的牛,从下一头开始找,找出区间有重合(此处要小心),并且终点最远的那个,然后确定使用这头,在循环这个操作,直到确定的牛的终点已经是所需要的最远的了。
对于下一头的区间重合要小心,WA了一发,题目中说A cow starts work at the start time and finishes after the end time. 所以只需要下一个牛起点小于等于前一个确定的牛的终点+1,就是可以继续工作了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define M 25009
#define INF 0x3f3f3f3f
typedef struct
{
int s,e;
}state;
state a[M];
int n,m;
int cmp(state a ,state b)
{
if(a.s != b.s) return a.s < b.s;
return a.e < b.e;
}
int main()
{
while(scanf("%d %d",&n,&m)==2)
{
for(int i = 0;i < n;i++)
{
scanf("%d %d",&a[i].s,&a[i].e);
}
sort(a,a+n,cmp);
if(a[0].s != 1)
{
printf("-1\n");
continue;
}
int cur = 0;
bool ok = false;
int ans = 1;
while(cur < n)
{
int k = -1;
int maxn = -INF;
int nx = cur+1;
if(a[cur].e >= m) break;
while(nx < n && a[nx].s <= a[cur].e+1) // 要注意a[nx].s <= a[cur].e+1
{
if(a[nx].e > maxn) //取出符合条件中的 停止时间最远的一个。
{
k = nx;
maxn = a[nx].e;
}
nx++;
}
if(k == -1)
{
ok = true;
break;
}
ans++;
cur = k;
}
if(ok) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}