标签:
Stall Reservations
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Submit Status Practice POJ 3190
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:
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.
题意:
需要安排N头牛在若干机器上进行工作。每一头牛有它自己的一段工作时间(起始时间s~结束时间t)且每头牛都只能单独在一台机器上进行工作。问至少需要多少台机器。
输入:
第一行N,之后N行,每行两个整数表示每一头牛工作时间段的起始时刻与结束时刻。
输出:
最小的机器台数。
分析:
根据贪心的思想。我们先将牛的时间区间按起始时间进行排序,起始时间小的区间排在前面,起始时间相同的则结束时间小的排在前面。然后定义一个优先队列q,将正在工作的牛对应的区间放入该队列,结束时间小的排在前面。一开始我们遍历每一个牛区间,这时如果我们查找发现优先队列q的队首元素的右区间小于遍历到的牛区间的左端点,则说明之前被一头牛占用的一台机器已经空出来了。那么这时候安排当前牛到那空出来的机器上去工作,否则新增一台机器。
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <queue> 5 using namespace std; 6 #define MAX_N 50000 7 int n,use[MAX_N + 1]; 8 struct Node{ 9 int l,r,pos; 10 bool operator <(const Node &a)const { 11 //if(r == a.r) return l > a.l; 12 return r > a.r; 13 } 14 }a[MAX_N + 1]; 15 priority_queue<Node> q; 16 bool cmp(Node a,Node b){ 17 if(a.l == b.l) return a.r < b.r; 18 return a.l < b.l; 19 } 20 int main(){ 21 while(scanf("%d",&n) != EOF){ 22 for(int i = 0 ; i < n ; i++){ 23 scanf("%d%d",&a[i].l,&a[i].r); 24 a[i].pos = i; 25 } 26 sort(a,a + n,cmp); 27 q.push(a[0]); 28 int now = 0,ans = 1; 29 use[a[0].pos] = 1; 30 for(int i = 1 ; i < n ; i++){ 31 if(!q.empty() && q.top().r < a[i].l){ 32 use[a[i].pos] = use[q.top().pos]; 33 q.pop(); 34 } 35 else{ 36 ans++; 37 use[a[i].pos] = ans; 38 } 39 q.push(a[i]); 40 } 41 printf("%d\n",ans); 42 for(int i = 0 ; i < n ; i++) 43 printf("%d\n",use[i]); 44 while(!q.empty()) q.pop(); 45 } 46 return 0; 47 }
标签:
原文地址:http://www.cnblogs.com/cyb123456/p/5785882.html