COIN-OR::LEMON - Graph Library

Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • lemon/bellman_ford.h

    r870 r1270  
    1 /* -*- C++ -*-
     1/* -*- mode: C++; indent-tabs-mode: nil; -*-
    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-2008
     5 * Copyright (C) 2003-2013
    66 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    77 * (Egervary Research Group on Combinatorial Optimization, EGRES).
     
    3636
    3737  /// \brief Default OperationTraits for the BellmanFord algorithm class.
    38   /// 
     38  ///
    3939  /// This operation traits class defines all computational operations
    4040  /// and constants that are used in the Bellman-Ford algorithm.
     
    4343  /// value is used as extremal infinity value.
    4444  template <
    45     typename V, 
     45    typename V,
    4646    bool has_inf = std::numeric_limits<V>::has_infinity>
    4747  struct BellmanFordDefaultOperationTraits {
     
    8484    }
    8585  };
    86  
     86
    8787  /// \brief Default traits class of BellmanFord class.
    8888  ///
     
    9292  template<typename GR, typename LEN>
    9393  struct BellmanFordDefaultTraits {
    94     /// The type of the digraph the algorithm runs on. 
     94    /// The type of the digraph the algorithm runs on.
    9595    typedef GR Digraph;
    9696
     
    110110    /// \see BellmanFordDefaultOperationTraits
    111111    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
    112  
    113     /// \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
    114114    /// shortest paths.
    115     /// 
     115    ///
    116116    /// The type of the map that stores the last
    117117    /// arcs of the shortest paths.
     
    120120
    121121    /// \brief Instantiates a \c PredMap.
    122     /// 
    123     /// This function instantiates a \ref PredMap. 
     122    ///
     123    /// This function instantiates a \ref PredMap.
    124124    /// \param g is the digraph to which we would like to define the
    125125    /// \ref PredMap.
     
    136136    /// \brief Instantiates a \c DistMap.
    137137    ///
    138     /// This function instantiates a \ref DistMap. 
    139     /// \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
    140140    /// \ref DistMap.
    141141    static DistMap *createDistMap(const GR& g) {
     
    144144
    145145  };
    146  
     146
    147147  /// \brief %BellmanFord algorithm class.
    148148  ///
    149149  /// \ingroup shortest_path
    150   /// This class provides an efficient implementation of the Bellman-Ford 
     150  /// This class provides an efficient implementation of the Bellman-Ford
    151151  /// algorithm. The maximum time complexity of the algorithm is
    152   /// <tt>O(ne)</tt>.
     152  /// <tt>O(nm)</tt>.
    153153  ///
    154154  /// The Bellman-Ford algorithm solves the single-source shortest path
     
    159159  ///
    160160  /// The arc lengths are passed to the algorithm using a
    161   /// \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
    162162  /// kind of length. The type of the length values is determined by the
    163163  /// \ref concepts::ReadMap::Value "Value" type of the length map.
     
    172172  /// the lengths of the arcs. The default map type is
    173173  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
     174  /// \tparam TR The traits class that defines various types used by the
     175  /// algorithm. By default, it is \ref BellmanFordDefaultTraits
     176  /// "BellmanFordDefaultTraits<GR, LEN>".
     177  /// In most cases, this parameter should not be set directly,
     178  /// consider to use the named template parameters instead.
    174179#ifdef DOXYGEN
    175180  template <typename GR, typename LEN, typename TR>
     
    184189    ///The type of the underlying digraph.
    185190    typedef typename TR::Digraph Digraph;
    186    
     191
    187192    /// \brief The type of the arc lengths.
    188193    typedef typename TR::LengthMap::Value Value;
     
    196201    /// The type of the paths.
    197202    typedef PredMapPath<Digraph, PredMap> Path;
    198     ///\brief The \ref BellmanFordDefaultOperationTraits
     203    ///\brief The \ref lemon::BellmanFordDefaultOperationTraits
    199204    /// "operation traits class" of the algorithm.
    200205    typedef typename TR::OperationTraits OperationTraits;
    201206
    202     ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
     207    ///\brief The \ref lemon::BellmanFordDefaultTraits "traits class"
     208    ///of the algorithm.
    203209    typedef TR Traits;
    204210
     
    231237    void create_maps() {
    232238      if(!_pred) {
    233         _local_pred = true;
    234         _pred = Traits::createPredMap(*_gr);
     239        _local_pred = true;
     240        _pred = Traits::createPredMap(*_gr);
    235241      }
    236242      if(!_dist) {
    237         _local_dist = true;
    238         _dist = Traits::createDistMap(*_gr);
     243        _local_dist = true;
     244        _dist = Traits::createDistMap(*_gr);
    239245      }
    240246      if(!_mask) {
     
    242248      }
    243249    }
    244    
     250
    245251  public :
    246  
     252
    247253    typedef BellmanFord Create;
    248254
     
    267273    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
    268274    template <class T>
    269     struct SetPredMap 
     275    struct SetPredMap
    270276      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
    271277      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
    272278    };
    273    
     279
    274280    template <class T>
    275281    struct SetDistMapTraits : public Traits {
     
    288294    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
    289295    template <class T>
    290     struct SetDistMap 
     296    struct SetDistMap
    291297      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
    292298      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
     
    297303      typedef T OperationTraits;
    298304    };
    299    
    300     /// \brief \ref named-templ-param "Named parameter" for setting 
     305
     306    /// \brief \ref named-templ-param "Named parameter" for setting
    301307    /// \c OperationTraits type.
    302308    ///
     
    310316      Create;
    311317    };
    312    
     318
    313319    ///@}
    314320
    315321  protected:
    316    
     322
    317323    BellmanFord() {}
    318324
    319   public:     
    320    
     325  public:
     326
    321327    /// \brief Constructor.
    322328    ///
     
    328334      _pred(0), _local_pred(false),
    329335      _dist(0), _local_dist(false), _mask(0) {}
    330    
     336
    331337    ///Destructor.
    332338    ~BellmanFord() {
     
    355361    BellmanFord &predMap(PredMap &map) {
    356362      if(_local_pred) {
    357         delete _pred;
    358         _local_pred=false;
     363        delete _pred;
     364        _local_pred=false;
    359365      }
    360366      _pred = &map;
     
    373379    BellmanFord &distMap(DistMap &map) {
    374380      if(_local_dist) {
    375         delete _dist;
    376         _local_dist=false;
     381        delete _dist;
     382        _local_dist=false;
    377383      }
    378384      _dist = &map;
     
    392398
    393399    /// \brief Initializes the internal data structures.
    394     /// 
     400    ///
    395401    /// Initializes the internal data structures. The optional parameter
    396402    /// is the initial distance of each node.
     
    398404      create_maps();
    399405      for (NodeIt it(*_gr); it != INVALID; ++it) {
    400         _pred->set(it, INVALID);
    401         _dist->set(it, value);
     406        _pred->set(it, INVALID);
     407        _dist->set(it, value);
    402408      }
    403409      _process.clear();
    404410      if (OperationTraits::less(value, OperationTraits::infinity())) {
    405         for (NodeIt it(*_gr); it != INVALID; ++it) {
    406           _process.push_back(it);
    407           _mask->set(it, true);
    408         }
     411        for (NodeIt it(*_gr); it != INVALID; ++it) {
     412          _process.push_back(it);
     413          _mask->set(it, true);
     414        }
    409415      } else {
    410         for (NodeIt it(*_gr); it != INVALID; ++it) {
    411           _mask->set(it, false);
    412         }
    413       }
    414     }
    415    
     416        for (NodeIt it(*_gr); it != INVALID; ++it) {
     417          _mask->set(it, false);
     418        }
     419      }
     420    }
     421
    416422    /// \brief Adds a new source node.
    417423    ///
     
    421427      _dist->set(source, dst);
    422428      if (!(*_mask)[source]) {
    423         _process.push_back(source);
    424         _mask->set(source, true);
     429        _process.push_back(source);
     430        _mask->set(source, true);
    425431      }
    426432    }
     
    447453    bool processNextRound() {
    448454      for (int i = 0; i < int(_process.size()); ++i) {
    449         _mask->set(_process[i], false);
     455        _mask->set(_process[i], false);
    450456      }
    451457      std::vector<Node> nextProcess;
    452458      std::vector<Value> values(_process.size());
    453459      for (int i = 0; i < int(_process.size()); ++i) {
    454         values[i] = (*_dist)[_process[i]];
     460        values[i] = (*_dist)[_process[i]];
    455461      }
    456462      for (int i = 0; i < int(_process.size()); ++i) {
    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         }
     463        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
     464          Node target = _gr->target(it);
     465          Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
     466          if (OperationTraits::less(relaxed, (*_dist)[target])) {
     467            _pred->set(target, it);
     468            _dist->set(target, relaxed);
     469            if (!(*_mask)[target]) {
     470              _mask->set(target, true);
     471              nextProcess.push_back(target);
     472            }
     473          }
     474        }
    469475      }
    470476      _process.swap(nextProcess);
     
    488494    bool processNextWeakRound() {
    489495      for (int i = 0; i < int(_process.size()); ++i) {
    490         _mask->set(_process[i], false);
     496        _mask->set(_process[i], false);
    491497      }
    492498      std::vector<Node> nextProcess;
    493499      for (int i = 0; i < int(_process.size()); ++i) {
    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         }
     500        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
     501          Node target = _gr->target(it);
     502          Value relaxed =
     503            OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
     504          if (OperationTraits::less(relaxed, (*_dist)[target])) {
     505            _pred->set(target, it);
     506            _dist->set(target, relaxed);
     507            if (!(*_mask)[target]) {
     508              _mask->set(target, true);
     509              nextProcess.push_back(target);
     510            }
     511          }
     512        }
    507513      }
    508514      _process.swap(nextProcess);
     
    526532      int num = countNodes(*_gr) - 1;
    527533      for (int i = 0; i < num; ++i) {
    528         if (processNextWeakRound()) break;
     534        if (processNextWeakRound()) break;
    529535      }
    530536    }
     
    538544    /// if the digraph contains cycles with negative total length.
    539545    ///
    540     /// The algorithm computes 
     546    /// The algorithm computes
    541547    /// - the shortest path tree (forest),
    542548    /// - the distance of each node from the root(s).
    543     /// 
     549    ///
    544550    /// \return \c false if there is a negative cycle in the digraph.
    545551    ///
    546552    /// \pre init() must be called and at least one root node should be
    547     /// added with addSource() before using this function. 
     553    /// added with addSource() before using this function.
    548554    bool checkedStart() {
    549555      int num = countNodes(*_gr);
    550556      for (int i = 0; i < num; ++i) {
    551         if (processNextWeakRound()) return true;
     557        if (processNextWeakRound()) return true;
    552558      }
    553559      return _process.empty();
     
    573579    ///
    574580    /// \pre init() must be called and at least one root node should be
    575     /// added with addSource() before using this function. 
     581    /// added with addSource() before using this function.
    576582    void limitedStart(int num) {
    577583      for (int i = 0; i < num; ++i) {
    578         if (processNextRound()) break;
    579       }
    580     }
    581    
     584        if (processNextRound()) break;
     585      }
     586    }
     587
    582588    /// \brief Runs the algorithm from the given root node.
    583     ///   
     589    ///
    584590    /// This method runs the Bellman-Ford algorithm from the given root
    585591    /// node \c s in order to compute the shortest path to each node.
     
    600606      start();
    601607    }
    602    
     608
    603609    /// \brief Runs the algorithm from the given root node with arc
    604610    /// number limit.
    605     ///   
     611    ///
    606612    /// This method runs the Bellman-Ford algorithm from the given root
    607613    /// node \c s in order to compute the shortest path distance for each
     
    629635      limitedStart(num);
    630636    }
    631    
     637
    632638    ///@}
    633639
     
    644650      ///
    645651      /// Constructor for getting the active nodes of the given BellmanFord
    646       /// instance. 
     652      /// instance.
    647653      ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
    648654      {
     
    658664      ///
    659665      /// Conversion to \c Node.
    660       operator Node() const { 
     666      operator Node() const {
    661667        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
    662668      }
     
    667673      ActiveIt& operator++() {
    668674        --_index;
    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      
     675        return *this;
     676      }
     677
     678      bool operator==(const ActiveIt& it) const {
     679        return static_cast<Node>(*this) == static_cast<Node>(it);
     680      }
     681      bool operator!=(const ActiveIt& it) const {
     682        return static_cast<Node>(*this) != static_cast<Node>(it);
     683      }
     684      bool operator<(const ActiveIt& it) const {
     685        return static_cast<Node>(*this) < static_cast<Node>(it);
     686      }
     687
    682688    private:
    683689      const BellmanFord* _algorithm;
    684690      int _index;
    685691    };
    686    
     692
    687693    /// \name Query Functions
    688694    /// The result of the Bellman-Ford algorithm can be obtained using these
    689695    /// functions.\n
    690696    /// Either \ref run() or \ref init() should be called before using them.
    691    
     697
    692698    ///@{
    693699
    694700    /// \brief The shortest path to the given node.
    695     ///   
     701    ///
    696702    /// Gives back the shortest path to the given node from the root(s).
    697703    ///
     
    704710      return Path(*_gr, *_pred, t);
    705711    }
    706          
     712
    707713    /// \brief The distance of the given node from the root(s).
    708714    ///
     
    744750    /// \pre Either \ref run() or \ref init() must be called before
    745751    /// using this function.
    746     Node predNode(Node v) const { 
    747       return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]); 
    748     }
    749    
     752    Node predNode(Node v) const {
     753      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
     754    }
     755
    750756    /// \brief Returns a const reference to the node map that stores the
    751757    /// distances of the nodes.
     
    757763    /// using this function.
    758764    const DistMap &distMap() const { return *_dist;}
    759  
     765
    760766    /// \brief Returns a const reference to the node map that stores the
    761767    /// predecessor arcs.
     
    767773    /// using this function.
    768774    const PredMap &predMap() const { return *_pred; }
    769  
     775
    770776    /// \brief Checks if a node is reached from the root(s).
    771777    ///
     
    779785
    780786    /// \brief Gives back a negative cycle.
    781     ///   
     787    ///
    782788    /// This function gives back a directed cycle with negative total
    783789    /// length if the algorithm has already found one.
     
    806812      return cycle;
    807813    }
    808    
     814
    809815    ///@}
    810816  };
    811  
     817
    812818  /// \brief Default traits class of bellmanFord() function.
    813819  ///
     
    817823  template <typename GR, typename LEN>
    818824  struct BellmanFordWizardDefaultTraits {
    819     /// The type of the digraph the algorithm runs on. 
     825    /// The type of the digraph the algorithm runs on.
    820826    typedef GR Digraph;
    821827
     
    838844    /// \brief The type of the map that stores the last
    839845    /// arcs of the shortest paths.
    840     /// 
     846    ///
    841847    /// The type of the map that stores the last arcs of the shortest paths.
    842848    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
     
    844850
    845851    /// \brief Instantiates a \c PredMap.
    846     /// 
     852    ///
    847853    /// This function instantiates a \ref PredMap.
    848854    /// \param g is the digraph to which we would like to define the
     
    860866    /// \brief Instantiates a \c DistMap.
    861867    ///
    862     /// This function instantiates a \ref DistMap. 
     868    /// This function instantiates a \ref DistMap.
    863869    /// \param g is the digraph to which we would like to define the
    864870    /// \ref DistMap.
     
    873879    typedef lemon::Path<Digraph> Path;
    874880  };
    875  
     881
    876882  /// \brief Default traits class used by BellmanFordWizard.
    877883  ///
     
    880886  /// \tparam LEN The type of the length map.
    881887  template <typename GR, typename LEN>
    882   class BellmanFordWizardBase 
     888  class BellmanFordWizardBase
    883889    : public BellmanFordWizardDefaultTraits<GR, LEN> {
    884890
     
    903909    public:
    904910    /// Constructor.
    905    
     911
    906912    /// This constructor does not require parameters, it initiates
    907913    /// all of the attributes to default values \c 0.
     
    910916
    911917    /// Constructor.
    912    
     918
    913919    /// This constructor requires two parameters,
    914920    /// others are initiated to \c 0.
    915921    /// \param gr The digraph the algorithm runs on.
    916922    /// \param len The length map.
    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))), 
     923    BellmanFordWizardBase(const GR& gr,
     924                          const LEN& len) :
     925      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
     926      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
    921927      _pred(0), _dist(0), _path(0), _di(0) {}
    922928
    923929  };
    924  
     930
    925931  /// \brief Auxiliary class for the function-type interface of the
    926932  /// \ref BellmanFord "Bellman-Ford" algorithm.
     
    934940  /// This class should only be used through the \ref bellmanFord()
    935941  /// function, which makes it easier to use the algorithm.
     942  ///
     943  /// \tparam TR The traits class that defines various types used by the
     944  /// algorithm.
    936945  template<class TR>
    937946  class BellmanFordWizard : public TR {
     
    944953    typedef typename Digraph::Arc Arc;
    945954    typedef typename Digraph::OutArcIt ArcIt;
    946    
     955
    947956    typedef typename TR::LengthMap LengthMap;
    948957    typedef typename LengthMap::Value Value;
     
    961970    /// \param gr The digraph the algorithm runs on.
    962971    /// \param len The length map.
    963     BellmanFordWizard(const Digraph& gr, const LengthMap& len) 
     972    BellmanFordWizard(const Digraph& gr, const LengthMap& len)
    964973      : TR(gr, len) {}
    965974
     
    970979
    971980    /// \brief Runs the Bellman-Ford algorithm from the given source node.
    972     ///   
     981    ///
    973982    /// This method runs the Bellman-Ford algorithm from the given source
    974983    /// node in order to compute the shortest path to each node.
    975984    void run(Node s) {
    976       BellmanFord<Digraph,LengthMap,TR> 
    977         bf(*reinterpret_cast<const Digraph*>(Base::_graph),
     985      BellmanFord<Digraph,LengthMap,TR>
     986        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
    978987           *reinterpret_cast<const LengthMap*>(Base::_length));
    979988      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
     
    10101019      SetPredMapBase(const TR &b) : TR(b) {}
    10111020    };
    1012    
     1021
    10131022    /// \brief \ref named-templ-param "Named parameter" for setting
    10141023    /// the predecessor map.
     
    10211030      return BellmanFordWizard<SetPredMapBase<T> >(*this);
    10221031    }
    1023    
     1032
    10241033    template<class T>
    10251034    struct SetDistMapBase : public Base {
     
    10281037      SetDistMapBase(const TR &b) : TR(b) {}
    10291038    };
    1030    
     1039
    10311040    /// \brief \ref named-templ-param "Named parameter" for setting
    10321041    /// the distance map.
     
    10691078      return *this;
    10701079    }
    1071    
     1080
    10721081  };
    1073  
     1082
    10741083  /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
    10751084  /// algorithm.
     
    10791088  /// algorithm.
    10801089  ///
    1081   /// This function also has several \ref named-templ-func-param 
    1082   /// "named parameters", they are declared as the members of class 
     1090  /// This function also has several \ref named-templ-func-param
     1091  /// "named parameters", they are declared as the members of class
    10831092  /// \ref BellmanFordWizard.
    10841093  /// The following examples show how to use these parameters.
     
    10971106  BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
    10981107  bellmanFord(const GR& digraph,
    1099               const LEN& length)
     1108              const LEN& length)
    11001109  {
    11011110    return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
Note: See TracChangeset for help on using the changeset viewer.