【题目】
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.
【输入】
Line 1: A single integer, N <br> <br>Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
【输出】
Line 1: The minimum number of stalls the barn must have. <br> <br>Lines 2..N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.
【样例】
输入:
5
1 10
2 4
3 6
5 8
4 7
输出:
4
1
2
3
2
4
题目大意:一群奶牛,有格子固定的产奶时间,每头牛产奶时需要产奶机器,为了满足所有牛产奶,最后需要多少个产奶机器,并顺序输出他们需要的产奶机器的编号
思路:
-
先按照牛产奶开始时间从小到大排序,如果开始时间相同,则按照结束时间从小到大排序
-
用一个优先产奶结束时间的优先队列去维护当前产奶奶牛
-
若下一个奶牛的开始产奶时间小于或等于当前奶牛的产奶结束时间,则需要一个新的产奶机器ans++,下一奶牛加入队列,若大于当前奶牛的产奶结束时间,则不需要新的产奶机器,并更新当前产奶奶牛
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int per[50010];
struct node
{
int st,en,pos;
}cow[50010],now;
bool operator<(const node & a,const node & b)
{
if(a.en==b.en)
return a.st>b.st;
return a.en>b.en;
}
int cmp(node a,node b)
{
if(a.st==b.st)
return a.en<b.en;
return a.st<b.st;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%d%d",&cow[i].st,&cow[i].en);
cow[i].pos=i; //数据初始编号
}
sort(cow,cow+n,cmp);
memset(per,0,sizeof(per));
priority_queue<node>q;
q.push(cow[0]);
per[cow[0].pos]=1;
int ans=1;
for(int i=1;i<=n-1;i++)
{
now=q.top();
if(cow[i].st>now.en)
{
per[cow[i].pos]=per[now.pos];
q.pop();
}
else
{
ans++;
per[cow[i].pos]=ans;
}
q.push(cow[i]);
}
printf("%d\n",ans);
for(int j=0;j<n;j++)
printf("%d\n",per[j]);
}
return 0;
}