zoukankan      html  css  js  c++  java
  • 堆的实现

    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
    ", pque.top());  //获取并删除最大值
            pque.pop();
        }
        return 0;
    }

  • 相关阅读:
    1.表单标签
    07.Ajax.post
    06.Ajax.get
    05.Ajax.get
    04.Ajax-get.html
    03.post.file
    nodejs-7.2. CURD数据管理系统小栗子
    nodejs-7.1. mongoose模块
    JS 无缝轮播图1-节点操作
    JS 放大镜特效
  • 原文地址:https://www.cnblogs.com/llguanli/p/7390787.html
Copyright © 2011-2022 走看看