中位数

对顶堆,随便维护一下大小,注意非空就好了

#include<bits/stdc++.h>
#define re return
#define ll long long
#define inc(i,l,r) for(int i=l;i<=r;++i)
#define dec(i,l,r) for(int i=l;i>=r;--i)
const int maxn=10e5+5;
using namespace std;
template<typename T>inline void rd(T&x)
{
	char c;bool f=0;
	while((c=getchar())<'0'||c>'9')if(c=='-')f=1;
	x=c^48;
	while((c=getchar())>='0'&&c<='9')x=x*10+(c^48);
	if(f)x=-x;
}

priority_queue<ll>q;
priority_queue<ll,vector<ll>,greater<ll> >q1;
ll cnt,cnt1,n;

int main()
{
//	freopen("in.txt","r",stdin);
	ll x,y;
	rd(n);
	inc(i,1,n)
	{
		rd(x);
		q.push(x);
		if(cnt>cnt1){
			x=q.top();q.pop();
			q1.push(x);
			++cnt1;
		}
		else 
		{
			++cnt;
			if(!q1.empty())y=q1.top();
			else y=1e17+5;
			if(y<x){
				q1.pop();q.pop();
				q.push(y);q1.push(x);
			}
			printf("%d
",q.top());
		}
	}
	re 0;
}
原文地址:https://www.cnblogs.com/lsyyy/p/11265828.html