/* -*- C++ -*-
 * src/lemon/bin_heap.h - Part of LEMON, a generic C++ optimization library
 *
 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 * (Egervary Combinatorial Optimization Research Group, EGRES).
 *
 * Permission to use, modify and distribute this software is granted
 * provided that this copyright notice appears in all copies. For
 * precise terms see the accompanying LICENSE file.
 *
 * This software is provided "AS IS" with no warranty of any kind,
 * express or implied, and with no claim as to its suitability for any
 * purpose.
 *
 */

#ifndef LEMON_BIN_HEAP_H
#define LEMON_BIN_HEAP_H

///\ingroup auxdat
///\file
///\brief Binary Heap implementation.
///\todo It should be documented.

#include <vector>
#include <utility>
#include <functional>

namespace lemon {

  /// \addtogroup auxdat
  /// @{

   /// A Binary Heap implementation.
  
  ///\todo Please document...
  ///
  ///\sa FibHeap
  ///\sa Dijkstra
  template <typename Item, typename Prio, typename ItemIntMap,
	    typename Compare = std::less<Prio> >
  class BinHeap {

  public:
    typedef Item                             ItemType;
    // FIXME: stl-ben nem ezt hivjak value_type -nak, hanem a kovetkezot...
    typedef Prio                             PrioType;
    typedef std::pair<ItemType,PrioType>     PairType;
    typedef ItemIntMap                       ItemIntMapType;
    typedef Compare                          PrioCompare;

    /**
     * Each Item element have a state associated to it. It may be "in heap",
     * "pre heap" or "post heap". The later two are indifferent from the
     * heap's point of view, but may be useful to the user.
     *
     * The ItemIntMap _should_ be initialized in such way, that it maps
     * PRE_HEAP (-1) to any element to be put in the heap...
     */
    ///\todo it is used nowhere
    ///
    enum state_enum {
      IN_HEAP = 0,
      PRE_HEAP = -1,
      POST_HEAP = -2
    };

  private:
    std::vector<PairType> data;
    Compare comp;
    // FIXME: jo ez igy???
    ItemIntMap &iim;

  public:
    ///\e
    BinHeap(ItemIntMap &_iim) : iim(_iim) {}
    ///\e
    BinHeap(ItemIntMap &_iim, const Compare &_comp) : comp(_comp), iim(_iim) {}


    ///\e
    int size() const { return data.size(); }
    ///\e
    bool empty() const { return data.empty(); }

  private:
    static int parent(int i) { return (i-1)/2; }
    static int second_child(int i) { return 2*i+2; }
    bool less(const PairType &p1, const PairType &p2) const {
      return comp(p1.second, p2.second);
    }

    int bubble_up(int hole, PairType p);
    int bubble_down(int hole, PairType p, int length);

    void move(const PairType &p, int i) {
      data[i] = p;
      iim.set(p.first, i);
    }

    void rmidx(int h) {
      int n = data.size()-1;
      if( h>=0 && h<=n ) {
	iim.set(data[h].first, POST_HEAP);
	if ( h<n ) {
	  bubble_down(h, data[n], n);
	}
	data.pop_back();
      }
    }

  public:
    ///\e
    void push(const PairType &p) {
      int n = data.size();
      data.resize(n+1);
      bubble_up(n, p);
    }
    ///\e
    void push(const Item &i, const Prio &p) { push(PairType(i,p)); }

    ///\e
    Item top() const {
      return data[0].first;
    }
    /// Returns the prio of the top element of the heap.
    Prio prio() const {
      return data[0].second;
    }

    ///\e
    void pop() {
      rmidx(0);
    }

    ///\e
    void erase(const Item &i) {
      rmidx(iim[i]);
    }

    ///\e
    Prio operator[](const Item &i) const {
      int idx = iim[i];
      return data[idx].second;
    }

    ///\e
    void set(const Item &i, const Prio &p) {
      int idx = iim[i];
      if( idx < 0 ) {
	push(i,p);
      }
      else if( comp(p, data[idx].second) ) {
	bubble_up(idx, PairType(i,p));
      }
      else {
	bubble_down(idx, PairType(i,p), data.size());
      }
    }

    ///\e
    void decrease(const Item &i, const Prio &p) {
      int idx = iim[i];
      bubble_up(idx, PairType(i,p));
    }
    ///\e
    void increase(const Item &i, const Prio &p) {
      int idx = iim[i];
      bubble_down(idx, PairType(i,p), data.size());
    }

    ///\e
    state_enum state(const Item &i) const {
      int s = iim[i];
      if( s>=0 )
	s=0;
      return state_enum(s);
    }

  }; // class BinHeap

  
  template <typename K, typename V, typename M, typename C>
  int BinHeap<K,V,M,C>::bubble_up(int hole, PairType p) {
    int par = parent(hole);
    while( hole>0 && less(p,data[par]) ) {
      move(data[par],hole);
      hole = par;
      par = parent(hole);
    }
    move(p, hole);
    return hole;
  }

  template <typename K, typename V, typename M, typename C>
  int BinHeap<K,V,M,C>::bubble_down(int hole, PairType p, int length) {
    int child = second_child(hole);
    while(child < length) {
      if( less(data[child-1], data[child]) ) {
	--child;
      }
      if( !less(data[child], p) )
	goto ok;
      move(data[child], hole);
      hole = child;
      child = second_child(hole);
    }
    child--;
    if( child<length && less(data[child], p) ) {
      move(data[child], hole);
      hole=child;
    }
  ok:
    move(p, hole);
    return hole;
  }

  ///@}

} // namespace lemon

#endif // LEMON_BIN_HEAP_H
