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:

    •   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
Sample Input

Sample Output

题意:

  一些奶牛要在指定的时间内挤牛奶,而一个机器只能同时对一个奶牛工作。给你每头奶牛的指定时间的区间,问你最小需要多少机器。

思路:

  按奶牛要求的时间起始点进行从小到大排序,然后维护一个优先队列,里面以已经开始挤奶的奶牛的结束时间早为优先。然后每次只需要检查当前是否有奶牛的挤奶工作已经完成的机器即可,若有,则换那台机器进行工作。若没有,则加一台新的机器。这个题是会场安排问题的升级版,题目链接:这里,将会场举行的每一场写出来。这里绝不可以两层循环,两层循环会超时,用优先队列代替一层循环写不会超时。

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=;
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=; i<n; i++)
{
scanf("%d%d",&a[i].left,&a[i].right);
a[i].pos=i;
}
sort(a,a+n,cmp);//按照结束时间从小到大排序
q.push(a[]);
int now=,ans=;
use[a[].pos]=;
for(int i=; 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=; i<n; i++)
printf("%d\n",use[i]);
while(!q.empty())
q.pop();
}
return ;
}
上一篇:Greedy:Stall Reservations(POJ 3190)


下一篇:2013年7月份第3周51Aspx源码发布详情