洛谷 P1168 中位数

题目描述

给出一个长度为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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值