洛谷 P1168 中位数

题目描述

给出一个长度为N的非负整数序列A[i],对于所有1 ≤ k ≤ (N + 1) / 2,输出A[1], A[3], …, 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[3], …, 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。

两个堆 一大一小

大根堆存比中位数小的树,小根堆维护比中位数大的数。

屠龙宝刀点击就送

#include <algorithm>
#include <cstdio>
#include <queue>
using namespace std;
priority_queue<int>gr;
priority_queue<int,vector<int>,greater<int> >les;
int syg,n,now;
int main()
{
    scanf("%d",&n);
    scanf("%d",&now);
    printf("%d
",now);les.push(now);
    syg=now;
    for(int x,y,i=1;i<=(n-1)/2;++i)
    {
        scanf("%d%d",&x,&y);
        if(syg>x) gr.push(x);else les.push(x);
        if(syg>y) gr.push(y);else les.push(y);
        while(gr.size()>=les.size()) {les.push(gr.top());gr.pop();}
        while(gr.size()<les.size()-1){gr.push(les.top());les.pop();}
        printf("%d
",les.top());
        syg=les.top();
    }
    return 0;
}
我们都在命运之湖上荡舟划桨,波浪起伏着而我们无法逃脱孤航。但是假使我们迷失了方向,波浪将指引我们穿越另一天的曙光。
原文地址:https://www.cnblogs.com/ruojisun/p/6613284.html