Cleaning Shifts
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 14878 |
|
Accepted: 3804 |
Description
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~T个时间段(注意是时间段,不是时间点),一共有n头牛,每个牛都有自己能工作的时间段(给出开始时间段~结束时间段),要求在T个时间段内每个时间段必须至少有一头牛在打扫仓库,问最少需要安排几头牛,若不能分配牛到每一个时间段,则输出-1。
题解:先将牛按照开始时间从小到大排序,若开始时间相同按照结束从大到小排序。排序后第一头牛的开始时间不是1,则直接输出-1 。 第一头牛开始时间满足时,则当前覆盖的最右端为time=a[0].end ,然后找下一个可行区间,必须满足 a[i].start<=time+1,并保证a[i].end最大。如此查找,直到覆盖住T,若中间有覆盖不住的,输出-1,若所有区间全部全部遍历后,覆盖不住T,则输出-1。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int start,end;
}a[25010];
int cmp(node a,node b)
{
if(a.start==b.start)
return a.end>b.end;
return a.start<b.start;
}
int main()
{
int n,t,i,time;
while(scanf("%d%d",&n,&t)!=EOF)
{
for(i=0;i<n;++i)
scanf("%d%d",&a[i].start,&a[i].end);
sort(a,a+n,cmp);
int ans;
if(a[0].start>1)//不能覆盖第一个时间段的
ans=-1;
else
{
ans=1;
time=a[0].end;
int now_time=time;
int sign=0;
for(i=1;i<n;++i)
{
if(a[i].start<=time+1)
{
if(a[i].end>now_time)
now_time=a[i].end;
if(i==n-1)//当前区间为最后一个可用区间
{
if(now_time>time)
{
time=now_time;
ans++;
}
}
}
else
{
if(now_time>time)//判断是否是确定区间的内含区间
{
time=now_time;
ans++;
if(time==t)//所有区间全部被覆盖了
sign=1;
i--;//当前这个区间还没有被用过
}
else//存在没有被覆盖住的时间段
ans=-1;
}
if(sign==1)
break;
if(ans==-1)
break;
}
}
if(time!=t)
ans=-1;
printf("%d\n",ans);
}
return 0;
}