[数据结构] 对顶堆求中位数

中位数求法比较多 离线的主席树

比较容易实现的就是 在线的对顶堆

对顶堆的定义:

  • 小顶堆存 大于小顶堆堆顶所有元素
  • 大顶堆存 小于大顶堆堆顶所有元素

那么 小顶堆和大顶堆堆顶 就是整个 当前数据元素分界线

并且 堆顶对换/互相插入 不影响定义性质

那么当求中位数时 只需调堆即可

得益于堆的性质 每次调堆时间复杂度为log(n)

1. 当前总元素量为奇数时

入大反小

2.当前总元素量为偶数时

入小反大

例题及代码

https://www.luogu.org/problemnew/show/P1168

struct getMid
{
    priority_queue <int> Q1;
    priority_queue <int, vector <int> , greater<int> > Q2;
    int pos = 0;
    void push(int x)
    {
        ++pos;
        if(pos & 1)
        {
            Q1.push(x);
            Q2.push(Q1.top());
            Q1.pop();
        }
        else
        {
            Q2.push(x);
            Q1.push(Q2.top());
            Q2.pop();
        }
    }
    
    int get()
    {
        return Q2.top();
    }
};

 

 

 

posted @ 2019-03-19 10:35  张浦  阅读(229)  评论(0编辑  收藏  举报