大/小根堆

大小根堆

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;
}

猜你喜欢

转载自blog.csdn.net/hesorchen/article/details/124283266