Stall Reservations
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 6315 | Accepted: 2302 | Special Judge |
Description
Oh those picky N (1 <= N <= 50,000) cows! They are so picky that each one will only be milked over some precise time interval A..B (1 <= A <= B <= 1,000,000), which includes both times A and B. Obviously, FJ must create a reservation system to determine which stall each cow can be assigned for her milking time. Of course, no cow will share such a private moment with other cows.
Help FJ by determining:
Help FJ by determining:
- The minimum number of stalls required in the barn so that each cow can have her private milking period
- An assignment of cows to these stalls over time
Input
Line 1: A single integer, N
Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
Output
Line 1: The minimum number of stalls the barn must have.
Lines 2..N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.
Lines 2..N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.
Sample Input
5 1 10 2 4 3 6 5 8 4 7
Sample Output
4 1 2 3 2 4
Hint
Explanation of the sample:
Here's a graphical schedule for this output:
Here's a graphical schedule for this output:
Time 1 2 3 4 5 6 7 8 9 10 Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>> Stall 2 .. c2>>>>>> c4>>>>>>>>> .. .. Stall 3 .. .. c3>>>>>>>>> .. .. .. .. Stall 4 .. .. .. c5>>>>>>>>> .. .. ..Other outputs using the same number of stalls are possible.
大致题意:
有一群牛,每个牛都有固定的吃饭时间,并且一个牛槽只能同时让一只牛吃饭。给出所有牛吃饭的开始时间和结束时间,求出最优的策略,使用最少的牛槽让所有的牛吃上饭。输出最少的牛槽数,以及每个牛在第几个牛槽吃。
大体思路:
贪心。用到了优先队列。
1)将牛按照开始时间由小到大排序,开始时间相等的话按结束时间由小到大排序。
2)创建一个优先队列,在队列中牛按照结束的时间从小到大排序。
3)把第一只牛加入队列,然后检查第二只牛能否和它同用一槽。如果能,第一只牛出队列,第二只牛进队列。若不能,第二只牛进队列,牛槽数加一。继续该步骤,知道所有的牛都吃过了。
4)注意,记录牛的数据时,除了开始和结束时间,还要记录牛一开始的顺序,以便记录它在哪个槽吃。
#include<cstdio>
#include<algorithm>
#include<queue>
struct Cow{
int s,e,n;
friend const bool operator < (const Cow x,const Cow y)
{
return (x.e==y.e)?x.s>y.s:x.e>y.e;
}
}C[50005];
int Ans[50005];
bool cmp (Cow x,Cow y)
{
return (x.s==y.s)?x.e<y.e:x.s<y.s;
}
int main()
{
//freopen("in.txt","r",stdin);
int N,a;
while(scanf("%d",&N)!=EOF){
for(int i=0;i<N;i++){
scanf("%d%d",&C[i].s,&C[i].e);
C[i].n=i;
}
std::sort(C,C+N,cmp);
std::priority_queue<Cow>qu;
qu.push(C[0]);
Ans[C[0].n]=a=1;
for(int i=1;i<N;i++){
if(qu.top().e<C[i].s){
Ans[C[i].n]=Ans[qu.top().n];
qu.pop();
}
else{
Ans[C[i].n]=++a;
}
qu.push(C[i]);
}
printf("%d\n",a);
for(int i=0;i<N;i++)
printf("%d\n",Ans[i]);
}
return 0;
}