src/include/bin_heap.hh
author jacint
Sat, 20 Mar 2004 20:08:24 +0000
changeset 221 d8a67c5b26d1
parent 214 44f01e580f16
permissions -rw-r--r--
map.get(v) <- map[v] csere
     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<ItemType, PrioType, ItemIntMap, [PrioCompare]>
    10  *
    11  * Ez az osztaly item-prioritas parok tarolasara alkalmas binaris kupacot
    12  * valosit meg.
    13  * A kupacban legfolul mindig az a par talalhato, amiben a prioritas a
    14  * legkisebb. (Gondolj a Dijkstra pont-tavolsag kupacara; igazabol ahhoz
    15  * lett keszitve...)
    16  *
    17  * Megjegyzes: a kupacos temakorokben a prioritast kulcsnak szoktak nevezni,
    18  * de mivel ez zavaro tud lenni a property-map-es kulcs-ertek szohasznalata
    19  * miatt, megprobaltunk valami semleges elnevezeseket kitalalni.
    20  *
    21  * A hasznalatahoz szukseg van egy irhato/olvashato property_map-re, ami
    22  * az itemekhez 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  * set(Item, Prio) 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" prioritasu elemet. De csak nagyjabol,
    39  * hiszen a kupacbol kikerult elemeknek elvesz az ertekuk...
    40  *
    41  * Kozvetlen mod:
    42  * push(Item, Prio) metodussal belerakunk a kupacba (ha az illeto kulcs mar
    43  * benn volt, akkor gaz).
    44  * increase/decrease(Item i, Prio new_prio) metodusokkal lehet
    45  * novelni/csokkenteni az illeto elemhez tartozo prioritast. (Ha nem volt
    46  * megbenne a kupacban az illeto elem, 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   template <typename Item, typename Prio, typename ItemIntMap,
    69 	    typename Compare = std::less<Prio> >
    70   class BinHeap {
    71 
    72   public:
    73     typedef Item                             ItemType;
    74     // FIXME: stl-ben nem ezt hivjak value_type -nak, hanem a kovetkezot...
    75     typedef Prio                             PrioType;
    76     typedef std::pair<ItemType,PrioType>     PairType;
    77     typedef ItemIntMap                       ItemIntMapType;
    78     typedef Compare                          PrioCompare;
    79 
    80     /**
    81      * Each Item element have a state associated to it. It may be "in heap",
    82      * "pre heap" or "post heap". The later two are indifferent from the
    83      * heap's point of view, but may be useful to the user.
    84      *
    85      * The ItemIntMap _should_ be initialized in such way, that it maps
    86      * PRE_HEAP (-1) to any element to be put in the heap...
    87      */
    88     enum state_enum {
    89       IN_HEAP = 0,
    90       PRE_HEAP = -1,
    91       POST_HEAP = -2
    92     };
    93 
    94   private:
    95     std::vector<PairType> data;
    96     Compare comp;
    97     // FIXME: jo ez igy???
    98     ItemIntMap &iim;
    99 
   100   public:
   101     BinHeap(ItemIntMap &_iim) : iim(_iim) {}
   102     BinHeap(ItemIntMap &_iim, const Compare &_comp) : comp(_comp), iim(_iim) {}
   103 
   104 
   105     int size() const { return data.size(); }
   106     bool empty() const { return data.empty(); }
   107 
   108   private:
   109     static int parent(int i) { return (i-1)/2; }
   110     static int second_child(int i) { return 2*i+2; }
   111     bool less(const PairType &p1, const PairType &p2) const {
   112       return comp(p1.second, p2.second);
   113     }
   114 
   115     int bubble_up(int hole, PairType p);
   116     int bubble_down(int hole, PairType p, int length);
   117 
   118     void move(const PairType &p, int i) {
   119       data[i] = p;
   120       iim.set(p.first, i);
   121     }
   122 
   123     void rmidx(int h) {
   124       int n = data.size()-1;
   125       if( h>=0 && h<=n ) {
   126 	iim.set(data[h].first, POST_HEAP);
   127 	if ( h<n ) {
   128 	  bubble_down(h, data[n], n);
   129 	}
   130 	data.pop_back();
   131       }
   132     }
   133 
   134   public:
   135     void push(const PairType &p) {
   136       int n = data.size();
   137       data.resize(n+1);
   138       bubble_up(n, p);
   139     }
   140     void push(const Item &i, const Prio &p) { push(PairType(i,p)); }
   141 
   142     Item top() const {
   143       // FIXME: test size>0 ?
   144       return data[0].first;
   145     }
   146     Prio topPrio() const {
   147       // FIXME: test size>0 ?
   148       return data[0].second;
   149     }
   150 
   151     void pop() {
   152       rmidx(0);
   153     }
   154 
   155     void erase(const Item &i) {
   156       rmidx(iim[i]);
   157     }
   158 
   159     Prio get(const Item &i) const {
   160       int idx = iim[i];
   161       return data[idx].second;
   162     }
   163     Prio operator[](const Item &i) const {
   164       return get(i);
   165     }
   166     void set(const Item &i, const Prio &p) {
   167       int idx = iim[i];
   168       if( idx < 0 ) {
   169 	push(i,p);
   170       }
   171       else if( comp(p, data[idx].second) ) {
   172 	bubble_up(idx, PairType(i,p));
   173       }
   174       else {
   175 	bubble_down(idx, PairType(i,p), data.size());
   176       }
   177     }
   178 
   179     void decrease(const Item &i, const Prio &p) {
   180       int idx = iim[i];
   181       bubble_up(idx, PairType(i,p));
   182     }
   183     void increase(const Item &i, const Prio &p) {
   184       int idx = iim[i];
   185       bubble_down(idx, PairType(i,p), data.size());
   186     }
   187 
   188     state_enum state(const Item &i) const {
   189       int s = iim[i];
   190       if( s>=0 )
   191 	s=0;
   192       return state_enum(s);
   193     }
   194 
   195   }; // class BinHeap
   196 
   197   
   198   template <typename K, typename V, typename M, typename C>
   199   int BinHeap<K,V,M,C>::bubble_up(int hole, PairType p) {
   200     int par = parent(hole);
   201     while( hole>0 && less(p,data[par]) ) {
   202       move(data[par],hole);
   203       hole = par;
   204       par = parent(hole);
   205     }
   206     move(p, hole);
   207     return hole;
   208   }
   209 
   210   template <typename K, typename V, typename M, typename C>
   211   int BinHeap<K,V,M,C>::bubble_down(int hole, PairType p, int length) {
   212     int child = second_child(hole);
   213     while(child < length) {
   214       if( less(data[child-1], data[child]) ) {
   215 	--child;
   216       }
   217       if( !less(data[child], p) )
   218 	goto ok;
   219       move(data[child], hole);
   220       hole = child;
   221       child = second_child(hole);
   222     }
   223     child--;
   224     if( child<length && less(data[child], p) ) {
   225       move(data[child], hole);
   226       hole=child;
   227     }
   228   ok:
   229     move(p, hole);
   230     return hole;
   231   }
   232 
   233 } // namespace hugo
   234 
   235 #endif // BIN_HEAP_HH