POJ3190 Stall Reservations 贪心

题目链接

http://poj.org/problem?id=3190

分析

贪心,先将牛按开始吃草的时间升序排序。

依次考虑每头牛,若其能加入某个已存在的畜栏(即其开始时间晚于该畜栏中上一头牛的结束时间),则加入;

否则新建一个畜栏供其使用。

枚举下一头牛在安置时可能的情况,会发现这样做最优。

AC代码

#include <cstdio>
#include <algorithm>
#include <queue>

using namespace std;

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 5e4 + 5;

struct Cow {
	int id, l, r;

	bool operator < (const Cow& rhs) const {
		return l < rhs.l;
	}
} cow[maxn];

struct Stall {
	int id, last;

	bool operator < (const Stall& rhs) const {
		return last > rhs.last;
	}
};

int ans[maxn], tot;
priority_queue<Stall> q;

int main() {
	int n = read();
	for (int i = 1; i <= n; ++i)
		cow[i].id = i, cow[i].l = read(), cow[i].r = read();
	sort(cow + 1, cow + n + 1);
	for (int i = 1; i <= n; ++i) {
		if (q.empty() || cow[i].l <= q.top().last) {
			ans[cow[i].id] = ++tot;
			q.push((Stall){tot, cow[i].r});
		} else {
			ans[cow[i].id] = q.top().id;
			q.pop();
			q.push((Stall){ans[cow[i].id], cow[i].r});
		}
	}
	printf("%d\n", tot);
	for (int i = 1; i <= n; ++i) printf("%d\n", ans[i]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值