题目链接
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;
}