中位数

来源:互联网 发布:eve有mac版吗 编辑:程序博客网 时间:2024/06/03 15:13

P1168 中位数

题目链接

题目描述

给出一个长度为N的非负整数序列A[i],对于所有1 ≤ k ≤ (N + 1) / 2,输出A[1], A[3], …, A[2k - 1]的中位数。即前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:
71 3 5 7 9 11 6
输出样例#1:
1356

说明

对于20%的数据,N ≤ 100;

对于40%的数据,N ≤ 3000;

对于100%的数据,N ≤ 100000。



#include <bits/stdc++.h>using namespace std;struct cmp1{    bool operator()(int a,int b)    {        return a>b;    }};struct cmp2{    bool operator()(int a,int b)    {        return a<b;    }};int main(){    int n;    while(cin>>n)    {        priority_queue<int,vector<int >,cmp1 >d; //小顶堆        priority_queue<int,vector<int >,cmp2 >p; //大顶堆        int x;        for(int i=1;i<=n;i++)        {            //cin>>x;            scanf("%d",&x);            d.push(x);            if(i%2==1)            {                while(p.size()&&d.top()<p.top())                {                    d.push(p.top());                    p.pop();                    p.push(d.top());                    d.pop();                }                while(d.size()-p.size()>1)                {                    p.push(d.top());                    d.pop();                }                cout<<d.top()<<endl;            }        }    }}