Stall Reservations
Time Limit:
1000MS
Memory Limit:
65536KB
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.
题意:n头牛,每头牛的挤奶时间,问你最少需要几台机器工作,然后对每头牛所工作机器的编号。
做法:贪心,排序,如果l相等,r小的排前面,否则l小的排前面,维护一个优先队列,正在工作的机器且优先结束的机器排在最前面,判断这台机器奶牛是否能用,如果不能用,那么再加一台机器。
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
struct node{
int x,y,i;
bool operator <(const node &a)const {
if(y==a.y)return x>a.x;
return y>a.y; //先结束的排前面
}
}e[50005];
bool cmp(node a,node b){
if(a.x==b.y)return a.y<b.y;
return a.x<b.x;
}
int use[50005];
priority_queue<node>sp;
int main(){
int n,i,j;
while(scanf("%d",&n)!=EOF){
for(i=1;i<=n;i++){
scanf("%d%d",&e[i].x,&e[i].y);
e[i].i=i;
}
sort(e+1,e+1+n,cmp);
int cnt=1;
use[e[1].i]=1;
sp.push(e[1]);
for(i=2;i<=n;i++){
if(!sp.empty()&&sp.top().y<e[i].x){//如果队列非空且最先结束的机器的时间小于当前奶牛开始时间
use[e[i].i]=use[sp.top().i];
sp.pop();
}
else{//否则就再加一台机器
cnt++;
use[e[i].i]=cnt;
}
sp.push(e[i]);
}
printf("%d\n",cnt);
for(i=1;i<=n;i++){
printf("%d\n",use[i]);
}
while(!sp.empty())sp.pop();
}
return 0;
}