堆-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();
}
posted @ 2017-08-25 14:53  默默无语敲代码  阅读(197)  评论(0编辑  收藏  举报