戳我进题
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
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.
题意:
建最少的stall在最少的时间内把所有牛的奶都挤了,这些母牛“不愿意和别的母牛一起分享这样私密的时刻”,(我怀疑它们已经成精了,但是没有证据) ,所以每头母牛在自己的挤奶时间段里面stall里只能有它一头母牛,等它挤完奶下一头母牛才能进stall挤奶。
思路:
stall尽量都满,用优先队列来维护时间,(等下整理补个优先队列的blog),用空间最多的stall来装,装不下的话其他的stall也装不下,就多建一个stall,用母牛的左右时间点来贪心
略绕
AC代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
int vis[52000]={0};///存每头牛用的stall号码
struct node
{
int l,r;///左右时间点
int pos;///母牛编号
bool operator < (const node &a)const
{
return r>a.r||(r==a.r&&l>a.l);
}
}cow[52000];
bool cmp(node a,node b)
{
if(a.l==b.l)
return a.r<b.r;
return a.l<b.l;
}
int main()
{
int n;
scanf("%d",&n);
int x,y;
priority_queue <node > cowque;
for(int i=0;i<n;i++)
{
scanf("%d%d",&x,&y);
cow[i].l=x;
cow[i].r=y;
cow[i].pos=i;
}
sort(cow,cow+n,cmp);
cowque.push(cow[0]);
vis[cow[0].pos]=1;
int stall=1;
for(int i=1;i<n;i++)
{
if(!cowque.empty()&&cow[i].l>cowque.top().r)
{
vis[cow[i].pos]=vis[cowque.top().pos];
cowque.pop();
}
else
{
stall++;
vis[cow[i].pos]=stall;
}
cowque.push(cow[i]);
}
printf("%d\n",stall);
for(int i=0;i<n;i++)
printf("%d\n",vis[i]);
return 0;
}