挑战程序设竞赛里的练习题 poj2376
Description
Each cow is only available at some interval of times during the day for work on cleaning. Any cow that is selected for cleaning duty will work for the entirety of her interval.
Your job is to help Farmer John assign some cows to shifts so that (i) every shift has at least one cow assigned to it, and (ii) as few cows as possible are involved in cleaning. If it is not possible to assign a cow to each shift, print -1.
Input
* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.
Output
Sample Input
3 10 1 7 3 6 6 10
Sample Output
2
Hint
INPUT DETAILS:
There are 3 cows and 10 shifts. Cow #1 can work shifts 1..7, cow #2 can work shifts 3..6, and cow #3 can work shifts 6..10.
OUTPUT DETAILS:
By selecting cows #1 and #3, all shifts are covered. There is no way to cover all the shifts using fewer than 2 cows.
#include<iostream>
#include<cstdio>
#include<algorithm>
#define Max 50000
using namespace std;
pair<int,int> it[Max];
int N,T;
bool cmp(pair<int,int>a,pair<int,int >b){
if(a.first==b.first) return a.second>b.second;
else return a.first<b.first;
}//开始时间一样按大小排序 否则选开始早的 贪心覆盖
int main()
{
cin>>N>>T;
for(int i=0;i<N;i++)
{
cin>>it[i].first>>it[i].second;
}
sort(it,it+N,cmp);
if(it[0].first==1&&it[0].second>=T)//第一头牛完全覆盖
{
printf("1\n");
return 0;
}
if(it[0].first!=1)//第一头牛不合题意
{
printf("-1\n");
return 0;
}
int end=it[0].second;
int cnt=1;
for(int i=1;i<N&&end<T;)
{
cnt++;
int mm=end;
if(it[i].first>end+1)//第i头牛越界了 不能覆盖
{
printf("-1\n");
return 0;
}
while(i<N&&it[i].first<=end+1){
//可以覆盖
mm=max(mm,it[i].second);//选取最大值
i++;
}
end=mm;//更新结束点
if(end>=T)//结束了
break;
}
if(end<T) printf("-1\n");
else printf("%d\n",cnt);
return 0;
}