** Cleaning Shifts **
Farmer John is assigning some of his N (1 <= N <= 25,000) cows to do some cleaning chores around the barn. He always wants to have one cow working on cleaning things up and has divided the day into T shifts (1 <= T <= 1,000,000), the first being shift 1 and the last being shift T.
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
-
Line 1: Two space-separated integers: N and T
-
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 -
Line 1: The minimum number of cows Farmer John needs to hire or -1 if it is not possible to assign a cow to each shift.
Sample Input
3 10
1 7
3 6
6 10
Sample Output
2
Hint
This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed.
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.
**题意:**在让母牛干活时分配奶牛去干活,整个区间至少分配一头奶牛,干活开始时间都为1,给出n头奶牛的开始时间和结束时间和总的工作结束时间t,然后尽可能少的分配奶牛,使得整个时间段都有奶牛,如果某个区间没有奶牛工作,则无法分配奶牛,输出-1。
**思路:**贪心思想,最小区间的覆盖问题,首先对奶牛的开始时间从小到大排序,在开始时间相同的情况下结束时间从大到小排序。
排完序后如果第一头奶牛的开始时间不为1,那就不可能覆盖整个区间,如果第一头奶牛的工作区间覆盖整个工作时间段,那么只需一头奶牛即可。
如果上面两种情况都不符合,找下一个奶牛的开始时间,如果比上一个奶牛的结束时间大2,那么区间就无法覆盖。
如果下一头奶牛开始时间可以和上一个奶牛结束时间对接,就在满足这个条件的情况下找到结束时间最晚的奶牛,这样可以保证分配的奶牛数量最少,最后如果覆盖完区间则输出分配奶牛数量,如果遍历完所有奶牛仍未覆盖完区间则输出-1。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m,i,j,k,l;
struct nn
{
int x,y;
}p[33333];
bool ac(nn a,nn b)
{
if(a.x!=b.x) return a.x<b.x;
else return a.y>b.y;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(i=0;i<n;i++){
scanf("%d%d",&p[i].x,&p[i].y);
if(p[i].x>p[i].y){
int t=p[i].x;
p[i].x=p[i].y;p[i].y=t;
}
}
sort(p,p+n,ac);
int start=1,end=1;
int l=0;
if(p[0].x==1&&p[0].y>=m){
printf("1\n"); continue;//第一头奶牛就满足条件;
}
else if(p[0].x>1) {
printf("-1\n");continue;//第一头奶牛无法覆盖1;
}
//核心
for(i=0;i<n;i++)
{
if(p[i].x<=start)
{
if(p[i].y>end) end=p[i].y;
}
else
{
l++; start=end+1;
if(p[i].x<=start)
end=max(end,p[i].y);
else break;
}
if(end>=m) break;
}
if(end>=m) printf("%d\n",l+1);//完全覆盖
else printf("-1\n");
}
}