POJ1442:Black Box

浅谈堆:https://www.cnblogs.com/AKMer/p/10284629.html

题目传送门:http://poj.org/problem?id=1442

用对顶堆维护第(k)小即可。保持小根堆大小逐渐递增就行。

时间复杂度:(O(mlogn))

空间复杂度:(O(n))

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn=3e4+5;

int n,m;
int a[maxn],u[maxn];

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

struct Heap {
	int tot;
	int tree[maxn];

	void ins(int v) {
		tree[++tot]=v;
		int pos=tot;
		while(pos>1) {
			if(tree[pos]<tree[pos>>1])
				swap(tree[pos],tree[pos>>1]),pos>>=1;
			else break;
		}
	}

	int pop() {
		int res=tree[1];
		tree[1]=tree[tot--];
		int pos=1,son=2;
		while(son<=tot) {
			if(son<tot&&tree[son|1]<tree[son])son|=1;
			if(tree[son]<tree[pos])
				swap(tree[son],tree[pos]),pos=son,son=pos<<1;
			else break;
		}
		return res;
	}
}T1,T2;

int main() {
	n=read(),m=read();
	for(int i=1;i<=n;i++)
		a[i]=read();
	for(int i=1;i<=m;i++)
		u[i]=read();
	sort(u+1,u+m+1);
	for(int i=1,st=1;i<=m;i++) {
		while(st<=u[i]) {
			if(a[st]>=T1.tree[1])T1.ins(a[st]);
			else T2.ins(-a[st]);
			st++;
		}
		while(T2.tot<i)T2.ins(-T1.pop());
		while(T2.tot>i)T1.ins(-T2.pop());
		printf("%d
",-T2.tree[1]);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/AKMer/p/10286480.html