• 最大堆


    做online judge的时候用到了最大堆,自己实现了一个。主要参考算法导论中的设计思路。

    #include <iostream>
    using namespace std;
    
    const int MAX_LEN = 100;
    
    class MaxHeap
    {
    private:
        int heap[MAX_LEN];
        int len;
        inline int parent(int i){ return i / 2; };
        inline int left(int i){ return i * 2; };
        inline int right(int i){ return i * 2 + 1; };
        void heapify(int i);
        void build(int *arr, int n);
    public:
        MaxHeap();
        MaxHeap(int *arr, int n);
        inline int length(){ return len; };
        inline int max(){ return heap[1]; };
        void print();
        int extractMax();
        void increaseKey(int i, int key);
        void insert(int key);
    };
    
    MaxHeap::MaxHeap(){
        len = 0;
        memset(heap, 0, MAX_LEN);
    }
    
    MaxHeap::MaxHeap(int *arr, int n){
        len = n;
        memset(heap, 0, MAX_LEN);
        build(arr, n);
    }
    
    void MaxHeap::heapify(int i){
        int l = left(i);
        int r = right(i);
        int largest = i;
        if (l <= len&&heap[l] > heap[largest])
            largest = l;
        if (r <= len&&heap[r] > heap[largest])
            largest = r;
        if (largest != i){
            swap(heap[i], heap[largest]);
            heapify(largest);
        }
    }
    
    void MaxHeap::build(int *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);
    }
    
    int MaxHeap::extractMax(){
        if (len < 1){
            cout << "Error. Returning -1." << endl;
            return -1;
        }
        int max = heap[1];
        heap[1] = heap[len];
        len--;
        heapify(1);
        return max;
    }
    
    void MaxHeap::print(){
        for (int i = 1; i <= len; i++)
            cout << heap[i] << endl;
    }
    
    void MaxHeap::increaseKey(int i, int key){
        if (key < heap[i]){
            cout << "New key is smaller than current key." << endl;
            return;
        }
        heap[i] = key;
        while (i > 1 && heap[parent(i)] < heap[i]){
            swap(heap[parent(i)], heap[i]);
            i = parent(i);
        }
    }
    
    void MaxHeap::insert(int key){
        len++;
        heap[len] = INT_MIN;
        increaseKey(len, key);
    }
    
    int main()
    {
        int num[10] = { 4, 1, 6, 2, 9, 7, 3, 8, 5, 0 };
        MaxHeap max_heap(num, 10);
        max_heap.print();
        return 0;
    }
  • 相关阅读:
    代码格式化[转]
    ASP.NET错误大杂烩
    Web考勤管理系统 .net 2005 开发
    Ftp 类
    c#中Split等分割字符串的几种方法
    强大的firebug 使用 介绍
    一页面多个文本框回车提交不同事件问题解决
    Ajax电子书下载 发现的好东东贴上了
    编程技术书籍[转]
    推荐下权威的《IT十年经典书系列》1打
  • 原文地址:https://www.cnblogs.com/caiminfeng/p/4817827.html
Copyright © 2020-2023  润新知