COIN-OR::LEMON - Graph Library

Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • lemon/bellman_ford.h

    r1337 r870  
    1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
     1/* -*- C++ -*-
    22 *
    3  * This file is a part of LEMON, a generic C++ optimization library.
     3 * This file is a part of LEMON, a generic C++ optimization library
    44 *
    5  * Copyright (C) 2003-2013
     5 * Copyright (C) 2003-2008
    66 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    77 * (Egervary Research Group on Combinatorial Optimization, EGRES).
     
    3030#include <lemon/maps.h>
    3131#include <lemon/path.h>
    32 #include <lemon/bits/stl_iterators.h>
    3332
    3433#include <limits>
     
    3736
    3837  /// \brief Default OperationTraits for the BellmanFord algorithm class.
    39   ///
     38  /// 
    4039  /// This operation traits class defines all computational operations
    4140  /// and constants that are used in the Bellman-Ford algorithm.
     
    4443  /// value is used as extremal infinity value.
    4544  template <
    46     typename V,
     45    typename V, 
    4746    bool has_inf = std::numeric_limits<V>::has_infinity>
    4847  struct BellmanFordDefaultOperationTraits {
     
    8584    }
    8685  };
    87 
     86 
    8887  /// \brief Default traits class of BellmanFord class.
    8988  ///
     
    9392  template<typename GR, typename LEN>
    9493  struct BellmanFordDefaultTraits {
    95     /// The type of the digraph the algorithm runs on.
     94    /// The type of the digraph the algorithm runs on. 
    9695    typedef GR Digraph;
    9796
     
    111110    /// \see BellmanFordDefaultOperationTraits
    112111    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
    113 
    114     /// \brief The type of the map that stores the last arcs of the
     112 
     113    /// \brief The type of the map that stores the last arcs of the 
    115114    /// shortest paths.
    116     ///
     115    /// 
    117116    /// The type of the map that stores the last
    118117    /// arcs of the shortest paths.
     
    121120
    122121    /// \brief Instantiates a \c PredMap.
    123     ///
    124     /// This function instantiates a \ref PredMap.
     122    /// 
     123    /// This function instantiates a \ref PredMap. 
    125124    /// \param g is the digraph to which we would like to define the
    126125    /// \ref PredMap.
     
    137136    /// \brief Instantiates a \c DistMap.
    138137    ///
    139     /// This function instantiates a \ref DistMap.
    140     /// \param g is the digraph to which we would like to define the
     138    /// This function instantiates a \ref DistMap. 
     139    /// \param g is the digraph to which we would like to define the 
    141140    /// \ref DistMap.
    142141    static DistMap *createDistMap(const GR& g) {
     
    145144
    146145  };
    147 
     146 
    148147  /// \brief %BellmanFord algorithm class.
    149148  ///
    150149  /// \ingroup shortest_path
    151   /// This class provides an efficient implementation of the Bellman-Ford
     150  /// This class provides an efficient implementation of the Bellman-Ford 
    152151  /// algorithm. The maximum time complexity of the algorithm is
    153   /// <tt>O(nm)</tt>.
     152  /// <tt>O(ne)</tt>.
    154153  ///
    155154  /// The Bellman-Ford algorithm solves the single-source shortest path
     
    160159  ///
    161160  /// The arc lengths are passed to the algorithm using a
    162   /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
     161  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any 
    163162  /// kind of length. The type of the length values is determined by the
    164163  /// \ref concepts::ReadMap::Value "Value" type of the length map.
     
    173172  /// the lengths of the arcs. The default map type is
    174173  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
    175   /// \tparam TR The traits class that defines various types used by the
    176   /// algorithm. By default, it is \ref BellmanFordDefaultTraits
    177   /// "BellmanFordDefaultTraits<GR, LEN>".
    178   /// In most cases, this parameter should not be set directly,
    179   /// consider to use the named template parameters instead.
    180174#ifdef DOXYGEN
    181175  template <typename GR, typename LEN, typename TR>
     
    190184    ///The type of the underlying digraph.
    191185    typedef typename TR::Digraph Digraph;
    192 
     186   
    193187    /// \brief The type of the arc lengths.
    194188    typedef typename TR::LengthMap::Value Value;
     
    202196    /// The type of the paths.
    203197    typedef PredMapPath<Digraph, PredMap> Path;
    204     ///\brief The \ref lemon::BellmanFordDefaultOperationTraits
     198    ///\brief The \ref BellmanFordDefaultOperationTraits
    205199    /// "operation traits class" of the algorithm.
    206200    typedef typename TR::OperationTraits OperationTraits;
    207201
    208     ///\brief The \ref lemon::BellmanFordDefaultTraits "traits class"
    209     ///of the algorithm.
     202    ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
    210203    typedef TR Traits;
    211204
     
    238231    void create_maps() {
    239232      if(!_pred) {
    240         _local_pred = true;
    241         _pred = Traits::createPredMap(*_gr);
     233        _local_pred = true;
     234        _pred = Traits::createPredMap(*_gr);
    242235      }
    243236      if(!_dist) {
    244         _local_dist = true;
    245         _dist = Traits::createDistMap(*_gr);
     237        _local_dist = true;
     238        _dist = Traits::createDistMap(*_gr);
    246239      }
    247240      if(!_mask) {
     
    249242      }
    250243    }
    251 
     244   
    252245  public :
    253 
     246 
    254247    typedef BellmanFord Create;
    255248
     
    274267    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
    275268    template <class T>
    276     struct SetPredMap
     269    struct SetPredMap 
    277270      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
    278271      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
    279272    };
    280 
     273   
    281274    template <class T>
    282275    struct SetDistMapTraits : public Traits {
     
    295288    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
    296289    template <class T>
    297     struct SetDistMap
     290    struct SetDistMap 
    298291      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
    299292      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
     
    304297      typedef T OperationTraits;
    305298    };
    306 
    307     /// \brief \ref named-templ-param "Named parameter" for setting
     299   
     300    /// \brief \ref named-templ-param "Named parameter" for setting 
    308301    /// \c OperationTraits type.
    309302    ///
     
    317310      Create;
    318311    };
    319 
     312   
    320313    ///@}
    321314
    322315  protected:
    323 
     316   
    324317    BellmanFord() {}
    325318
    326   public:
    327 
     319  public:     
     320   
    328321    /// \brief Constructor.
    329322    ///
     
    335328      _pred(0), _local_pred(false),
    336329      _dist(0), _local_dist(false), _mask(0) {}
    337 
     330   
    338331    ///Destructor.
    339332    ~BellmanFord() {
     
    362355    BellmanFord &predMap(PredMap &map) {
    363356      if(_local_pred) {
    364         delete _pred;
    365         _local_pred=false;
     357        delete _pred;
     358        _local_pred=false;
    366359      }
    367360      _pred = &map;
     
    380373    BellmanFord &distMap(DistMap &map) {
    381374      if(_local_dist) {
    382         delete _dist;
    383         _local_dist=false;
     375        delete _dist;
     376        _local_dist=false;
    384377      }
    385378      _dist = &map;
     
    399392
    400393    /// \brief Initializes the internal data structures.
    401     ///
     394    /// 
    402395    /// Initializes the internal data structures. The optional parameter
    403396    /// is the initial distance of each node.
     
    405398      create_maps();
    406399      for (NodeIt it(*_gr); it != INVALID; ++it) {
    407         _pred->set(it, INVALID);
    408         _dist->set(it, value);
     400        _pred->set(it, INVALID);
     401        _dist->set(it, value);
    409402      }
    410403      _process.clear();
    411404      if (OperationTraits::less(value, OperationTraits::infinity())) {
    412         for (NodeIt it(*_gr); it != INVALID; ++it) {
    413           _process.push_back(it);
    414           _mask->set(it, true);
    415         }
     405        for (NodeIt it(*_gr); it != INVALID; ++it) {
     406          _process.push_back(it);
     407          _mask->set(it, true);
     408        }
    416409      } else {
    417         for (NodeIt it(*_gr); it != INVALID; ++it) {
    418           _mask->set(it, false);
    419         }
    420       }
    421     }
    422 
     410        for (NodeIt it(*_gr); it != INVALID; ++it) {
     411          _mask->set(it, false);
     412        }
     413      }
     414    }
     415   
    423416    /// \brief Adds a new source node.
    424417    ///
     
    428421      _dist->set(source, dst);
    429422      if (!(*_mask)[source]) {
    430         _process.push_back(source);
    431         _mask->set(source, true);
     423        _process.push_back(source);
     424        _mask->set(source, true);
    432425      }
    433426    }
     
    454447    bool processNextRound() {
    455448      for (int i = 0; i < int(_process.size()); ++i) {
    456         _mask->set(_process[i], false);
     449        _mask->set(_process[i], false);
    457450      }
    458451      std::vector<Node> nextProcess;
    459452      std::vector<Value> values(_process.size());
    460453      for (int i = 0; i < int(_process.size()); ++i) {
    461         values[i] = (*_dist)[_process[i]];
     454        values[i] = (*_dist)[_process[i]];
    462455      }
    463456      for (int i = 0; i < int(_process.size()); ++i) {
    464         for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
    465           Node target = _gr->target(it);
    466           Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
    467           if (OperationTraits::less(relaxed, (*_dist)[target])) {
    468             _pred->set(target, it);
    469             _dist->set(target, relaxed);
    470             if (!(*_mask)[target]) {
    471               _mask->set(target, true);
    472               nextProcess.push_back(target);
    473             }
    474           }
    475         }
     457        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
     458          Node target = _gr->target(it);
     459          Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
     460          if (OperationTraits::less(relaxed, (*_dist)[target])) {
     461            _pred->set(target, it);
     462            _dist->set(target, relaxed);
     463            if (!(*_mask)[target]) {
     464              _mask->set(target, true);
     465              nextProcess.push_back(target);
     466            }
     467          }       
     468        }
    476469      }
    477470      _process.swap(nextProcess);
     
    495488    bool processNextWeakRound() {
    496489      for (int i = 0; i < int(_process.size()); ++i) {
    497         _mask->set(_process[i], false);
     490        _mask->set(_process[i], false);
    498491      }
    499492      std::vector<Node> nextProcess;
    500493      for (int i = 0; i < int(_process.size()); ++i) {
    501         for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
    502           Node target = _gr->target(it);
    503           Value relaxed =
    504             OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
    505           if (OperationTraits::less(relaxed, (*_dist)[target])) {
    506             _pred->set(target, it);
    507             _dist->set(target, relaxed);
    508             if (!(*_mask)[target]) {
    509               _mask->set(target, true);
    510               nextProcess.push_back(target);
    511             }
    512           }
    513         }
     494        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
     495          Node target = _gr->target(it);
     496          Value relaxed =
     497            OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
     498          if (OperationTraits::less(relaxed, (*_dist)[target])) {
     499            _pred->set(target, it);
     500            _dist->set(target, relaxed);
     501            if (!(*_mask)[target]) {
     502              _mask->set(target, true);
     503              nextProcess.push_back(target);
     504            }
     505          }       
     506        }
    514507      }
    515508      _process.swap(nextProcess);
     
    533526      int num = countNodes(*_gr) - 1;
    534527      for (int i = 0; i < num; ++i) {
    535         if (processNextWeakRound()) break;
     528        if (processNextWeakRound()) break;
    536529      }
    537530    }
     
    545538    /// if the digraph contains cycles with negative total length.
    546539    ///
    547     /// The algorithm computes
     540    /// The algorithm computes 
    548541    /// - the shortest path tree (forest),
    549542    /// - the distance of each node from the root(s).
    550     ///
     543    /// 
    551544    /// \return \c false if there is a negative cycle in the digraph.
    552545    ///
    553546    /// \pre init() must be called and at least one root node should be
    554     /// added with addSource() before using this function.
     547    /// added with addSource() before using this function. 
    555548    bool checkedStart() {
    556549      int num = countNodes(*_gr);
    557550      for (int i = 0; i < num; ++i) {
    558         if (processNextWeakRound()) return true;
     551        if (processNextWeakRound()) return true;
    559552      }
    560553      return _process.empty();
     
    580573    ///
    581574    /// \pre init() must be called and at least one root node should be
    582     /// added with addSource() before using this function.
     575    /// added with addSource() before using this function. 
    583576    void limitedStart(int num) {
    584577      for (int i = 0; i < num; ++i) {
    585         if (processNextRound()) break;
    586       }
    587     }
    588 
     578        if (processNextRound()) break;
     579      }
     580    }
     581   
    589582    /// \brief Runs the algorithm from the given root node.
    590     ///
     583    ///   
    591584    /// This method runs the Bellman-Ford algorithm from the given root
    592585    /// node \c s in order to compute the shortest path to each node.
     
    607600      start();
    608601    }
    609 
     602   
    610603    /// \brief Runs the algorithm from the given root node with arc
    611604    /// number limit.
    612     ///
     605    ///   
    613606    /// This method runs the Bellman-Ford algorithm from the given root
    614607    /// node \c s in order to compute the shortest path distance for each
     
    636629      limitedStart(num);
    637630    }
    638 
     631   
    639632    ///@}
    640633
     
    651644      ///
    652645      /// Constructor for getting the active nodes of the given BellmanFord
    653       /// instance.
     646      /// instance. 
    654647      ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
    655648      {
     
    665658      ///
    666659      /// Conversion to \c Node.
    667       operator Node() const {
     660      operator Node() const { 
    668661        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
    669662      }
     
    674667      ActiveIt& operator++() {
    675668        --_index;
    676         return *this;
    677       }
    678 
    679       bool operator==(const ActiveIt& it) const {
    680         return static_cast<Node>(*this) == static_cast<Node>(it);
    681       }
    682       bool operator!=(const ActiveIt& it) const {
    683         return static_cast<Node>(*this) != static_cast<Node>(it);
    684       }
    685       bool operator<(const ActiveIt& it) const {
    686         return static_cast<Node>(*this) < static_cast<Node>(it);
    687       }
    688 
     669        return *this; 
     670      }
     671
     672      bool operator==(const ActiveIt& it) const { 
     673        return static_cast<Node>(*this) == static_cast<Node>(it); 
     674      }
     675      bool operator!=(const ActiveIt& it) const { 
     676        return static_cast<Node>(*this) != static_cast<Node>(it); 
     677      }
     678      bool operator<(const ActiveIt& it) const { 
     679        return static_cast<Node>(*this) < static_cast<Node>(it); 
     680      }
     681     
    689682    private:
    690683      const BellmanFord* _algorithm;
    691684      int _index;
    692685    };
    693 
    694     /// \brief Gets the collection of the active nodes.
    695     ///
    696     /// This function can be used for iterating on the active nodes of the
    697     /// Bellman-Ford algorithm after the last phase.
    698     /// These nodes should be checked in the next phase to
    699     /// find augmenting arcs outgoing from them.
    700     /// It returns a wrapped ActiveIt, which looks
    701     /// like an STL container (by having begin() and end())
    702     /// which you can use in range-based for loops, STL algorithms, etc.
    703     LemonRangeWrapper1<ActiveIt, BellmanFord>
    704     activeNodes() const {
    705       return LemonRangeWrapper1<ActiveIt, BellmanFord>(*this);
    706     }
    707 
    708 
     686   
    709687    /// \name Query Functions
    710688    /// The result of the Bellman-Ford algorithm can be obtained using these
    711689    /// functions.\n
    712690    /// Either \ref run() or \ref init() should be called before using them.
    713 
     691   
    714692    ///@{
    715693
    716694    /// \brief The shortest path to the given node.
    717     ///
     695    ///   
    718696    /// Gives back the shortest path to the given node from the root(s).
    719697    ///
     
    726704      return Path(*_gr, *_pred, t);
    727705    }
    728 
     706         
    729707    /// \brief The distance of the given node from the root(s).
    730708    ///
     
    766744    /// \pre Either \ref run() or \ref init() must be called before
    767745    /// using this function.
    768     Node predNode(Node v) const {
    769       return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
    770     }
    771 
     746    Node predNode(Node v) const { 
     747      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]); 
     748    }
     749   
    772750    /// \brief Returns a const reference to the node map that stores the
    773751    /// distances of the nodes.
     
    779757    /// using this function.
    780758    const DistMap &distMap() const { return *_dist;}
    781 
     759 
    782760    /// \brief Returns a const reference to the node map that stores the
    783761    /// predecessor arcs.
     
    789767    /// using this function.
    790768    const PredMap &predMap() const { return *_pred; }
    791 
     769 
    792770    /// \brief Checks if a node is reached from the root(s).
    793771    ///
     
    801779
    802780    /// \brief Gives back a negative cycle.
    803     ///
     781    ///   
    804782    /// This function gives back a directed cycle with negative total
    805783    /// length if the algorithm has already found one.
     
    828806      return cycle;
    829807    }
    830 
     808   
    831809    ///@}
    832810  };
    833 
     811 
    834812  /// \brief Default traits class of bellmanFord() function.
    835813  ///
     
    839817  template <typename GR, typename LEN>
    840818  struct BellmanFordWizardDefaultTraits {
    841     /// The type of the digraph the algorithm runs on.
     819    /// The type of the digraph the algorithm runs on. 
    842820    typedef GR Digraph;
    843821
     
    860838    /// \brief The type of the map that stores the last
    861839    /// arcs of the shortest paths.
    862     ///
     840    /// 
    863841    /// The type of the map that stores the last arcs of the shortest paths.
    864842    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
     
    866844
    867845    /// \brief Instantiates a \c PredMap.
    868     ///
     846    /// 
    869847    /// This function instantiates a \ref PredMap.
    870848    /// \param g is the digraph to which we would like to define the
     
    882860    /// \brief Instantiates a \c DistMap.
    883861    ///
    884     /// This function instantiates a \ref DistMap.
     862    /// This function instantiates a \ref DistMap. 
    885863    /// \param g is the digraph to which we would like to define the
    886864    /// \ref DistMap.
     
    895873    typedef lemon::Path<Digraph> Path;
    896874  };
    897 
     875 
    898876  /// \brief Default traits class used by BellmanFordWizard.
    899877  ///
     
    902880  /// \tparam LEN The type of the length map.
    903881  template <typename GR, typename LEN>
    904   class BellmanFordWizardBase
     882  class BellmanFordWizardBase 
    905883    : public BellmanFordWizardDefaultTraits<GR, LEN> {
    906884
     
    925903    public:
    926904    /// Constructor.
    927 
     905   
    928906    /// This constructor does not require parameters, it initiates
    929907    /// all of the attributes to default values \c 0.
     
    932910
    933911    /// Constructor.
    934 
     912   
    935913    /// This constructor requires two parameters,
    936914    /// others are initiated to \c 0.
    937915    /// \param gr The digraph the algorithm runs on.
    938916    /// \param len The length map.
    939     BellmanFordWizardBase(const GR& gr,
    940                           const LEN& len) :
    941       _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
    942       _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
     917    BellmanFordWizardBase(const GR& gr, 
     918                          const LEN& len) :
     919      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))), 
     920      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))), 
    943921      _pred(0), _dist(0), _path(0), _di(0) {}
    944922
    945923  };
    946 
     924 
    947925  /// \brief Auxiliary class for the function-type interface of the
    948926  /// \ref BellmanFord "Bellman-Ford" algorithm.
     
    956934  /// This class should only be used through the \ref bellmanFord()
    957935  /// function, which makes it easier to use the algorithm.
    958   ///
    959   /// \tparam TR The traits class that defines various types used by the
    960   /// algorithm.
    961936  template<class TR>
    962937  class BellmanFordWizard : public TR {
     
    969944    typedef typename Digraph::Arc Arc;
    970945    typedef typename Digraph::OutArcIt ArcIt;
    971 
     946   
    972947    typedef typename TR::LengthMap LengthMap;
    973948    typedef typename LengthMap::Value Value;
     
    986961    /// \param gr The digraph the algorithm runs on.
    987962    /// \param len The length map.
    988     BellmanFordWizard(const Digraph& gr, const LengthMap& len)
     963    BellmanFordWizard(const Digraph& gr, const LengthMap& len) 
    989964      : TR(gr, len) {}
    990965
     
    995970
    996971    /// \brief Runs the Bellman-Ford algorithm from the given source node.
    997     ///
     972    ///   
    998973    /// This method runs the Bellman-Ford algorithm from the given source
    999974    /// node in order to compute the shortest path to each node.
    1000975    void run(Node s) {
    1001       BellmanFord<Digraph,LengthMap,TR>
    1002         bf(*reinterpret_cast<const Digraph*>(Base::_graph),
     976      BellmanFord<Digraph,LengthMap,TR> 
     977        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
    1003978           *reinterpret_cast<const LengthMap*>(Base::_length));
    1004979      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
     
    10351010      SetPredMapBase(const TR &b) : TR(b) {}
    10361011    };
    1037 
     1012   
    10381013    /// \brief \ref named-templ-param "Named parameter" for setting
    10391014    /// the predecessor map.
     
    10461021      return BellmanFordWizard<SetPredMapBase<T> >(*this);
    10471022    }
    1048 
     1023   
    10491024    template<class T>
    10501025    struct SetDistMapBase : public Base {
     
    10531028      SetDistMapBase(const TR &b) : TR(b) {}
    10541029    };
    1055 
     1030   
    10561031    /// \brief \ref named-templ-param "Named parameter" for setting
    10571032    /// the distance map.
     
    10941069      return *this;
    10951070    }
    1096 
     1071   
    10971072  };
    1098 
     1073 
    10991074  /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
    11001075  /// algorithm.
     
    11041079  /// algorithm.
    11051080  ///
    1106   /// This function also has several \ref named-templ-func-param
    1107   /// "named parameters", they are declared as the members of class
     1081  /// This function also has several \ref named-templ-func-param 
     1082  /// "named parameters", they are declared as the members of class 
    11081083  /// \ref BellmanFordWizard.
    11091084  /// The following examples show how to use these parameters.
     
    11221097  BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
    11231098  bellmanFord(const GR& digraph,
    1124               const LEN& length)
     1099              const LEN& length)
    11251100  {
    11261101    return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
Note: See TracChangeset for help on using the changeset viewer.