[Luogu]中位数

Description

Luogu1168

Solution

一种神奇的做法:开一个大根堆和小根堆,保证大根堆比小根堆多1个元素,且大根堆堆顶元素比小根堆堆顶元素小,那么大根堆堆顶就是中位数。插入的时候用交换堆顶元素的方法维护一下这个性质就行。

Code

#include <cstdio>
#include <queue>

const int N = 100010;

int n, a[N];
std::priority_queue<int> big;
std::priority_queue<int, std::vector<int>, std::greater<int> > small;

int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
	int p = 1;
	big.push(a[p++]);
	printf("%d
", big.top());
	if (!n%2) n--;
	while (p < n) {
		int x = a[p++], y = a[p++];
		if (x > y) std::swap(x, y);
		big.push(x);
		small.push(y);
		if (big.top() > small.top()) {
			int x = big.top(), y = small.top();
			big.pop(); big.push(y);
			small.pop(); small.push(x);
		}
		printf("%d
", big.top());
 	}
	return 0;
}
原文地址:https://www.cnblogs.com/wyxwyx/p/lg1168.html