POJ1456 Supermarket 堆

题目链接

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

分析

将商品按过期时间排成不降序,依次考虑每件商品,建一个节点为商品价值的小根堆。

比较商品的过期时间与堆中元素个数,若大于,则将该商品价值插入;

若等于,则比较商品价值与堆顶,若大于,则弹出堆顶,再将该商品价值插入。

这就做到了在不卖过期商品的前提下,尽量卖出价值排名靠前的商品。

AC代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

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 = 1e4 + 5;

struct Heap {
	int h[maxn], tot;

	Heap() {
		memset(h, 0, sizeof(h));
		tot = 0;
	}

	void up(int p) {
		while (p > 1) {
			if (h[p] < h[p / 2]) swap(h[p], h[p / 2]), p /= 2;
			else break;
		}
	}

	void down(int p) {
		while (2 * p <= tot) {
			int q = 2 * p;
			if (q + 1 <= tot && h[q + 1] < h[q]) ++q;
			if (h[q] < h[p]) swap(h[q], h[p]), p = q;
			else break;
		}
	}

	void insert(int x) {
		h[++tot] = x;
		up(tot);
	}

	int get_top() {
		return h[1];
	}

	void remove(int p = 1) {
		h[p] = h[tot--];
		up(p), down(p);
	}
} h;

struct Product {
	int p, c;

	bool operator < (const Product& rhs) const {
		return c < rhs.c;
	}
} p[maxn];

int main() {
	int n;
	while (scanf("%d", &n) == 1) {
		for (int i = 1; i <= n; ++i)
			p[i].p = read(), p[i].c = read();
		sort(p + 1, p + n + 1);
		for (int i = 1; i <= n; ++i) {
			if (p[i].c > h.tot) h.insert(p[i].p);
			else if (p[i].c == h.tot) {
				if (p[i].p > h.get_top())
					h.remove(), h.insert(p[i].p);
			}
		}
		int ans = 0;
		while (h.tot) ans += h.get_top(), h.remove();
		printf("%d\n", ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值