POJ1442 Black Box 堆

题目链接

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

分析

建一个大根堆保存当前序列前 k − 1 k - 1 k1 小的元素,建一个小根堆保存剩余元素。

每次插入到小根堆,若小根堆堆顶小于大根堆堆顶,则交换两堆堆顶。

每次输出大根堆堆顶,并将堆顶取出放入小根堆,以此维护小根堆的大小。

AC代码

#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

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

const int maxm = 3e4 + 5;

int a[maxm];
priority_queue<int> q1;
priority_queue<int, vector<int>, greater<int> > q2;

int main() {
	int m = read(), n = read(), p = 1;
	for (int i = 1; i <= m; ++i) a[i] = read();
	for (int i = 1; i <= n; ++i) {
		int k = read();
		while (p <= k) {
			q2.push(a[p]);
			if (!q1.empty() && q2.top() < q1.top()) {
				int x = q1.top(), y = q2.top();
				q1.pop(), q2.pop();
				q1.push(y), q2.push(x);
			}
			++p;
		}
		printf("%d\n", q2.top());
		q1.push(q2.top()), q2.pop();
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值