Stall Reservations

时间:2021-05-23 15:32:47
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.

 
题解:整理区间,将不重合的区间整理成一个区间
需要用到优先队列
当优先队列的元素是结构体时候,需要在结构体内重载比较操作符函数。
 struct node{
int a;
int b;
int flag;
friend bool operator <(node node1,node node2)
{
//<为从大到小排列,>为从小到大排列
return node1.b<node2.b;
}
}n[];
 #include<iostream>
#include<algorithm>
#include<queue>
using namespace std; struct node{
int a; //开始时间
int b; //结束时间
int c; //序列号
int flag; //区间安排序号
friend bool operator <(node node1,node node2) //重载比较操作符函数
{
return node1.b > node2.b;
}
}cows[]; bool cmp1(node t1,node t2) //根据区间排序
{
if(t1.a != t2.a) return t1.a < t2.a;
else return t1.b < t2.b;
} bool cmp2(node t1,node t2) //根据序列号排序
{
return t1.c < t2.c;
} int main()
{
int n;
priority_queue<node>que;
while(~scanf("%d",&n))
{
for(int i = ; i < n; i++)
{
scanf("%d %d",&cows[i].a,&cows[i].b);
cows[i].c = i;
}
sort(cows,cows+n,cmp1);
int ans = ;
cows[].flag = ans;
que.push(cows[]); for(int i = ; i < n; i++)
{
if(que.top().b >= cows[i].a) //此时cows的区间与que内的任意区间有重合
{
ans++;
cows[i].flag = ans;
}
else
{
cows[i].flag = que.top().flag;
que.pop();
}
que.push(cows[i]);
} sort(cows,cows+n,cmp2);
cout<<ans<<endl;
for(int i = ; i < n; i++)
{
printf("%d\n",cows[i].flag);
}
}
return ;
}