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.
C++编写:
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAX_N=25010;
struct Time_sch{
int begin,end;
}sch[MAX_N];
int N,T;
bool compare(const Time_sch& a, const Time_sch& b)
{
return a.begin < b.begin || (a.begin == b.begin && a.end > b.end);
}
void solve()
{
for(int i=0;i<N;i++) //读入数据
cin>>sch[i].begin>>sch[i].end;
sort(sch,sch+N,compare); //按照开始时间从小到大排序,如果开始时间相同,按照结束时间从大到小排序
int sum=0,right=0,i=0;
while(right<T && i<N)
{
sum++; //进入循环,必选一头牛
int temp=right;
if(sch[i].begin > right+1)
break; //如果下一头牛的开始班次都大于了前一头牛的结束班次的下一班次,则肯定无法实现
while(sch[i].begin <= right+1 && i<N)
temp=max(temp,sch[i++].end);
right=temp; //记录下此时的末尾班次
}
if(right>=T)
cout<<sum<<endl;
else
cout<<-1<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin>>N>>T;
solve();
}
博客围绕奶牛清洁班次分配问题展开,农场主John有N头奶牛,需将一天分为T个班次,每头奶牛有工作时间区间。要使每个班次至少有一头奶牛且参与奶牛数最少,若无法分配则输出 -1。还给出输入输出格式及示例,最后提及用C++编写。
775

被折叠的 条评论
为什么被折叠?



