Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 10801 | Accepted: 3819 | 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:
- 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.
Source
题意:一群很有个性的奶牛,只在固定的时间产奶,每头牛需要用一个挤奶机器,问为满足所有牛产奶,最少需要多少个挤奶机器,并按照奶牛给出的顺序来输出该奶牛挤奶机器的编号。
思路: 创建结构体Cow,储存奶牛的编号、开始时间和完成时间。先对奶牛的开始时间排序,找到使用挤奶器的顺序。创建结构体Stall储存挤奶器的结束时间(实际上就是使用这个挤奶器的牛的完成时间)和挤奶器的编号(因为最后要输出使用挤奶器的个数和编号),采用优先队列的方法(挤奶器的结束时间为根据)保证结束时间早的可以被合适的重新利用。而优先队列中又有三种情况,第一,没有使用挤奶器,也就是没有奶牛;第二,有奶牛,但是结束不符合;第三种,有奶牛,结束时间也符合。
需要注意的是 这里边的变量很多,需要仔细的弄清楚他们的含义,以及对于优先队列的掌握情况。
这篇博客,讲的优先队列很透彻 https://blog.youkuaiyun.com/c20182030/article/details/70757660
话不多说,上代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct Cow{
int a,b;
int No;
bool operator < (const Cow &c) const{
return a<c.a;
}
}cows[50100];
int pos[50100];
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;
scanf("%d",&n);//
for(int i=0;i<n;i++){
scanf("%d %d",&cows[i].a,&cows[i].b);
cows[i].No=i;///
}
sort(cows,cows+n);
int total=0;
priority_queue<Stall> pq;
for(int i=0;i<n;i++){//
if(pq.empty()){
total++;
pq.push(Stall(cows[i].b,total));
pos[cows[i].No]=total;
}
else{
Stall st=pq.top();
if(st.end<cows[i].a){//
pq.pop();
pos[cows[i].No]=st.No;
pq.push(Stall(cows[i].b,st.No));
}
else{
total++;
pq.push(Stall(cows[i].b,total));
pos[cows[i].No]=total;
}
}
}
printf("%d\n",total);
for(int i=0;i<n;i++){
printf("%d\n",pos[i]);
}
return 0;
}