2.4.1. Dynamic Heap

STL’s priority_queue is just a container adaptor, which cannot meet requirement in many cases. For example, priority_queue has no update, no erase methods, so we can it static heap. A dynamic heap is able to update and erase values. The following is a dynamic heap class implemented with STL’s heap function.

 1struct dynamic_heap {
 2    vector<int> d;
 3    dynamic_heap(const vector<int>& _d) {
 4        d = _d;
 5        make_heap(d.begin(), d.end());
 6    }
 7    void push(int i) {
 8        d.push_back(i); // O(LogN)
 9        push_heap(d.begin(), d.end());
10    }
11    int pop() {
12        pop_heap(d.begin(), d.end()); // O(LogN)
13        int t = d.back(); d.pop_back();
14        return t;
15    }
16    void erase(int n) { // O(N)
17        update(n, INT_MAX);
18        pop();
19    }
20    void update(int old_, int new_) { // O(N+LogN) = O(N)
21        int i = 0;
22        for (; i < d.size(); ++i) // O(N)
23            if (d[i] == old_) { d[i] = new_; break; }
24        push_heap(d.begin(),d.begin()+i+1);// the same like sift up/down
25    }
26    int size() { return d.size(); }
27};

With the built-in STL heap function, we can implement a dynamic heap class as above. It is pretty simple but the time complexity of update and erase are O(N). If we use a map to connect the data and index, we can reduce it to O(LogN). This data structure is called index heap. Index the data in the heap, so it takes O(1) time to find and O(LogN) to update and delete.