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
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct Cow{ //定义一个奶牛的结构体,包含奶牛的挤奶开始时间a,结束时间b,和奶牛的序号No
int a;
int b;
int No;
bool operator < (const Cow c) const{ //重载< 以挤奶时间从早到晚排序
return a<c.a;
}
}cow[50010];
int pos[50010]; //编号为i的奶牛的畜栏号
struct Stall{ //畜栏结构体,畜栏的使用只看结束时间,所以包括使用结束时间和畜栏序号
int end;
int No;
bool operator < (const Stall s) const{ //重载< 优先队列中 时间结束早的在前
return end>s.end;
}
Stall(int e,int n):end(e),No(n){}
};
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>cow[i].a>>cow[i].b;
cow[i].No=i;
}
sort(cow,cow+n); //排序
int total=0; //total为畜栏数,开始为0
priority_queue<Stall> pq; //奶牛队列
for(int i=1;i<=n;i++){
if(pq.empty()){ //如果队列为空,即一个也没有时
total++; //即第一个奶牛占第一个畜栏
pq.push(Stall(cow[i].b,total)); //插入奶牛结束挤奶时间和畜栏编号
pos[cow[i].No]=total; //畜栏编号
}
else{
Stall st=pq.top(); //队列不为空时,st为首元素
if(st.end<cow[i].a){ //奶牛结束时间小于另一只开始时间
pq.pop(); //删除此奶牛信息,下一步更新
pos[cow[i].No]=st.No; //此时用同一个畜栏
pq.push(Stall(cow[i].b,st.No)); //更新奶牛信息
}
else{ //奶牛结束时间大于另一只开始时间
total++; //创建新畜栏
pq.push(Stall(cow[i].b,total)); //插入奶牛信息
pos[cow[i].No]=total; //畜栏编号
}
}
}
cout<<total<<endl; //总畜栏数
for(int i=1;i<=n;i++)
cout<<pos[i]<<endl; //奶牛所在畜栏编号
return 0;
}