poj3784 Running Median查找中位数
参考http://blog.csdn.net/sdfzyhx/article/details/52735387
凡是关于排序,可以考虑优先队列。
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> > bh;
priority_queue<int,vector<int>,less<int> > sh;
int main()
{
int i,j,k,m,n,p,q,x,y,z,T,K;
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&K,&n);
printf("%d %d\n",K,n/2+1);
while (!bh.empty()) bh.pop();
while (!sh.empty()) sh.pop();
for (i=1;i<=n;i++)
{
scanf("%d",&x);
if (sh.empty()||sh.top()>=x) sh.push(x);//插入元素小的,就放入sh,其他放入bh 其实这里> 或者大于等于都可以,反正在后面要调整堆的元素个数
else bh.push(x);
if (sh.size()>(i+1)/2)//调整堆的大小使得当i为奇数时候,sh的大小为i的一半多一个,则这一个就是中位数。
{
x=sh.top();
sh.pop();
bh.push(x);
}
if (sh.size()<(i+1)/2)
{
x=bh.top();
bh.pop();
sh.push(x);
}
if (i&1)
{
printf("%d",sh.top());
if (i==n||(i+1)%20==0)
printf("\n");
else printf(" ");
}
}
}
}
http://blog.csdn.net/sdfzyhx/article/details/52735387