Generikus binaris kupac implementacio.
Alap demo file mukodesenek bemutatasahoz.
10 template <typename Key, typename Val, typename KeyIntMap,
11 typename Compare = std::less<Val> >
16 // FIXME: stl-ben nem ezt hivjak value_type -nak, hanem a kovetkezot...
17 typedef Val ValueType;
18 typedef std::pair<KeyType,ValueType> PairType;
19 typedef KeyIntMap KeyIntMapType;
20 typedef Compare ValueCompare;
23 * Each Key element have a state associated to it. It may be "in heap",
24 * "pre heap" or "post heap". The later two are indifferent from the
25 * heap's point of view, but may be useful to the user.
27 * The KeyIntMap _should_ be initialized in such way, that it maps
28 * PRE_HEAP (-1) to any element to be put in the heap...
38 std::vector<PairType> data;
40 // FIXME: jo ez igy???
44 BinHeap(KeyIntMap &_kim) : kim(_kim) {}
45 BinHeap(KeyIntMap &_kim, const Compare &_comp) : comp(_comp), kim(_kim) {}
48 int size() const { return data.size(); }
49 bool empty() const { return size() == 0; }
52 static int parent(int i) { return (i-1)/2; }
53 static int second_child(int i) { return 2*i+2; }
54 bool less(const PairType &p1, const PairType &p2) {
55 return comp(p1.second, p2.second);
58 int bubble_up(int hole, PairType p);
59 int bubble_down(int hole, PairType p, int length);
61 void move(const PairType &p, int i) {
67 void push(const PairType &p) {
72 void push(const Key &k, const Val &v) { push(PairType(k,v)); }
75 // FIXME: test size>0 ?
78 Val topValue() const {
79 // FIXME: test size>0 ?
80 return data[0].second;
84 int n = data.size()-1;
86 bubble_down(0, data[n], n);
93 const Val get(const Key &k) const {
95 return data[idx].second;
97 void put(const Key &k, const Val &v) {
102 else if( comp(v, data[idx].second) ) {
103 bubble_up(idx, PairType(k,v));
106 bubble_down(idx, PairType(k,v), data.size());
110 void decrease(const Key &k, const Val &v) {
111 int idx = kim.get(k);
112 bubble_up(idx, PairType(k,v));
114 void increase(const Key &k, const Val &v) {
115 int idx = kim.get(k);
116 bubble_down(idx, PairType(k,v), data.size());
122 template <typename K, typename V, typename M, typename C>
123 int BinHeap<K,V,M,C>::bubble_up(int hole, PairType p) {
124 int par = parent(hole);
125 while( hole>0 && less(p,data[par]) ) {
126 move(data[par],hole);
134 template <typename K, typename V, typename M, typename C>
135 int BinHeap<K,V,M,C>::bubble_down(int hole, PairType p, int length) {
136 int child = second_child(hole);
137 while(child < length) {
138 if( less(data[child-1], data[child]) ) {
141 if( !less(data[child], p) )
143 move(data[child], hole);
145 child = second_child(hole);
148 if( child<length && less(data[child], p) ) {
149 move(data[child], hole);
159 #endif // BIN_HEAP_HH