Stall Reservations
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 10799 | Accepted: 3818 | 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:
- 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
Many answers are correct for each test dataset; a program will grade your answer.
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.
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.
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:
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.
Source
源代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
struct cow{
int a;
int b;
int id;
bool operator <(const cow &c) const{
return a<c.a;
}
}cows[50000+5];
int pos[50000+5];//表示编号为i的奶牛去的畜栏编号
struct Stall{
int e;//设置畜栏结束使用时间,也就是奶牛挤完奶的时间
int id;//设置畜栏的编号
bool operator<(const Stall &s)const{
return e>s.e;
//结束时间越早的优先级越高
}
Stall(int e,int n):e(e),id(n){}
};
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d",&cows[i].a,&cows[i].b);
cows[i].id=i;//奶牛的编号就是变量i
}
sort(cows,cows+n);
int total=0;//设置栅栏计数
priority_queue<Stall>pq;//设置畜栏队列pq
for(int i=0;i<n;++i){
if(pq.empty()){//畜栏为空的情况,对应i等于的情况
++total;
pq.push(Stall(cows[i].b,total));//将奶牛结束时间,畜栏数目压入对列
pos[cows[i].id]=total;
}
else{//对应i不为0的情况
Stall st =pq.top();//取顶操作
if(st.e<cows[i].a){//端点也不能重合
pq.pop();//弹出操作
pos[cows[i].id]=st.id;//记录畜栏id
pq.push(Stall(cows[i].b,st.id));//不断更新畜栏结束时间还有队顶id
}
else{//找不到空的畜栏
++total;
pq.push(Stall(cows[i].b,total));
pos[cows[i].id]=total;
}
}
}
printf("%d\n",total);
for(int i=0;i<n;i++)
printf("%d\n",pos[i]);
return 0;
}
思路:明显要先处理产奶时间靠前并且结束时间靠前的奶牛,这样才能使后面的奶牛接着使用同一畜栏。
这里就要使用到优先队列priority_queue。
操作步骤如下:
①所有奶牛按照开始时间从小到大排序。
②为第一头奶牛分配一个畜栏
③依次处理后面每头奶牛i,考虑已经分配到畜栏中,结束时间最早的畜栏x
使得结束时间最早的畜栏始终位于队列头部。