大/小根堆

Posted hesorchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大/小根堆相关的知识,希望对你有一定的参考价值。

大小根堆

downup 两种操作,维护出堆顶即可。

值得一提的是,插入n个元素复杂度是O(nlogn),但是将n个元素建成堆时间复杂度是O(n)的,建堆代码如下:

for(int i = n/2;i >=1 ;i --) down(i);

代码

#include <bits/stdc++.h>
using namespace std;

class pile

private:
    int a[(int)1e6 + 5];
    int size;

public:
    int top()
    
        return a[1];
    
    void pop()
    
        a[1] = a[size--];
        down(1);
    
    void down(int i)
    
        int t = i;
        if (i * 2 <= size && a[i] > a[i * 2])
            t = i * 2;
        if (i * 2 + 1 <= size && a[t] > a[i * 2 + 1])
            t = i * 2 + 1;
        if (t != i)
        
            swap(a[t], a[i]);
            down(t);
        
    
    void up(int i)
    
        while (i / 2 && a[i] < a[i / 2])
            swap(a[i], a[i / 2]), i /= 2;
    
    void insert(int x)
    
        a[++size] = x;
        up(size);
    
;
int main()

    pile q;
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
    
        int opt;
        cin >> opt;
        if (opt == 1)
        
            cin >> opt;
            q.insert(opt);
        
        else if (opt == 2)
            cout << q.top() << endl;
        else
            q.pop();
    
    return 0;

创作挑战赛 新人创作奖励来咯,坚持创作打卡瓜分现金大奖

以上是关于大/小根堆的主要内容,如果未能解决你的问题,请参考以下文章

大/小根堆

大/小根堆

大顶堆 小顶堆应用----中位数查找

大顶堆 小顶堆应用----中位数查找

让priority_queue支持小根堆的几种方法

模板小根堆