思路

堆的原理就是每个节点保存以自身为根的树的最值。
那么左右子树,根节点也有此性质。
由此,较难的点便是插入与删除的树的调整。

# include <cstdio>
# include <iostream>
using namespace std;
# define INF    0x3f3f3f3f3f3f3f3f
# define MX     200005
/**************************/
int n;
int heap[MX];

void init() {
    n = 0;
}

/// 节点向上调整
void up(int u) {
    while(u>1 && heap[u] < heap[u/2]) {
        swap(heap[u], heap[u/2]);
        u/=2;
    }
}

/// 节点向下调整
void down(int u) {
    while(u<=n) {
        if (u*2+1<=n) { //有左右孩子
            int small = heap[u*2]<heap[u*2+1] ? u*2:u*2+1;  // 找出孩子中较小的
            if (heap[small] < heap[u]) {
                swap(heap[small], heap[u]);
                u = small;
            } else break;
        } else if (u*2<=n && heap[u*2] < heap[u]) { //只有左孩子
            swap(heap[u*2], heap[u]);
            u = u*2;
        } else break;
    }
}

/// 增加数据
void add(int x){
    heap[++n] = x;
    up(n);
}

/// 删除数据
int dele() {
    if (n==0) return -1;

    int ret = heap[1];
    swap(heap[n--], heap[1]); // 将根节点与末节点的值互换,并且n--
    down(1);
    return ret;
}


int main() {
    init();

    int xxx[98] = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39};

    for (int i=0; i<98; i++) {
        add(xxx[i]);
    }

    for (int i=0; i<98; i++){
        printf("%d\n", dele());
    }
}
posted @ 2019-06-25 10:30  happy_codes  阅读(75)  评论(0编辑  收藏