题目描述
给出一个长度为N的非负整数序列A[i],对于所有1 ≤ k ≤ (N + 1) / 2,输出A[1], A[2], …, A[2k - 1]的中位数。[color=red]即[/color]前1,3,5,……个数的中位数。
输入输出格式
输入格式:
输入文件median.in的第1行为一个正整数N,表示了序列长度。
第2行包含N个非负整数A[i] (A[i] ≤ 10^9)。
输出格式:
输出文件median.out包含(N + 1) / 2行,第i行为A[1], A[2], …, A[2i – 1]的中位数。
输入输出样例
输入样例#1:
7
1 3 5 7 9 11 6
输出样例#1:
1
3
5
6
说明
对于20%的数据,N ≤ 100;
对于40%的数据,N ≤ 3000;
对于100%的数据,N ≤ 100000。
【分析】
以前做过。。现在纯属水博。。
大根堆放小数,小根堆放大数,维护小根堆数目,始终比大根堆大
【代码】
//poj 3784 Running Median
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
priority_queue <int> da;
priority_queue < int,vector<int>,greater<int> > xiao;
int Q,n,x,y,t;
int a[100005];
bool b;
int main()
{
int i,j,k,p,f,d; //k为中位数
t=0;b=0;
scanf("%d",&n);
scanf("%d",&k),printf("%d\n",k);
xiao.push(k);
fo(i,1,(n-1)/2)
{
scanf("%d%d",&x,&y);
if(x>=k) xiao.push(x);
else da.push(x);
if(y>=k) xiao.push(y);
else da.push(y);
while(xiao.size()!=da.size()+1 && xiao.size()>da.size())
//如果小根堆大
{
p=xiao.top();
xiao.pop();
da.push(p);
}
while(xiao.size()!=da.size()+1 && da.size()>xiao.size())
//如果大根堆大
{
p=da.top();
da.pop();
xiao.push(p);
}
k=xiao.top();
a[++t]=k;
}
fo(i,1,t) printf("%d\n",a[i]);
return 0;
}