码迷,mamicode.com
首页 > 其他好文 > 详细

自己实现的一个最大堆

时间:2015-09-17 23:21:48      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

做online judge的时候用到了最大堆,自己实现了一个,不过只适用于unsigned int类型,因为代码量比较小就都写在一起了。看有时间重写一下改成模版类吧。

class MaxHeap
{
private:
    int heap[MAX];
    int len;
public:
    MaxHeap()
    {
        len = 0;
        memset(heap, 0, MAX);
    }
    MaxHeap(uint *arr, int n){
        len = n;
        memset(heap, 0, MAX);
        build(arr, n);
    }
    int parent(int i){
        return i / 2;
    }
    int left(int i){
        return i * 2;
    }
    int right(int i){
        return i * 2 + 1;
    }
    void heapify(int i){
        int l = left(i);
        int r = right(i);
        int largest;
        if (l <= len && heap[l] > heap[i]){
            largest = l;
        }
        else{
            largest = i;
        }
        if (r <= len && heap[r] > heap[largest]){
            largest = r;
        }
        if (largest != i){
            swap(heap[i], heap[largest]);
            heapify(largest);
        }
    }
    void build(uint *arr, int n){
        for (int i = 0; i < n; ++i){
            heap[i + 1] = arr[i];
        }
        for (int i = len / 2; i >= 1; i--){
            heapify(i);
        }
    }
    uint maximum(){
        return heap[1];
    }
    uint extractMax(){
        if (len < 1)cout << "error, returning -1" << endl;
        uint max = heap[1];
        heap[1] = heap[len];
        len--;
        heapify(1);
        return max;
    }
    void increaseKey(int i, uint key){
        if (key < heap[i]){
            cout << "new key is samller than current key" << endl;
            return;
        }
        heap[i] = key;
        while (i > 1 && heap[parent(i)] < heap[i]){
            swap(heap[i], heap[parent(i)]);
            i = parent(i);
        }
    }
    void insert(uint key){
        len++;
        heap[len] = 0;
        increaseKey(len, key);
    }
    int length(){
        return len;
    }
    void print(){
        for (int i = 1; i <= len; i++){
            cout << heap[i] << endl;
        }
    }
};

自己实现的一个最大堆

标签:

原文地址:http://www.cnblogs.com/caiminfeng/p/4817827.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!