zoukankan      html  css  js  c++  java
  • 堆——优先队列

    /*
    挑战程序设计竞赛——第2版
    P73
    */
    #include<iostream>
    #include<queue>
    #include<cstdio>
    #define MAX_N 100
    using namespace std;
    
    int heap[MAX_N], 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[b] < heap[a])a = b;
    
            if (heap[a] >= x)break;
    
            heap[i] = heap[a];
            i = a;
        }
    
        heap[i] = x;
    
        return ret;
    }
    
    int main()
    {
        priority_queue<int> pque;
    
        pque.push(3);
        pque.push(5);
        pque.push(1);
    
        while (!pque.empty())
        {
            cout << pque.top() << endl;
            pque.pop();
        }
    
        system("pause");
        return 0;
    }
    世上无难事,只要肯登攀。
  • 相关阅读:
    Python3 文件
    Python 字典
    Python OS
    Python函数zip-map
    Python 3.5 filter
    python3.5.2库getpass
    JavaScript学习四
    cocos creator学习
    JavaScript学习三
    JavaScript学习3
  • 原文地址:https://www.cnblogs.com/littlehoom/p/3513687.html
Copyright © 2011-2022 走看看