【算法】手写优先队列

template<typename T>
class MyPriorityQueue {
    
private:
    int n;
    vector<T> q;
    function<bool(T,T)> compare; // 比较函数,类似STL中优先队列创建的第三个仿函数参数
    
    void down(int u) {
        int t;
        do {
            t = u;
            if (u * 2 <= n && compare(cnt[q[t]], cnt[q[u * 2]])) t = u * 2;
            if (u * 2 + 1 <= n && compare(cnt[q[t]], cnt[q[u * 2 + 1]])) t = u * 2 + 1;
            swap(q[u], q[t]);
            swap(u, t);
        } while (t != u);
    }
    
    void up(int u) {
        while ((u >> 1) >= 1 && compare(cnt[q[u >> 1]], cnt[q[u]])) {
            swap(q[u], q[u >> 1]);
            u >>= 1;
        }
    }
    
public:
    
    unordered_map<T, int> cnt; // 用来辅助compare的部分,一般需要由外界设置,非pq标配函数,因此设置为public
    
    MyPriorityQueue(function<bool(T,T)> compare = [](T a, T b) { return a > b; }): q(1, 1), compare(compare), n(0) {}
    
    int top() {
        return q[1];
    }
    
    void pop() {
        if (n <= 0) return ;
        swap(q[1], q[n]);
        q.pop_back();
        n -= 1;
        down(1);
    }
    
    void push(T x) {
        q.push_back(x);
        n += 1;
        up(n);
    }
    
    bool empty() {
        return n == 0;
    }
    
    int size() {
        return n;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值