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
大致意思:有 n头牛(1<=n<=50,000)要挤奶。给定每头牛挤奶的时间区间[A,B] (1<=A<=B<=1,000,000,A,B为整数)。
牛需要呆畜栏里才能挤奶。一个畜栏同一时间只能容纳一头牛。问至少需要多少个畜栏,才能完成全部挤奶工作,以及每头牛都
放哪个畜栏里(Special judged)
去同一个畜栏的两头牛,它们挤奶时间区间哪怕只在端点重合也是不可以的。
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXC = 50000+10;
struct cow{
int s,e,num;
bool operator < (const cow &c) const{
return s < c.s;
}
}cows[MAXC];
struct stall{
int num,e;
bool operator < (const stall &s) const{
return e > s.e;
}
};
priority_queue<stall> p;
int solve[MAXC];
int main(){
int n;
cin >> n;
for(int i = 0;i<n;i++){
cows[i].num = i+1;
cin >> cows[i].s >> cows[i].e;
}
sort(cows,cows+n);
stall early;
//处理第一只牛
int cnt = 1;
early.num = cnt;
early.e = cows[0].e;
p.push(early);
solve[cows[0].num] = cnt;
for(int i = 1;i<n;i++){
early = p.top();
p.pop();
if(cows[i].s > early.e){
solve[cows[i].num] = early.num;
early.e = cows[i].e;
}else{
cnt++;
solve[cows[i].num] = cnt;
stall news;
news.num = cnt;
news.e = cows[i].e;
p.push(news);
}
p.push(early);
}
cout << cnt << endl;
for(int i = 1;i<=n;i++)
cout << solve[i] << endl;
return 0;
}