src/work/alpar/dijkstra/bin_heap.hh
author alpar
Sun, 21 Mar 2004 14:59:51 +0000
changeset 224 5bc1c83257f8
parent 222 0c6bd3a98edf
child 242 b255f25ad394
permissions -rw-r--r--
Some doc added
     1 /* FIXME: Copyright ... 
     2  *
     3  * This implementation is heavily based on STL's heap functions and
     4  * the similar class by Alpar Juttner in IKTA...
     5  */
     6 
     7 /******
     8  *
     9  * BinHeap<KeyType, ValueType, KeyIntMap, [ValueCompare]>
    10  *
    11  * Ez az osztaly kulcs-ertek parok tarolasara alkalmas binaris kupacot
    12  * valosit meg.
    13  * A kupacban legfolul mindig az a par talalhato, amiben az _ertek_ a
    14  * legkisebb. (Gondolj a Dijkstra pont-tavolsag kupacara; igazabol ahhoz
    15  * lett keszitve...)
    16  *
    17  * Megjegyzes: egy kicsit gyanus nekem, hogy a kupacos temakorben nem
    18  * azt hivjak kulcsnak, amit most en annak nevezek. :) En olyan 
    19  * property_map -os ertelemben hasznalom.
    20  *
    21  * A hasznalatahoz szukseg van egy irhato/olvashato property_map-re, ami
    22  * a kulcsokhoz egy int-et tud tarolni (ezzel tudom megkeresni az illeto
    23  * elemet a kupacban a csokkentes es hasonlo muveletekhez).
    24  * A map-re csak referenciat tarol, ugy hogy a kupac elete folyan a map-nek
    25  * is elnie kell. (???)
    26  *
    27  * Ketfele modon hasznalhato:
    28  * Lusta mod:
    29  * put(Key, Value) metodussal pakolunk a kupacba,
    30  * aztan o majd eldonti, hogy ez az elem mar benne van-e es ha igen, akkor
    31  * csokkentettunk-e rajta, vagy noveltunk.
    32  * Ehhez nagyon fontos, hogy az atadott property map inicializalva legyen
    33  * minden szobajovo kulcs ertekre, -1 -es ertekkel!
    34  * Es ilyen esetben a kulcsokrol lekerdezheto az allapotuk a state metodussal:
    35  * (nem jart meg a kupacban PRE_HEAP=-1, epp a kupacban van IN_HEAP=0,
    36  *  mar kikerult a kupacbol POST_HEAP=-2).
    37  * Szoval ebben a modban a kupac nagyjabol hasznalhato property_map-kent, csak
    38  * meg meg tudja mondani a "legkisebb" erteku elemet. De csak nagyjabol,
    39  * hiszen a kupacbol kikerult elemeknek elvesz az ertekuk...
    40  *
    41  * Kozvetlen mod:
    42  * push(Key, Value) metodussal belerakunk a kupacba (ha az illeto kulcs mar
    43  * benn volt, akkor gaz).
    44  * increase/decrease(Key k, Value new_value) metodusokkal lehet
    45  * novelni/csokkenteni az illeto kulcshoz tartozo erteket. (Ha nem volt meg
    46  * benne a kupacban az illeto kulcs, vagy nem abba az iranyba valtoztattad
    47  * az erteket, amerre mondtad -- gaz).
    48  *
    49  * Termeszetesen a fenti ket modot ertelemszeruen lehet keverni.
    50  * Ja es mindig nagyon gaz, ha belepiszkalsz a map-be, amit a kupac
    51  * hasznal. :-))
    52  *
    53  *
    54  * Bocs, most faradt vagyok, majd egyszer leforditom. (Misi)
    55  *
    56  */
    57 
    58 
    59 #ifndef BIN_HEAP_HH
    60 #define BIN_HEAP_HH
    61 
    62 #include <vector>
    63 #include <utility>
    64 #include <functional>
    65 
    66 namespace hugo {
    67 
    68   /// A Binary Heap implementation.
    69   template <typename Key, typename Val, typename KeyIntMap,
    70 	    typename Compare = std::less<Val> >
    71   class BinHeap {
    72 
    73   public:
    74     typedef Key	             KeyType;
    75     // FIXME: stl-ben nem ezt hivjak value_type -nak, hanem a kovetkezot...
    76     typedef Val              ValueType;
    77     typedef std::pair<KeyType,ValueType>     PairType;
    78     typedef KeyIntMap        KeyIntMapType;
    79     typedef Compare          ValueCompare;
    80 
    81     /**
    82      * Each Key element have a state associated to it. It may be "in heap",
    83      * "pre heap" or "post heap". The later two are indifferent from the
    84      * heap's point of view, but may be useful to the user.
    85      *
    86      * The KeyIntMap _should_ be initialized in such way, that it maps
    87      * PRE_HEAP (-1) to any element to be put in the heap...
    88      */
    89     ///\todo it is used nowhere
    90     ///
    91     enum state_enum {
    92       IN_HEAP = 0,
    93       PRE_HEAP = -1,
    94       POST_HEAP = -2
    95     };
    96 
    97   private:
    98     std::vector<PairType> data;
    99     Compare comp;
   100     // FIXME: jo ez igy???
   101     KeyIntMap &kim;
   102 
   103   public:
   104     BinHeap(KeyIntMap &_kim) : kim(_kim) {}
   105     BinHeap(KeyIntMap &_kim, const Compare &_comp) : comp(_comp), kim(_kim) {}
   106 
   107 
   108     int size() const { return data.size(); }
   109     bool empty() const { return data.empty(); }
   110 
   111   private:
   112     static int parent(int i) { return (i-1)/2; }
   113     static int second_child(int i) { return 2*i+2; }
   114     bool less(const PairType &p1, const PairType &p2) {
   115       return comp(p1.second, p2.second);
   116     }
   117 
   118     int bubble_up(int hole, PairType p);
   119     int bubble_down(int hole, PairType p, int length);
   120 
   121     void move(const PairType &p, int i) {
   122       data[i] = p;
   123       kim.set(p.first, i);
   124     }
   125 
   126     void rmidx(int h) {
   127       int n = data.size()-1;
   128       if( h>=0 && h<=n ) {
   129 	kim.set(data[h].first, POST_HEAP);
   130 	if ( h<n ) {
   131 	  bubble_down(h, data[n], n);
   132 	}
   133 	data.pop_back();
   134       }
   135     }
   136 
   137   public:
   138     void push(const PairType &p) {
   139       int n = data.size();
   140       data.resize(n+1);
   141       bubble_up(n, p);
   142     }
   143     void push(const Key &k, const Val &v) { push(PairType(k,v)); }
   144 
   145     Key top() const {
   146       // FIXME: test size>0 ?
   147       return data[0].first;
   148     }
   149     Val topValue() const {
   150       // FIXME: test size>0 ?
   151       return data[0].second;
   152     }
   153 
   154     void pop() {
   155       rmidx(0);
   156     }
   157 
   158     void erase(const Key &k) {
   159       rmidx(kim[k]);
   160     }
   161 
   162     Val operator[](const Key &k) const {
   163       int idx = kim[k];
   164       return data[idx].second;
   165     }
   166     
   167     void put(const Key &k, const Val &v) {
   168       int idx = kim[k];
   169       if( idx < 0 ) {
   170 	push(k,v);
   171       }
   172       else if( comp(v, data[idx].second) ) {
   173 	bubble_up(idx, PairType(k,v));
   174       }
   175       else {
   176 	bubble_down(idx, PairType(k,v), data.size());
   177       }
   178     }
   179 
   180     void decrease(const Key &k, const Val &v) {
   181       int idx = kim[k];
   182       bubble_up(idx, PairType(k,v));
   183     }
   184     void increase(const Key &k, const Val &v) {
   185       int idx = kim[k];
   186       bubble_down(idx, PairType(k,v), data.size());
   187     }
   188 
   189     state_enum state(const Key &k) const {
   190       int s = kim[k];
   191       if( s>=0 )
   192 	s=0;
   193       return state_enum(s);
   194     }
   195 
   196   }; // class BinHeap
   197 
   198   
   199   template <typename K, typename V, typename M, typename C>
   200   int BinHeap<K,V,M,C>::bubble_up(int hole, PairType p) {
   201     int par = parent(hole);
   202     while( hole>0 && less(p,data[par]) ) {
   203       move(data[par],hole);
   204       hole = par;
   205       par = parent(hole);
   206     }
   207     move(p, hole);
   208     return hole;
   209   }
   210 
   211   template <typename K, typename V, typename M, typename C>
   212   int BinHeap<K,V,M,C>::bubble_down(int hole, PairType p, int length) {
   213     int child = second_child(hole);
   214     while(child < length) {
   215       if( less(data[child-1], data[child]) ) {
   216 	--child;
   217       }
   218       if( !less(data[child], p) )
   219 	goto ok;
   220       move(data[child], hole);
   221       hole = child;
   222       child = second_child(hole);
   223     }
   224     child--;
   225     if( child<length && less(data[child], p) ) {
   226       move(data[child], hole);
   227       hole=child;
   228     }
   229   ok:
   230     move(p, hole);
   231     return hole;
   232   }
   233 
   234 } // namespace hugo
   235 
   236 #endif // BIN_HEAP_HH