Fork me on GitHub

P1168 中位数

https://www.luogu.org/problem/show?pid=1168#sub

这里写图片描述

用上c++的stl中的优先队列,小根堆用负值来存,构成对顶堆,就变成了一道水题。

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
int n;
priority_queue <int> q1;//大根堆 
priority_queue <int> q2;//小根堆 
int main()
{
    scanf("%d",&n);
    int x;
    for(int i=1;i<=n;i++)
    {   
        scanf("%d",&x);
        q1.push(x);
        while(q1.size()>q2.size()+1) 
        {
            x=q1.top();q1.pop();x=-x;
            q2.push(x);
        }
        while(q1.size()<q2.size()+1)
        {
            x=q2.top();q2.pop();x=-x;
            q1.push(x);
        }
        if(i%2) 
        {
            x=q1.top();
            printf("%d\n",x);
        }
    }
    return 0;
}
posted @ 2017-09-24 17:48  primes  阅读(68)  评论(0编辑  收藏  举报