zoukankan      html  css  js  c++  java
  • 堆-heap

    #include <vector>
    #include <cstdio>
    using namespace std;
    class Heap {
    
    private :
        vector<int> data;
        void reBuildHead();
        void reBuildTail();
    public:
        Heap(){}
        ~Heap(){}
        int pop();
        int top();
        void push(int value);
    };
    void Heap::reBuildHead(){
        int now = 0;
        while(true) {
            int lson = now << 1;
            int rson = now << 1 | 1;
            if (lson >= data.size()) break;
            int target = rson >= data.size() ? lson : (data[lson] < data[rson] ? rson : lson);
            if (data[now] < data[target]) {
                swap(data[now], data[target]);
                now = target;
            } else {
                break;
            }
        }
    }
    void Heap::reBuildTail(){
        int now = this -> data.size() - 1;
        while(true) {
            if (now == 0) break;
            int father = now >> 1;
            if (data[now] > data[father]) {
                swap(data[now], data[father]);
                now = father;
            } else {
                break;
            }
        }
    }
    int Heap::pop() {
        if (data.size() == 0) return NULL;
        int ans = data[0];
        data[0] = data [data.size() -1];
        data.pop_back();
        this -> reBuildHead();
        return ans;
    }
    int Heap::top() {
        return data.size() == 0 ? NULL : data[0];
    }
    void Heap::push(int value) {
        data.push_back(value);
        this -> reBuildTail();
    }
  • 相关阅读:
    如何学习区块链
    用Python从零开始创建区块链
    区块链入门
    什么是区块链
    localStorage使用总结
    整理vue学习笔记
    SCSS 教程
    vue — 创建vue项目
    软件开发的常见文档
    史上最全的CSS hack方式一览(转)
  • 原文地址:https://www.cnblogs.com/shuly/p/7428044.html
Copyright © 2011-2022 走看看