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 Input

5
1 10
2 4
3 6
5 8
4 7

Sample Output

4
1
2
3
2
4

思路

定义一个优先队列,按照棚子的使用结束时间排序。将所有的牛按照开始时间排序。遍历每一个牛,如果牛的开始时间小于队列首元素,因为是按序排的,所以队列中所有的都大于牛的开始时间,也就是现在有的棚子都在使用用,就需要再加一个棚子。如果牛开始的时间大于队列首元素,那么这个棚子就可以用,将棚子的时间修改再加入至队列中。另外,需要注意,需要输出每个牛的棚子编号,但顺序需要为题中的顺序而不是按从小到大排序后的顺序。

代码

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;

struct cow
{
    
    
	int s,e,n,st;					//s 起始时间  e 结束时间 
}c[50005];							//n 牛的编号 st 棚子的编号 

struct stall
{
    
    
	int n,t;						//n 棚子的编号 t棚子的使用结束时间 
	friend bool operator < (const stall a,const stall b)
	{
    
    
		return a.t>b.t;				//队列排列顺序按时间从小到大 
	}
};

priority_queue<stall> q;			//棚子的优先队列 

bool cmp(const cow a,const cow b)
{
    
    
	return a.s<b.s;					//牛按照开始时间排序 
}

bool cmpp(const cow a,const cow b)
{
    
    
	return a.n<b.n;					//牛按照编号排序  以便按照题中顺序输出棚子编号 
}

int main()
{
    
    
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
    
    
		scanf("%d%d",&c[i].s,&c[i].e);
		c[i].n=i;					//牛的编号 
	}	
	sort(c+1,c+n+1,cmp);			//起始时间排序 
	stall tmp;
	int cnt=0;
	tmp.n=++cnt;					//将第一个棚子加入队列 
	tmp.t=c[1].e;
	q.push(tmp);
	c[1].st=tmp.n; 	
	for(int i=2;i<=n;i++)
	{
    
    
		tmp=q.top();				//队列首元素 
		if(tmp.t>=c[i].s)			//队列中的棚子不可用 
			tmp.n=++cnt;			//新棚子编号 
		else
			q.pop();				//队列中的棚子可用 将原棚子踢出队列,改变时间后重新加入 
		tmp.t=c[i].e;				//更新时间 
		q.push(tmp);				//加入队列 
		c[i].st=tmp.n;				//牛对应的棚子编号 
	}	
	cout<<cnt<<endl;
	sort(c+1,c+n+1,cmpp);			//恢复题中输入顺序 
	for(int i=1;i<=n;i++)
		printf("%d\n",c[i].st);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_54621932/article/details/113922153