Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 10784 | Accepted: 3813 | 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:
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
解题思路:
奶牛到挤奶的时间就必须要挤,只需逐个观察该奶牛需要挤奶时,有没有空牛棚即可。
1)把所有奶牛根据开始时间从小到大进行排序。
2)为第一头奶牛分配一个牛棚。
3)依次对后面的奶牛进行操作,处理第 i 头时,考虑这时有没有空牛棚(上一只奶牛挤奶结束)。
令结束时间最早的牛棚结束时间为E(x)(奶牛挤奶结束时间),S(i)为第i头奶牛开始的时间
如果E(x) < S(i) 则不用新增牛棚,i 可以进入 x,并修改E(i)。
如果E(x) >= S(i) 则需要新增牛棚,并使该牛棚的结束事假为E(i)。
在为牛分配牛棚时存在三种情况
1)还没有建造过牛棚,此时就要新增牛棚,并把牛棚结束时间改为第一头牛的E(i)。
2)建过牛棚,该牛可以进入最早结束的牛棚进行操作。
3)建过牛棚,但是最早结束的牛棚的结束时间 >= 该牛的开始时间,则要新增牛棚。
注意:优先队列默认为从大到小排列,如果要从小到大,排列规则的符号与一般的相反(> 改成 <)
代码:
#include
#include
#include
#include
using namespace std;
struct cow {
int a,b;
int nu; //牛的编号
bool operator < (const cow & c) const{
return a < c.a;
}
}cows[50000+10];
int pos [50000+10]; //pos[i]表示编号为i的牛去的牛棚
struct stall{
int end;
int nu;
bool operator <(const stall & c) const{
return end > c.end;
}
stall(int x,int y):end(x),nu(y){ }
};
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].nu = i;
}
sort(cows,cows+n);
int total = 0;
priority_queue pq;
for(int i = 0;i < n;i++){
if(pq.empty()){
total++;
pq.push (stall(cows[i].b,total));
pos[cows[i].nu] = total;
}
else{
stall st = pq.top();
if(st.end < cows[i].a){
pq.pop();
pos[cows[i].nu] = st.nu;
pq.push (stall(cows[i].b,st.nu));
}
else{
total++;
pos[cows[i].nu] = total;
pq.push (stall(cows[i].b,total));
}
}
}
printf("%d\n",total);
for(int i = 0;i < n;i++){
printf("%d\n",pos[i]);
}
return 0;
}