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