|洛谷|堆|P1168 中位数

https://www.luogu.org/problem/show?pid=1168

维护两个堆,一个大根堆L维护小于等于mid的数,一个小根堆R维护大于等于mid的数,mid是上次输出的中位数

然后进行调整即可

#include
#include
#include
#include
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
int n;
priority_queue L;//big
priority_queue, greater > R;//small
int main()
{
	scanf("%d",&n);
	int x1,x2;
	scanf("%d", &x1); 
	R.push(x1);
	int mid = x1;
	printf("%d\n", mid);
	for (int i=1;i<=(n+1)/2-1;i++)
	{
		scanf("%d%d", &x1, &x2);
		if (x1<=mid) L.push(x1); else R.push(x1);
		if (x2<=mid) L.push(x2); else R.push(x2);
		while (L.size() >= R.size()) {R.push(L.top()); L.pop();}
		while (L.size() < R.size()-1) {L.push(R.top()); R.pop();}
		printf("%d\n", R.top()); mid = R.top();
	}
    return 0;
}


你可能感兴趣的:(树,-,堆,洛谷)