题目链接
http://poj.org/problem?id=1442
分析
建一个大根堆保存当前序列前 k − 1 k - 1 k−1 小的元素,建一个小根堆保存剩余元素。
每次插入到小根堆,若小根堆堆顶小于大根堆堆顶,则交换两堆堆顶。
每次输出大根堆堆顶,并将堆顶取出放入小根堆,以此维护小根堆的大小。
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;
}