POJ - 3190 Stall Reservations 【贪心】【优先队列】

题目链接:https://cn.vjudge.net/problem/POJ-3190

 POJ不会不对外开放了吧天天进不去好坑啊,这个题vj交不上poj进不去。。。不确定能A,但个人认为没问题

思路:贪心,具体思路看代码有注释,优先队列可以用二分查找+插入+删除代替,时间复杂度O(nlogn),不会T

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 5e4+5;
struct Cow {
	int s,e;		// 开始和结束时间
	int b; 			// 所在牛棚
	bool operator < (const Cow &t) {
		return s < t.s;
	}
}Cows[maxn];
struct Barn
{
	int num, end;   // 编号 当前结束时间
	friend bool operator < (const Barn &t1,const Barn &t2) {
		return t1.end > t2.end;
	}
};
int main()
{
	int n;
	scanf("%d",&n);

	for(int i=1;i<=n;i++)
		scanf("%d %d",&Cows[i].s,&Cows[i].e);		//cin >> Cows[i].s >> Cows[i].e;

	sort(Cows+1,Cows+n+1);

	priority_queue< Barn> Barns;		// 按从结束时间排序,结束时间小的放在前边
	Barn tttt;		// 先加一个结束时间为无穷大的牛棚放到队列中,方便后续操作,不算在总需要牛棚内
	tttt.num = inf;	
	tttt.end = inf;
	Barns.push(tttt);	
	
	int sum = 0; 		// 所需牛棚总数
	Barn temp;
	for(int i=1;i<=n;i++) {
		temp = Barns.top();
		if(temp.end >= Cows[i].s) {		//最早结束的牛棚结束时间 >= 先最先需要产奶的牛的产奶时间
			sum++;		// 增加一个牛棚;
			Barn newBarn;
			newBarn.num = sum;
			newBarn.end = Cows[i].e;
			Barns.push(newBarn);
			Cows[i].b = sum;
		}
		else {
			Barns.pop();
			temp.end = Cows[i].e;
			Barns.push(temp);
			Cows[i].b = temp.num;
		}
	}
	printf("%d\n",sum);
	for(int i=1;i<=n;i++)
		printf("%d\n",Cows[i].b);
}

猜你喜欢

转载自blog.csdn.net/weixin_42765557/article/details/84890259