最大值堆

#pragma once
#include <iostream>
using namespace std;
void swap(int a, int b, int *x) {
    int t = x[a];
    x[a] = x[b];
    x[b] = t;
}
class Heap {
private:
    int *heap;
    int maxSize;
    int n;
    void siftdown(int pos) {
        while(!isLeaf(pos)){
            int rc = rightchildren(pos);
            int j = leftchildren(pos);
            if ((rc < n) &&( heap[j] < heap[rc]))
                j = rc;
            if (heap[pos] > heap[j])
                return;
            swap(pos, j, heap);
            pos = j;
        }
    }
public:
    Heap(int sz, int num,int *a) {
        maxSize = sz;
        n = num;
        heap = a;
        buildHeap();
    }
    bool isLeaf(int pos)const {
        return (pos >= n / 2) && (pos < n);
    }
    int rightchildren(int pos)const {
        return 2 * pos + 2;
    }
    int leftchildren(int pos)const {
        return 2 * pos + 1;
    }
    int parent(int pos) const{
        return (pos - 1) / 2;
    }
    void buildHeap() {
        for (int i = n / 2 - 1; i >= 0; i--) {
            siftdown(i);
        }
    }
    void insert(const int& it) {
        int curr = n++;
        heap[curr] = it;
        while ((curr != 0) && (heap[curr] > heap[parent(curr)]) ){
            swap(curr, parent(curr), heap);
            curr = parent(curr);
        }
    }
    int removefirst() {
        swap(0, --n, heap);
        if (n != 0)siftdown(0);
        return heap[n];
    }
    int remove(int pos) {
        if (pos == n - 1)--n;
        else {
            swap(pos, --n, heap);
            while ((pos != 0) && heap[pos] > heap[parent(pos)]) {
                swap(pos, parent(pos), heap);
                pos = parent(pos);
            }
            if (n != 0)siftdown(pos);
        }
        return heap[n];
    }
};

转载于:https://my.oschina.net/u/3772904/blog/1616345

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值