Stall Reservations
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 4746 | Accepted: 1694 | 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:
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
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.
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.
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:
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.
题意:
某个人有n头奶牛,给出每只奶牛产奶的开始时间和结束时间,问这个人最少需要多少个房子才能使得每只奶牛(好像都是母牛...)产奶的时候都可以单独使用一个房子
输出最少需要的房子的数量,并且按给出的奶牛顺序输出每只奶牛使用的房子的编号(错了两次才发现这个条件!!)
题解:
区间选择问题,贪心的思想
步骤如下:
1,奶牛是需要排序的,但是输出的顺序必须是按给出的顺序,因此需要给每只奶牛编号,用一个数组(num)映射来保存他的位置信息
2,为了使得尽量使得区间不相交,对奶牛排序,一级排序按开始时间递增(最先开始的优先选择),二级排序按结束时间递增
3,使用优先队列,队列中的元素代表当前在产奶的奶牛,队列中的元素结束时间的较小者优先出队,保证尽量空出来多的房子
4,当新加入一只奶牛时,如果队首奶牛还没有产奶结束,只能新使用一个房子,否则就使用当前队首的奶牛使用的房子,并且把队首的奶牛出队(产奶结束)
5,遍历所有奶牛,并记录奶牛的编号和房子的编号的对应关系,最终输出房子的编号即为所求
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
struct cow
{
int bg,ed,num;
bool friend operator <(cow a,cow b)
{
return a.ed>b.ed;
}
}x[100005];
bool cmp(cow a,cow b)
{
if(a.bg==b.bg)
{
a.ed<b.ed;//最早结束的
}
return a.bg<b.bg;
}
int main()
{
int n,num[50005];
//freopen("shuju.txt","r",stdin);
while(~scanf("%d",&n))
{
priority_queue<cow> q;
for(int i=0;i<n;++i)
{
scanf("%d%d",&x[i].bg,&x[i].ed);
x[i].num=i;//牛编上号
}
sort(x,x+n,cmp);//排序
int cnt=0;
num[x[0].num]=cnt++;//第一头牛的编号
q.push(x[0]);
for(int i=1;i<n;++i)
{
cow st=q.top();
if(x[i].bg>st.ed)//有头牛的时间结束
{
q.pop();
num[x[i].num]=num[st.num];//下头牛 使用这个编号
}
else//当前没有结束
{
num[x[i].num]=cnt++;
}
q.push(x[i]);
}
printf("%d\n",cnt);
for(int i=0;i<n;++i)
{
printf("%d\n",num[i]+1);
}
}
return 0;
}