堆的实现

来源:互联网 发布:织梦cms后台演示地址 编辑:程序博客网 时间:2024/06/04 01:33
int heap[maxn], sz = 0;void push(int x){    int i = sz++; //自己节点的编号    while (i > 0){        int p = (i - 1) / 2;  //父亲节点的编号        if (heap[p] <= x)  //如果已经没有大小颠倒则退出            break;        heap[i] = heap[p];  //把父亲节点的数值放下来,而把自己提上去        i = p;    }    heap[i] = x;}int pop(){    int ret = heap[0];   //最小值    int x = heap[--sz];  //要提到根的数值    //从下开始交换    int i = 0;    while (i * 2 + 1 < sz){   //比较儿子的值        int a = i * 2 + 1, b = i * 2 + 2;        if (b < sz && heap[a] < heap[b])            a = b;        if (heap[a] >= x)   //如果已经没有大小颠倒则退出            break;        heap[i] = heap[a];   //把儿子的数值提上来        i = a;    }    heap[i] = x;    return ret;}实际上,大部分情况下并不需要自己实现堆。例如在C++中,STL里的priority_queue就是其中之一,不过需要注意的是,priority_queue取出数值时得到的是最大值。#include <queue>#include <cstdio>using namespace std;int main(){    priority_queue<int> pque;     //声明    pque.push(3);   //插入元素    pque.push(5);    pque.push(1);    while (!pque.empty()){    //不断循环直到空为止        printf("%d\n", pque.top());  //获取并删除最大值        pque.pop();    }    return 0;}

0 0