# HG changeset patch # User Balazs Dezso # Date 1244751089 -7200 # Node ID 532697c9fa536a2cd3ccc715b47f1e6a678510a6 # Parent 257e91516e09d8d6be58236c587e3e0199770412 Port remaining heaps from SVN -r 3509 (#50) - FibHeap - RadixHeap - BucketHeap - SimpleBucketHeap diff -r 257e91516e09 -r 532697c9fa53 lemon/Makefile.am --- a/lemon/Makefile.am Fri May 29 17:46:48 2009 +0100 +++ b/lemon/Makefile.am Thu Jun 11 22:11:29 2009 +0200 @@ -59,6 +59,7 @@ lemon/assert.h \ lemon/bfs.h \ lemon/bin_heap.h \ + lemon/bucket_heap.h \ lemon/cbc.h \ lemon/circulation.h \ lemon/clp.h \ @@ -76,6 +77,7 @@ lemon/elevator.h \ lemon/error.h \ lemon/euler.h \ + lemon/fib_heap.h \ lemon/full_graph.h \ lemon/glpk.h \ lemon/gomory_hu.h \ @@ -99,6 +101,7 @@ lemon/network_simplex.h \ lemon/path.h \ lemon/preflow.h \ + lemon/radix_heap.h \ lemon/radix_sort.h \ lemon/random.h \ lemon/smart_graph.h \ diff -r 257e91516e09 -r 532697c9fa53 lemon/bucket_heap.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemon/bucket_heap.h Thu Jun 11 22:11:29 2009 +0200 @@ -0,0 +1,831 @@ +/* -*- mode: C++; indent-tabs-mode: nil; -*- + * + * This file is a part of LEMON, a generic C++ optimization library. + * + * Copyright (C) 2003-2009 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport + * (Egervary Research Group on Combinatorial Optimization, 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_BUCKET_HEAP_H +#define LEMON_BUCKET_HEAP_H + +///\ingroup auxdat +///\file +///\brief Bucket Heap implementation. + +#include +#include +#include + +namespace lemon { + + /// \ingroup auxdat + /// + /// \brief A Bucket Heap implementation. + /// + /// This class implements the \e bucket \e heap data structure. A \e heap + /// is a data structure for storing items with specified values called \e + /// priorities in such a way that finding the item with minimum priority is + /// efficient. The bucket heap is very simple implementation, it can store + /// only integer priorities and it stores for each priority in the + /// \f$ [0..C) \f$ range a list of items. So it should be used only when + /// the priorities are small. It is not intended to use as dijkstra heap. + /// + /// \param _ItemIntMap A read and writable Item int map, used internally + /// to handle the cross references. + /// \param minimize If the given parameter is true then the heap gives back + /// the lowest priority. + template + class BucketHeap { + + public: + /// \e + typedef typename _ItemIntMap::Key Item; + /// \e + typedef int Prio; + /// \e + typedef std::pair Pair; + /// \e + typedef _ItemIntMap ItemIntMap; + + /// \brief Type to represent the items states. + /// + /// Each Item element have a state associated to it. It may be "in heap", + /// "pre heap" or "post heap". The latter two are indifferent from the + /// heap's point of view, but may be useful to the user. + /// + /// The ItemIntMap \e should be initialized in such way that it maps + /// PRE_HEAP (-1) to any element to be put in the heap... + enum State { + IN_HEAP = 0, + PRE_HEAP = -1, + POST_HEAP = -2 + }; + + public: + /// \brief The constructor. + /// + /// The constructor. + /// \param _index should be given to the constructor, since it is used + /// internally to handle the cross references. The value of the map + /// should be PRE_HEAP (-1) for each element. + explicit BucketHeap(ItemIntMap &_index) : index(_index), minimal(0) {} + + /// The number of items stored in the heap. + /// + /// \brief Returns the number of items stored in the heap. + int size() const { return data.size(); } + + /// \brief Checks if the heap stores no items. + /// + /// Returns \c true if and only if the heap stores no items. + bool empty() const { return data.empty(); } + + /// \brief Make empty this heap. + /// + /// Make empty this heap. It does not change the cross reference + /// map. If you want to reuse a heap what is not surely empty you + /// should first clear the heap and after that you should set the + /// cross reference map for each item to \c PRE_HEAP. + void clear() { + data.clear(); first.clear(); minimal = 0; + } + + private: + + void relocate_last(int idx) { + if (idx + 1 < int(data.size())) { + data[idx] = data.back(); + if (data[idx].prev != -1) { + data[data[idx].prev].next = idx; + } else { + first[data[idx].value] = idx; + } + if (data[idx].next != -1) { + data[data[idx].next].prev = idx; + } + index[data[idx].item] = idx; + } + data.pop_back(); + } + + void unlace(int idx) { + if (data[idx].prev != -1) { + data[data[idx].prev].next = data[idx].next; + } else { + first[data[idx].value] = data[idx].next; + } + if (data[idx].next != -1) { + data[data[idx].next].prev = data[idx].prev; + } + } + + void lace(int idx) { + if (int(first.size()) <= data[idx].value) { + first.resize(data[idx].value + 1, -1); + } + data[idx].next = first[data[idx].value]; + if (data[idx].next != -1) { + data[data[idx].next].prev = idx; + } + first[data[idx].value] = idx; + data[idx].prev = -1; + } + + public: + /// \brief Insert a pair of item and priority into the heap. + /// + /// Adds \c p.first to the heap with priority \c p.second. + /// \param p The pair to insert. + void push(const Pair& p) { + push(p.first, p.second); + } + + /// \brief Insert an item into the heap with the given priority. + /// + /// Adds \c i to the heap with priority \c p. + /// \param i The item to insert. + /// \param p The priority of the item. + void push(const Item &i, const Prio &p) { + int idx = data.size(); + index[i] = idx; + data.push_back(BucketItem(i, p)); + lace(idx); + if (p < minimal) { + minimal = p; + } + } + + /// \brief Returns the item with minimum priority. + /// + /// This method returns the item with minimum priority. + /// \pre The heap must be nonempty. + Item top() const { + while (first[minimal] == -1) { + ++minimal; + } + return data[first[minimal]].item; + } + + /// \brief Returns the minimum priority. + /// + /// It returns the minimum priority. + /// \pre The heap must be nonempty. + Prio prio() const { + while (first[minimal] == -1) { + ++minimal; + } + return minimal; + } + + /// \brief Deletes the item with minimum priority. + /// + /// This method deletes the item with minimum priority from the heap. + /// \pre The heap must be non-empty. + void pop() { + while (first[minimal] == -1) { + ++minimal; + } + int idx = first[minimal]; + index[data[idx].item] = -2; + unlace(idx); + relocate_last(idx); + } + + /// \brief Deletes \c i from the heap. + /// + /// This method deletes item \c i from the heap, if \c i was + /// already stored in the heap. + /// \param i The item to erase. + void erase(const Item &i) { + int idx = index[i]; + index[data[idx].item] = -2; + unlace(idx); + relocate_last(idx); + } + + + /// \brief Returns the priority of \c i. + /// + /// This function returns the priority of item \c i. + /// \pre \c i must be in the heap. + /// \param i The item. + Prio operator[](const Item &i) const { + int idx = index[i]; + return data[idx].value; + } + + /// \brief \c i gets to the heap with priority \c p independently + /// if \c i was already there. + /// + /// This method calls \ref push(\c i, \c p) if \c i is not stored + /// in the heap and sets the priority of \c i to \c p otherwise. + /// \param i The item. + /// \param p The priority. + void set(const Item &i, const Prio &p) { + int idx = index[i]; + if (idx < 0) { + push(i,p); + } else if (p > data[idx].value) { + increase(i, p); + } else { + decrease(i, p); + } + } + + /// \brief Decreases the priority of \c i to \c p. + /// + /// This method decreases the priority of item \c i to \c p. + /// \pre \c i must be stored in the heap with priority at least \c + /// p relative to \c Compare. + /// \param i The item. + /// \param p The priority. + void decrease(const Item &i, const Prio &p) { + int idx = index[i]; + unlace(idx); + data[idx].value = p; + if (p < minimal) { + minimal = p; + } + lace(idx); + } + + /// \brief Increases the priority of \c i to \c p. + /// + /// This method sets the priority of item \c i to \c p. + /// \pre \c i must be stored in the heap with priority at most \c + /// p relative to \c Compare. + /// \param i The item. + /// \param p The priority. + void increase(const Item &i, const Prio &p) { + int idx = index[i]; + unlace(idx); + data[idx].value = p; + lace(idx); + } + + /// \brief Returns if \c item is in, has already been in, or has + /// never been in the heap. + /// + /// This method returns PRE_HEAP if \c item has never been in the + /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP + /// otherwise. In the latter case it is possible that \c item will + /// get back to the heap again. + /// \param i The item. + State state(const Item &i) const { + int idx = index[i]; + if (idx >= 0) idx = 0; + return State(idx); + } + + /// \brief Sets the state of the \c item in the heap. + /// + /// Sets the state of the \c item in the heap. It can be used to + /// manually clear the heap when it is important to achive the + /// better time complexity. + /// \param i The item. + /// \param st The state. It should not be \c IN_HEAP. + void state(const Item& i, State st) { + switch (st) { + case POST_HEAP: + case PRE_HEAP: + if (state(i) == IN_HEAP) { + erase(i); + } + index[i] = st; + break; + case IN_HEAP: + break; + } + } + + private: + + struct BucketItem { + BucketItem(const Item& _item, int _value) + : item(_item), value(_value) {} + + Item item; + int value; + + int prev, next; + }; + + ItemIntMap& index; + std::vector first; + std::vector data; + mutable int minimal; + + }; // class BucketHeap + + + template + class BucketHeap<_ItemIntMap, false> { + + public: + typedef typename _ItemIntMap::Key Item; + typedef int Prio; + typedef std::pair Pair; + typedef _ItemIntMap ItemIntMap; + + enum State { + IN_HEAP = 0, + PRE_HEAP = -1, + POST_HEAP = -2 + }; + + public: + + explicit BucketHeap(ItemIntMap &_index) : index(_index), maximal(-1) {} + + int size() const { return data.size(); } + bool empty() const { return data.empty(); } + + void clear() { + data.clear(); first.clear(); maximal = -1; + } + + private: + + void relocate_last(int idx) { + if (idx + 1 != int(data.size())) { + data[idx] = data.back(); + if (data[idx].prev != -1) { + data[data[idx].prev].next = idx; + } else { + first[data[idx].value] = idx; + } + if (data[idx].next != -1) { + data[data[idx].next].prev = idx; + } + index[data[idx].item] = idx; + } + data.pop_back(); + } + + void unlace(int idx) { + if (data[idx].prev != -1) { + data[data[idx].prev].next = data[idx].next; + } else { + first[data[idx].value] = data[idx].next; + } + if (data[idx].next != -1) { + data[data[idx].next].prev = data[idx].prev; + } + } + + void lace(int idx) { + if (int(first.size()) <= data[idx].value) { + first.resize(data[idx].value + 1, -1); + } + data[idx].next = first[data[idx].value]; + if (data[idx].next != -1) { + data[data[idx].next].prev = idx; + } + first[data[idx].value] = idx; + data[idx].prev = -1; + } + + public: + + void push(const Pair& p) { + push(p.first, p.second); + } + + void push(const Item &i, const Prio &p) { + int idx = data.size(); + index[i] = idx; + data.push_back(BucketItem(i, p)); + lace(idx); + if (data[idx].value > maximal) { + maximal = data[idx].value; + } + } + + Item top() const { + while (first[maximal] == -1) { + --maximal; + } + return data[first[maximal]].item; + } + + Prio prio() const { + while (first[maximal] == -1) { + --maximal; + } + return maximal; + } + + void pop() { + while (first[maximal] == -1) { + --maximal; + } + int idx = first[maximal]; + index[data[idx].item] = -2; + unlace(idx); + relocate_last(idx); + } + + void erase(const Item &i) { + int idx = index[i]; + index[data[idx].item] = -2; + unlace(idx); + relocate_last(idx); + } + + Prio operator[](const Item &i) const { + int idx = index[i]; + return data[idx].value; + } + + void set(const Item &i, const Prio &p) { + int idx = index[i]; + if (idx < 0) { + push(i,p); + } else if (p > data[idx].value) { + decrease(i, p); + } else { + increase(i, p); + } + } + + void decrease(const Item &i, const Prio &p) { + int idx = index[i]; + unlace(idx); + data[idx].value = p; + if (p > maximal) { + maximal = p; + } + lace(idx); + } + + void increase(const Item &i, const Prio &p) { + int idx = index[i]; + unlace(idx); + data[idx].value = p; + lace(idx); + } + + State state(const Item &i) const { + int idx = index[i]; + if (idx >= 0) idx = 0; + return State(idx); + } + + void state(const Item& i, State st) { + switch (st) { + case POST_HEAP: + case PRE_HEAP: + if (state(i) == IN_HEAP) { + erase(i); + } + index[i] = st; + break; + case IN_HEAP: + break; + } + } + + private: + + struct BucketItem { + BucketItem(const Item& _item, int _value) + : item(_item), value(_value) {} + + Item item; + int value; + + int prev, next; + }; + + ItemIntMap& index; + std::vector first; + std::vector data; + mutable int maximal; + + }; // class BucketHeap + + /// \ingroup auxdat + /// + /// \brief A Simplified Bucket Heap implementation. + /// + /// This class implements a simplified \e bucket \e heap data + /// structure. It does not provide some functionality but it faster + /// and simplier data structure than the BucketHeap. The main + /// difference is that the BucketHeap stores for every key a double + /// linked list while this class stores just simple lists. In the + /// other way it does not supports erasing each elements just the + /// minimal and it does not supports key increasing, decreasing. + /// + /// \param _ItemIntMap A read and writable Item int map, used internally + /// to handle the cross references. + /// \param minimize If the given parameter is true then the heap gives back + /// the lowest priority. + /// + /// \sa BucketHeap + template + class SimpleBucketHeap { + + public: + typedef typename _ItemIntMap::Key Item; + typedef int Prio; + typedef std::pair Pair; + typedef _ItemIntMap ItemIntMap; + + /// \brief Type to represent the items states. + /// + /// Each Item element have a state associated to it. It may be "in heap", + /// "pre heap" or "post heap". The latter two are indifferent from the + /// heap's point of view, but may be useful to the user. + /// + /// The ItemIntMap \e should be initialized in such way that it maps + /// PRE_HEAP (-1) to any element to be put in the heap... + enum State { + IN_HEAP = 0, + PRE_HEAP = -1, + POST_HEAP = -2 + }; + + public: + + /// \brief The constructor. + /// + /// The constructor. + /// \param _index should be given to the constructor, since it is used + /// internally to handle the cross references. The value of the map + /// should be PRE_HEAP (-1) for each element. + explicit SimpleBucketHeap(ItemIntMap &_index) + : index(_index), free(-1), num(0), minimal(0) {} + + /// \brief Returns the number of items stored in the heap. + /// + /// The number of items stored in the heap. + int size() const { return num; } + + /// \brief Checks if the heap stores no items. + /// + /// Returns \c true if and only if the heap stores no items. + bool empty() const { return num == 0; } + + /// \brief Make empty this heap. + /// + /// Make empty this heap. It does not change the cross reference + /// map. If you want to reuse a heap what is not surely empty you + /// should first clear the heap and after that you should set the + /// cross reference map for each item to \c PRE_HEAP. + void clear() { + data.clear(); first.clear(); free = -1; num = 0; minimal = 0; + } + + /// \brief Insert a pair of item and priority into the heap. + /// + /// Adds \c p.first to the heap with priority \c p.second. + /// \param p The pair to insert. + void push(const Pair& p) { + push(p.first, p.second); + } + + /// \brief Insert an item into the heap with the given priority. + /// + /// Adds \c i to the heap with priority \c p. + /// \param i The item to insert. + /// \param p The priority of the item. + void push(const Item &i, const Prio &p) { + int idx; + if (free == -1) { + idx = data.size(); + data.push_back(BucketItem(i)); + } else { + idx = free; + free = data[idx].next; + data[idx].item = i; + } + index[i] = idx; + if (p >= int(first.size())) first.resize(p + 1, -1); + data[idx].next = first[p]; + first[p] = idx; + if (p < minimal) { + minimal = p; + } + ++num; + } + + /// \brief Returns the item with minimum priority. + /// + /// This method returns the item with minimum priority. + /// \pre The heap must be nonempty. + Item top() const { + while (first[minimal] == -1) { + ++minimal; + } + return data[first[minimal]].item; + } + + /// \brief Returns the minimum priority. + /// + /// It returns the minimum priority. + /// \pre The heap must be nonempty. + Prio prio() const { + while (first[minimal] == -1) { + ++minimal; + } + return minimal; + } + + /// \brief Deletes the item with minimum priority. + /// + /// This method deletes the item with minimum priority from the heap. + /// \pre The heap must be non-empty. + void pop() { + while (first[minimal] == -1) { + ++minimal; + } + int idx = first[minimal]; + index[data[idx].item] = -2; + first[minimal] = data[idx].next; + data[idx].next = free; + free = idx; + --num; + } + + /// \brief Returns the priority of \c i. + /// + /// This function returns the priority of item \c i. + /// \warning This operator is not a constant time function + /// because it scans the whole data structure to find the proper + /// value. + /// \pre \c i must be in the heap. + /// \param i The item. + Prio operator[](const Item &i) const { + for (int k = 0; k < first.size(); ++k) { + int idx = first[k]; + while (idx != -1) { + if (data[idx].item == i) { + return k; + } + idx = data[idx].next; + } + } + return -1; + } + + /// \brief Returns if \c item is in, has already been in, or has + /// never been in the heap. + /// + /// This method returns PRE_HEAP if \c item has never been in the + /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP + /// otherwise. In the latter case it is possible that \c item will + /// get back to the heap again. + /// \param i The item. + State state(const Item &i) const { + int idx = index[i]; + if (idx >= 0) idx = 0; + return State(idx); + } + + private: + + struct BucketItem { + BucketItem(const Item& _item) + : item(_item) {} + + Item item; + int next; + }; + + ItemIntMap& index; + std::vector first; + std::vector data; + int free, num; + mutable int minimal; + + }; // class SimpleBucketHeap + + template + class SimpleBucketHeap<_ItemIntMap, false> { + + public: + typedef typename _ItemIntMap::Key Item; + typedef int Prio; + typedef std::pair Pair; + typedef _ItemIntMap ItemIntMap; + + enum State { + IN_HEAP = 0, + PRE_HEAP = -1, + POST_HEAP = -2 + }; + + public: + + explicit SimpleBucketHeap(ItemIntMap &_index) + : index(_index), free(-1), num(0), maximal(0) {} + + int size() const { return num; } + + bool empty() const { return num == 0; } + + void clear() { + data.clear(); first.clear(); free = -1; num = 0; maximal = 0; + } + + void push(const Pair& p) { + push(p.first, p.second); + } + + void push(const Item &i, const Prio &p) { + int idx; + if (free == -1) { + idx = data.size(); + data.push_back(BucketItem(i)); + } else { + idx = free; + free = data[idx].next; + data[idx].item = i; + } + index[i] = idx; + if (p >= int(first.size())) first.resize(p + 1, -1); + data[idx].next = first[p]; + first[p] = idx; + if (p > maximal) { + maximal = p; + } + ++num; + } + + Item top() const { + while (first[maximal] == -1) { + --maximal; + } + return data[first[maximal]].item; + } + + Prio prio() const { + while (first[maximal] == -1) { + --maximal; + } + return maximal; + } + + void pop() { + while (first[maximal] == -1) { + --maximal; + } + int idx = first[maximal]; + index[data[idx].item] = -2; + first[maximal] = data[idx].next; + data[idx].next = free; + free = idx; + --num; + } + + Prio operator[](const Item &i) const { + for (int k = 0; k < first.size(); ++k) { + int idx = first[k]; + while (idx != -1) { + if (data[idx].item == i) { + return k; + } + idx = data[idx].next; + } + } + return -1; + } + + State state(const Item &i) const { + int idx = index[i]; + if (idx >= 0) idx = 0; + return State(idx); + } + + private: + + struct BucketItem { + BucketItem(const Item& _item) : item(_item) {} + + Item item; + + int next; + }; + + ItemIntMap& index; + std::vector first; + std::vector data; + int free, num; + mutable int maximal; + + }; + +} + +#endif diff -r 257e91516e09 -r 532697c9fa53 lemon/fib_heap.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemon/fib_heap.h Thu Jun 11 22:11:29 2009 +0200 @@ -0,0 +1,467 @@ +/* -*- mode: C++; indent-tabs-mode: nil; -*- + * + * This file is a part of LEMON, a generic C++ optimization library. + * + * Copyright (C) 2003-2009 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport + * (Egervary Research Group on Combinatorial Optimization, 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_FIB_HEAP_H +#define LEMON_FIB_HEAP_H + +///\file +///\ingroup auxdat +///\brief Fibonacci Heap implementation. + +#include +#include +#include + +namespace lemon { + + /// \ingroup auxdat + /// + ///\brief Fibonacci Heap. + /// + ///This class implements the \e Fibonacci \e heap data structure. A \e heap + ///is a data structure for storing items with specified values called \e + ///priorities in such a way that finding the item with minimum priority is + ///efficient. \c Compare specifies the ordering of the priorities. In a heap + ///one can change the priority of an item, add or erase an item, etc. + /// + ///The methods \ref increase and \ref erase are not efficient in a Fibonacci + ///heap. In case of many calls to these operations, it is better to use a + ///\ref BinHeap "binary heap". + /// + ///\param _Prio Type of the priority of the items. + ///\param _ItemIntMap A read and writable Item int map, used internally + ///to handle the cross references. + ///\param _Compare A class for the ordering of the priorities. The + ///default is \c std::less<_Prio>. + /// + ///\sa BinHeap + ///\sa Dijkstra +#ifdef DOXYGEN + template +#else + template > +#endif + class FibHeap { + public: + ///\e + typedef _ItemIntMap ItemIntMap; + ///\e + typedef _Prio Prio; + ///\e + typedef typename ItemIntMap::Key Item; + ///\e + typedef std::pair Pair; + ///\e + typedef _Compare Compare; + + private: + class store; + + std::vector container; + int minimum; + ItemIntMap &iimap; + Compare comp; + int num_items; + + public: + ///Status of the nodes + enum State { + ///The node is in the heap + IN_HEAP = 0, + ///The node has never been in the heap + PRE_HEAP = -1, + ///The node was in the heap but it got out of it + POST_HEAP = -2 + }; + + /// \brief The constructor + /// + /// \c _iimap should be given to the constructor, since it is + /// used internally to handle the cross references. + explicit FibHeap(ItemIntMap &_iimap) + : minimum(0), iimap(_iimap), num_items() {} + + /// \brief The constructor + /// + /// \c _iimap should be given to the constructor, since it is used + /// internally to handle the cross references. \c _comp is an + /// object for ordering of the priorities. + FibHeap(ItemIntMap &_iimap, const Compare &_comp) + : minimum(0), iimap(_iimap), comp(_comp), num_items() {} + + /// \brief The number of items stored in the heap. + /// + /// Returns the number of items stored in the heap. + int size() const { return num_items; } + + /// \brief Checks if the heap stores no items. + /// + /// Returns \c true if and only if the heap stores no items. + bool empty() const { return num_items==0; } + + /// \brief Make empty this heap. + /// + /// Make empty this heap. It does not change the cross reference + /// map. If you want to reuse a heap what is not surely empty you + /// should first clear the heap and after that you should set the + /// cross reference map for each item to \c PRE_HEAP. + void clear() { + container.clear(); minimum = 0; num_items = 0; + } + + /// \brief \c item gets to the heap with priority \c value independently + /// if \c item was already there. + /// + /// This method calls \ref push(\c item, \c value) if \c item is not + /// stored in the heap and it calls \ref decrease(\c item, \c value) or + /// \ref increase(\c item, \c value) otherwise. + void set (const Item& item, const Prio& value) { + int i=iimap[item]; + if ( i >= 0 && container[i].in ) { + if ( comp(value, container[i].prio) ) decrease(item, value); + if ( comp(container[i].prio, value) ) increase(item, value); + } else push(item, value); + } + + /// \brief Adds \c item to the heap with priority \c value. + /// + /// Adds \c item to the heap with priority \c value. + /// \pre \c item must not be stored in the heap. + void push (const Item& item, const Prio& value) { + int i=iimap[item]; + if ( i < 0 ) { + int s=container.size(); + iimap.set( item, s ); + store st; + st.name=item; + container.push_back(st); + i=s; + } else { + container[i].parent=container[i].child=-1; + container[i].degree=0; + container[i].in=true; + container[i].marked=false; + } + + if ( num_items ) { + container[container[minimum].right_neighbor].left_neighbor=i; + container[i].right_neighbor=container[minimum].right_neighbor; + container[minimum].right_neighbor=i; + container[i].left_neighbor=minimum; + if ( comp( value, container[minimum].prio) ) minimum=i; + } else { + container[i].right_neighbor=container[i].left_neighbor=i; + minimum=i; + } + container[i].prio=value; + ++num_items; + } + + /// \brief Returns the item with minimum priority relative to \c Compare. + /// + /// This method returns the item with minimum priority relative to \c + /// Compare. + /// \pre The heap must be nonempty. + Item top() const { return container[minimum].name; } + + /// \brief Returns the minimum priority relative to \c Compare. + /// + /// It returns the minimum priority relative to \c Compare. + /// \pre The heap must be nonempty. + const Prio& prio() const { return container[minimum].prio; } + + /// \brief Returns the priority of \c item. + /// + /// It returns the priority of \c item. + /// \pre \c item must be in the heap. + const Prio& operator[](const Item& item) const { + return container[iimap[item]].prio; + } + + /// \brief Deletes the item with minimum priority relative to \c Compare. + /// + /// This method deletes the item with minimum priority relative to \c + /// Compare from the heap. + /// \pre The heap must be non-empty. + void pop() { + /*The first case is that there are only one root.*/ + if ( container[minimum].left_neighbor==minimum ) { + container[minimum].in=false; + if ( container[minimum].degree!=0 ) { + makeroot(container[minimum].child); + minimum=container[minimum].child; + balance(); + } + } else { + int right=container[minimum].right_neighbor; + unlace(minimum); + container[minimum].in=false; + if ( container[minimum].degree > 0 ) { + int left=container[minimum].left_neighbor; + int child=container[minimum].child; + int last_child=container[child].left_neighbor; + + makeroot(child); + + container[left].right_neighbor=child; + container[child].left_neighbor=left; + container[right].left_neighbor=last_child; + container[last_child].right_neighbor=right; + } + minimum=right; + balance(); + } // the case where there are more roots + --num_items; + } + + /// \brief Deletes \c item from the heap. + /// + /// This method deletes \c item from the heap, if \c item was already + /// stored in the heap. It is quite inefficient in Fibonacci heaps. + void erase (const Item& item) { + int i=iimap[item]; + + if ( i >= 0 && container[i].in ) { + if ( container[i].parent!=-1 ) { + int p=container[i].parent; + cut(i,p); + cascade(p); + } + minimum=i; //As if its prio would be -infinity + pop(); + } + } + + /// \brief Decreases the priority of \c item to \c value. + /// + /// This method decreases the priority of \c item to \c value. + /// \pre \c item must be stored in the heap with priority at least \c + /// value relative to \c Compare. + void decrease (Item item, const Prio& value) { + int i=iimap[item]; + container[i].prio=value; + int p=container[i].parent; + + if ( p!=-1 && comp(value, container[p].prio) ) { + cut(i,p); + cascade(p); + } + if ( comp(value, container[minimum].prio) ) minimum=i; + } + + /// \brief Increases the priority of \c item to \c value. + /// + /// This method sets the priority of \c item to \c value. Though + /// there is no precondition on the priority of \c item, this + /// method should be used only if it is indeed necessary to increase + /// (relative to \c Compare) the priority of \c item, because this + /// method is inefficient. + void increase (Item item, const Prio& value) { + erase(item); + push(item, value); + } + + + /// \brief Returns if \c item is in, has already been in, or has never + /// been in the heap. + /// + /// This method returns PRE_HEAP if \c item has never been in the + /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP + /// otherwise. In the latter case it is possible that \c item will + /// get back to the heap again. + State state(const Item &item) const { + int i=iimap[item]; + if( i>=0 ) { + if ( container[i].in ) i=0; + else i=-2; + } + return State(i); + } + + /// \brief Sets the state of the \c item in the heap. + /// + /// Sets the state of the \c item in the heap. It can be used to + /// manually clear the heap when it is important to achive the + /// better time complexity. + /// \param i The item. + /// \param st The state. It should not be \c IN_HEAP. + void state(const Item& i, State st) { + switch (st) { + case POST_HEAP: + case PRE_HEAP: + if (state(i) == IN_HEAP) { + erase(i); + } + iimap[i] = st; + break; + case IN_HEAP: + break; + } + } + + private: + + void balance() { + + int maxdeg=int( std::floor( 2.08*log(double(container.size()))))+1; + + std::vector A(maxdeg,-1); + + /* + *Recall that now minimum does not point to the minimum prio element. + *We set minimum to this during balance(). + */ + int anchor=container[minimum].left_neighbor; + int next=minimum; + bool end=false; + + do { + int active=next; + if ( anchor==active ) end=true; + int d=container[active].degree; + next=container[active].right_neighbor; + + while (A[d]!=-1) { + if( comp(container[active].prio, container[A[d]].prio) ) { + fuse(active,A[d]); + } else { + fuse(A[d],active); + active=A[d]; + } + A[d]=-1; + ++d; + } + A[d]=active; + } while ( !end ); + + + while ( container[minimum].parent >=0 ) + minimum=container[minimum].parent; + int s=minimum; + int m=minimum; + do { + if ( comp(container[s].prio, container[minimum].prio) ) minimum=s; + s=container[s].right_neighbor; + } while ( s != m ); + } + + void makeroot(int c) { + int s=c; + do { + container[s].parent=-1; + s=container[s].right_neighbor; + } while ( s != c ); + } + + void cut(int a, int b) { + /* + *Replacing a from the children of b. + */ + --container[b].degree; + + if ( container[b].degree !=0 ) { + int child=container[b].child; + if ( child==a ) + container[b].child=container[child].right_neighbor; + unlace(a); + } + + + /*Lacing a to the roots.*/ + int right=container[minimum].right_neighbor; + container[minimum].right_neighbor=a; + container[a].left_neighbor=minimum; + container[a].right_neighbor=right; + container[right].left_neighbor=a; + + container[a].parent=-1; + container[a].marked=false; + } + + void cascade(int a) { + if ( container[a].parent!=-1 ) { + int p=container[a].parent; + + if ( container[a].marked==false ) container[a].marked=true; + else { + cut(a,p); + cascade(p); + } + } + } + + void fuse(int a, int b) { + unlace(b); + + /*Lacing b under a.*/ + container[b].parent=a; + + if (container[a].degree==0) { + container[b].left_neighbor=b; + container[b].right_neighbor=b; + container[a].child=b; + } else { + int child=container[a].child; + int last_child=container[child].left_neighbor; + container[child].left_neighbor=b; + container[b].right_neighbor=child; + container[last_child].right_neighbor=b; + container[b].left_neighbor=last_child; + } + + ++container[a].degree; + + container[b].marked=false; + } + + /* + *It is invoked only if a has siblings. + */ + void unlace(int a) { + int leftn=container[a].left_neighbor; + int rightn=container[a].right_neighbor; + container[leftn].right_neighbor=rightn; + container[rightn].left_neighbor=leftn; + } + + + class store { + friend class FibHeap; + + Item name; + int parent; + int left_neighbor; + int right_neighbor; + int child; + int degree; + bool marked; + bool in; + Prio prio; + + store() : parent(-1), child(-1), degree(), marked(false), in(true) {} + }; + }; + +} //namespace lemon + +#endif //LEMON_FIB_HEAP_H + diff -r 257e91516e09 -r 532697c9fa53 lemon/radix_heap.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemon/radix_heap.h Thu Jun 11 22:11:29 2009 +0200 @@ -0,0 +1,433 @@ +/* -*- mode: C++; indent-tabs-mode: nil; -*- + * + * This file is a part of LEMON, a generic C++ optimization library. + * + * Copyright (C) 2003-2009 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport + * (Egervary Research Group on Combinatorial Optimization, 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_RADIX_HEAP_H +#define LEMON_RADIX_HEAP_H + +///\ingroup auxdat +///\file +///\brief Radix Heap implementation. + +#include +#include + +namespace lemon { + + + /// \ingroup auxdata + /// + /// \brief A Radix Heap implementation. + /// + /// This class implements the \e radix \e heap data structure. A \e heap + /// is a data structure for storing items with specified values called \e + /// priorities in such a way that finding the item with minimum priority is + /// efficient. This heap type can store only items with \e int priority. + /// In a heap one can change the priority of an item, add or erase an + /// item, but the priority cannot be decreased under the last removed + /// item's priority. + /// + /// \param _ItemIntMap A read and writable Item int map, used internally + /// to handle the cross references. + /// + /// \see BinHeap + /// \see Dijkstra + template + class RadixHeap { + + public: + typedef typename _ItemIntMap::Key Item; + typedef int Prio; + typedef _ItemIntMap ItemIntMap; + + /// \brief Exception thrown by RadixHeap. + /// + /// This Exception is thrown when a smaller priority + /// is inserted into the \e RadixHeap then the last time erased. + /// \see RadixHeap + + class UnderFlowPriorityError : public Exception { + public: + virtual const char* what() const throw() { + return "lemon::RadixHeap::UnderFlowPriorityError"; + } + }; + + /// \brief Type to represent the items states. + /// + /// Each Item element have a state associated to it. It may be "in heap", + /// "pre heap" or "post heap". The latter two are indifferent from the + /// heap's point of view, but may be useful to the user. + /// + /// The ItemIntMap \e should be initialized in such way that it maps + /// PRE_HEAP (-1) to any element to be put in the heap... + enum State { + IN_HEAP = 0, + PRE_HEAP = -1, + POST_HEAP = -2 + }; + + private: + + struct RadixItem { + int prev, next, box; + Item item; + int prio; + RadixItem(Item _item, int _prio) : item(_item), prio(_prio) {} + }; + + struct RadixBox { + int first; + int min, size; + RadixBox(int _min, int _size) : first(-1), min(_min), size(_size) {} + }; + + std::vector data; + std::vector boxes; + + ItemIntMap &iim; + + + public: + /// \brief The constructor. + /// + /// The constructor. + /// + /// \param _iim It should be given to the constructor, since it is used + /// internally to handle the cross references. The value of the map + /// should be PRE_HEAP (-1) for each element. + /// + /// \param minimal The initial minimal value of the heap. + /// \param capacity It determines the initial capacity of the heap. + RadixHeap(ItemIntMap &_iim, int minimal = 0, int capacity = 0) + : iim(_iim) { + boxes.push_back(RadixBox(minimal, 1)); + boxes.push_back(RadixBox(minimal + 1, 1)); + while (lower(boxes.size() - 1, capacity + minimal - 1)) { + extend(); + } + } + + /// The number of items stored in the heap. + /// + /// \brief Returns the number of items stored in the heap. + int size() const { return data.size(); } + /// \brief Checks if the heap stores no items. + /// + /// Returns \c true if and only if the heap stores no items. + bool empty() const { return data.empty(); } + + /// \brief Make empty this heap. + /// + /// Make empty this heap. It does not change the cross reference + /// map. If you want to reuse a heap what is not surely empty you + /// should first clear the heap and after that you should set the + /// cross reference map for each item to \c PRE_HEAP. + void clear(int minimal = 0, int capacity = 0) { + data.clear(); boxes.clear(); + boxes.push_back(RadixBox(minimal, 1)); + boxes.push_back(RadixBox(minimal + 1, 1)); + while (lower(boxes.size() - 1, capacity + minimal - 1)) { + extend(); + } + } + + private: + + bool upper(int box, Prio pr) { + return pr < boxes[box].min; + } + + bool lower(int box, Prio pr) { + return pr >= boxes[box].min + boxes[box].size; + } + + /// \brief Remove item from the box list. + void remove(int index) { + if (data[index].prev >= 0) { + data[data[index].prev].next = data[index].next; + } else { + boxes[data[index].box].first = data[index].next; + } + if (data[index].next >= 0) { + data[data[index].next].prev = data[index].prev; + } + } + + /// \brief Insert item into the box list. + void insert(int box, int index) { + if (boxes[box].first == -1) { + boxes[box].first = index; + data[index].next = data[index].prev = -1; + } else { + data[index].next = boxes[box].first; + data[boxes[box].first].prev = index; + data[index].prev = -1; + boxes[box].first = index; + } + data[index].box = box; + } + + /// \brief Add a new box to the box list. + void extend() { + int min = boxes.back().min + boxes.back().size; + int bs = 2 * boxes.back().size; + boxes.push_back(RadixBox(min, bs)); + } + + /// \brief Move an item up into the proper box. + void bubble_up(int index) { + if (!lower(data[index].box, data[index].prio)) return; + remove(index); + int box = findUp(data[index].box, data[index].prio); + insert(box, index); + } + + /// \brief Find up the proper box for the item with the given prio. + int findUp(int start, int pr) { + while (lower(start, pr)) { + if (++start == int(boxes.size())) { + extend(); + } + } + return start; + } + + /// \brief Move an item down into the proper box. + void bubble_down(int index) { + if (!upper(data[index].box, data[index].prio)) return; + remove(index); + int box = findDown(data[index].box, data[index].prio); + insert(box, index); + } + + /// \brief Find up the proper box for the item with the given prio. + int findDown(int start, int pr) { + while (upper(start, pr)) { + if (--start < 0) throw UnderFlowPriorityError(); + } + return start; + } + + /// \brief Find the first not empty box. + int findFirst() { + int first = 0; + while (boxes[first].first == -1) ++first; + return first; + } + + /// \brief Gives back the minimal prio of the box. + int minValue(int box) { + int min = data[boxes[box].first].prio; + for (int k = boxes[box].first; k != -1; k = data[k].next) { + if (data[k].prio < min) min = data[k].prio; + } + return min; + } + + /// \brief Rearrange the items of the heap and makes the + /// first box not empty. + void moveDown() { + int box = findFirst(); + if (box == 0) return; + int min = minValue(box); + for (int i = 0; i <= box; ++i) { + boxes[i].min = min; + min += boxes[i].size; + } + int curr = boxes[box].first, next; + while (curr != -1) { + next = data[curr].next; + bubble_down(curr); + curr = next; + } + } + + void relocate_last(int index) { + if (index != int(data.size()) - 1) { + data[index] = data.back(); + if (data[index].prev != -1) { + data[data[index].prev].next = index; + } else { + boxes[data[index].box].first = index; + } + if (data[index].next != -1) { + data[data[index].next].prev = index; + } + iim[data[index].item] = index; + } + data.pop_back(); + } + + public: + + /// \brief Insert an item into the heap with the given priority. + /// + /// Adds \c i to the heap with priority \c p. + /// \param i The item to insert. + /// \param p The priority of the item. + void push(const Item &i, const Prio &p) { + int n = data.size(); + iim.set(i, n); + data.push_back(RadixItem(i, p)); + while (lower(boxes.size() - 1, p)) { + extend(); + } + int box = findDown(boxes.size() - 1, p); + insert(box, n); + } + + /// \brief Returns the item with minimum priority. + /// + /// This method returns the item with minimum priority. + /// \pre The heap must be nonempty. + Item top() const { + const_cast&>(*this).moveDown(); + return data[boxes[0].first].item; + } + + /// \brief Returns the minimum priority. + /// + /// It returns the minimum priority. + /// \pre The heap must be nonempty. + Prio prio() const { + const_cast&>(*this).moveDown(); + return data[boxes[0].first].prio; + } + + /// \brief Deletes the item with minimum priority. + /// + /// This method deletes the item with minimum priority. + /// \pre The heap must be non-empty. + void pop() { + moveDown(); + int index = boxes[0].first; + iim[data[index].item] = POST_HEAP; + remove(index); + relocate_last(index); + } + + /// \brief Deletes \c i from the heap. + /// + /// This method deletes item \c i from the heap, if \c i was + /// already stored in the heap. + /// \param i The item to erase. + void erase(const Item &i) { + int index = iim[i]; + iim[i] = POST_HEAP; + remove(index); + relocate_last(index); + } + + /// \brief Returns the priority of \c i. + /// + /// This function returns the priority of item \c i. + /// \pre \c i must be in the heap. + /// \param i The item. + Prio operator[](const Item &i) const { + int idx = iim[i]; + return data[idx].prio; + } + + /// \brief \c i gets to the heap with priority \c p independently + /// if \c i was already there. + /// + /// This method calls \ref push(\c i, \c p) if \c i is not stored + /// in the heap and sets the priority of \c i to \c p otherwise. + /// It may throw an \e UnderFlowPriorityException. + /// \param i The item. + /// \param p The priority. + void set(const Item &i, const Prio &p) { + int idx = iim[i]; + if( idx < 0 ) { + push(i, p); + } + else if( p >= data[idx].prio ) { + data[idx].prio = p; + bubble_up(idx); + } else { + data[idx].prio = p; + bubble_down(idx); + } + } + + + /// \brief Decreases the priority of \c i to \c p. + /// + /// This method decreases the priority of item \c i to \c p. + /// \pre \c i must be stored in the heap with priority at least \c p, and + /// \c should be greater or equal to the last removed item's priority. + /// \param i The item. + /// \param p The priority. + void decrease(const Item &i, const Prio &p) { + int idx = iim[i]; + data[idx].prio = p; + bubble_down(idx); + } + + /// \brief Increases the priority of \c i to \c p. + /// + /// This method sets the priority of item \c i to \c p. + /// \pre \c i must be stored in the heap with priority at most \c p + /// \param i The item. + /// \param p The priority. + void increase(const Item &i, const Prio &p) { + int idx = iim[i]; + data[idx].prio = p; + bubble_up(idx); + } + + /// \brief Returns if \c item is in, has already been in, or has + /// never been in the heap. + /// + /// This method returns PRE_HEAP if \c item has never been in the + /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP + /// otherwise. In the latter case it is possible that \c item will + /// get back to the heap again. + /// \param i The item. + State state(const Item &i) const { + int s = iim[i]; + if( s >= 0 ) s = 0; + return State(s); + } + + /// \brief Sets the state of the \c item in the heap. + /// + /// Sets the state of the \c item in the heap. It can be used to + /// manually clear the heap when it is important to achive the + /// better time complexity. + /// \param i The item. + /// \param st The state. It should not be \c IN_HEAP. + void state(const Item& i, State st) { + switch (st) { + case POST_HEAP: + case PRE_HEAP: + if (state(i) == IN_HEAP) { + erase(i); + } + iim[i] = st; + break; + case IN_HEAP: + break; + } + } + + }; // class RadixHeap + +} // namespace lemon + +#endif // LEMON_RADIX_HEAP_H diff -r 257e91516e09 -r 532697c9fa53 test/heap_test.cc --- a/test/heap_test.cc Fri May 29 17:46:48 2009 +0100 +++ b/test/heap_test.cc Thu Jun 11 22:11:29 2009 +0200 @@ -31,6 +31,9 @@ #include #include +#include +#include +#include #include "test_tools.h" @@ -183,5 +186,39 @@ dijkstraHeapTest(digraph, length, source); } + { + typedef FibHeap IntHeap; + checkConcept, IntHeap>(); + heapSortTest(); + heapIncreaseTest(); + + typedef FibHeap NodeHeap; + checkConcept, NodeHeap>(); + dijkstraHeapTest(digraph, length, source); + } + + { + typedef RadixHeap IntHeap; + checkConcept, IntHeap>(); + heapSortTest(); + heapIncreaseTest(); + + typedef RadixHeap NodeHeap; + checkConcept, NodeHeap>(); + dijkstraHeapTest(digraph, length, source); + } + + { + typedef BucketHeap IntHeap; + checkConcept, IntHeap>(); + heapSortTest(); + heapIncreaseTest(); + + typedef BucketHeap NodeHeap; + checkConcept, NodeHeap>(); + dijkstraHeapTest(digraph, length, source); + } + + return 0; }