POJ 3190 Stall Reservations贪心
Posted 爱国呐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 3190 Stall Reservations贪心相关的知识,希望对你有一定的参考价值。
POJ 3190 Stall Reservations贪心
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
Sample Input 5 1 10 2 4 3 6 5 8 4 7 Sample Output 4 1 2 3 2 4
题意:
一些奶牛要在指定的时间内挤牛奶,而一个机器只能同时对一个奶牛工作。给你每头奶牛的指定时间的区间,问你最小需要多少机器。
思路:
按奶牛要求的时间起始点进行从小到大排序,然后维护一个优先队列,里面以已经开始挤奶的奶牛的结束时间早为优先。然后每次只需要检查当前是否有奶牛的挤奶工作已经完成的机器即可,若有,则换那台机器进行工作。若没有,则加一台新的机器。这个题是会场安排问题的升级版,题目链接:这里,将会场举行的每一场写出来。这里绝不可以两层循环,两层循环会超时,用优先队列代替一层循环写不会超时。
代码:
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; const int maxn=60000; int n,use[maxn]; struct Node { int left;//开始时间 int right;//结束时间 int pos;//记录标号用来排序 friend bool operator <(Node a,Node b) { if(a.right==b.right) return a.left>b.left; return a.right>b.right; }//优先队列按照结束时间从小到大排序,结束时间相等,开始时从小到大排序 } a[maxn]; priority_queue<Node> q; bool cmp(Node a,Node b) { if(a.left==b.left) return a.right<b.right; return a.left<b.left; } int main() { while(~scanf("%d",&n)) { for(int i=0; i<n; i++) { scanf("%d%d",&a[i].left,&a[i].right); a[i].pos=i; } sort(a,a+n,cmp);//按照结束时间从小到大排序 q.push(a[0]); int now=0,ans=1; use[a[0].pos]=1; for(int i=1; i<n; i++) { if(!q.empty()&&q.top().right<a[i].left) { use[a[i].pos]=use[q.top().pos]; q.pop(); } else { ans++; use[a[i].pos]=ans; } q.push(a[i]); } printf("%d\n",ans); for(int i=0; i<n; i++) printf("%d\n",use[i]); while(!q.empty()) q.pop(); } return 0; }
以上是关于POJ 3190 Stall Reservations贪心的主要内容,如果未能解决你的问题,请参考以下文章