1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2010
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_BELLMAN_FORD_H
20 #define LEMON_BELLMAN_FORD_H
22 /// \ingroup shortest_path
24 /// \brief Bellman-Ford algorithm.
26 #include <lemon/list_graph.h>
27 #include <lemon/bits/path_dump.h>
28 #include <lemon/core.h>
29 #include <lemon/error.h>
30 #include <lemon/maps.h>
31 #include <lemon/tolerance.h>
32 #include <lemon/path.h>
38 /// \brief Default operation traits for the BellmanFord algorithm class.
40 /// This operation traits class defines all computational operations
41 /// and constants that are used in the Bellman-Ford algorithm.
42 /// The default implementation is based on the \c numeric_limits class.
43 /// If the numeric type does not have infinity value, then the maximum
44 /// value is used as extremal infinity value.
46 /// \see BellmanFordToleranceOperationTraits
49 bool has_inf = std::numeric_limits<V>::has_infinity>
50 struct BellmanFordDefaultOperationTraits {
51 /// \brief Value type for the algorithm.
53 /// \brief Gives back the zero value of the type.
55 return static_cast<Value>(0);
57 /// \brief Gives back the positive infinity value of the type.
58 static Value infinity() {
59 return std::numeric_limits<Value>::infinity();
61 /// \brief Gives back the sum of the given two elements.
62 static Value plus(const Value& left, const Value& right) {
65 /// \brief Gives back \c true only if the first value is less than
67 static bool less(const Value& left, const Value& right) {
73 struct BellmanFordDefaultOperationTraits<V, false> {
76 return static_cast<Value>(0);
78 static Value infinity() {
79 return std::numeric_limits<Value>::max();
81 static Value plus(const Value& left, const Value& right) {
82 if (left == infinity() || right == infinity()) return infinity();
85 static bool less(const Value& left, const Value& right) {
90 /// \brief Operation traits for the BellmanFord algorithm class
93 /// This operation traits class defines all computational operations
94 /// and constants that are used in the Bellman-Ford algorithm.
95 /// The only difference between this implementation and
96 /// \ref BellmanFordDefaultOperationTraits is that this class uses
97 /// the \ref Tolerance "tolerance technique" in its \ref less()
100 /// \tparam V The value type.
101 /// \tparam eps The epsilon value for the \ref less() function.
102 /// By default, it is the epsilon value used by \ref Tolerance
105 /// \see BellmanFordDefaultOperationTraits
107 template <typename V, V eps>
111 V eps = Tolerance<V>::def_epsilon>
113 struct BellmanFordToleranceOperationTraits {
114 /// \brief Value type for the algorithm.
116 /// \brief Gives back the zero value of the type.
117 static Value zero() {
118 return static_cast<Value>(0);
120 /// \brief Gives back the positive infinity value of the type.
121 static Value infinity() {
122 return std::numeric_limits<Value>::infinity();
124 /// \brief Gives back the sum of the given two elements.
125 static Value plus(const Value& left, const Value& right) {
128 /// \brief Gives back \c true only if the first value is less than
130 static bool less(const Value& left, const Value& right) {
131 return left + eps < right;
135 /// \brief Default traits class of BellmanFord class.
137 /// Default traits class of BellmanFord class.
138 /// \param GR The type of the digraph.
139 /// \param LEN The type of the length map.
140 template<typename GR, typename LEN>
141 struct BellmanFordDefaultTraits {
142 /// The type of the digraph the algorithm runs on.
145 /// \brief The type of the map that stores the arc lengths.
147 /// The type of the map that stores the arc lengths.
148 /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
149 typedef LEN LengthMap;
151 /// The type of the arc lengths.
152 typedef typename LEN::Value Value;
154 /// \brief Operation traits for Bellman-Ford algorithm.
156 /// It defines the used operations and the infinity value for the
157 /// given \c Value type.
158 /// \see BellmanFordDefaultOperationTraits,
159 /// BellmanFordToleranceOperationTraits
160 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
162 /// \brief The type of the map that stores the last arcs of the
165 /// The type of the map that stores the last
166 /// arcs of the shortest paths.
167 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
168 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
170 /// \brief Instantiates a \c PredMap.
172 /// This function instantiates a \ref PredMap.
173 /// \param g is the digraph to which we would like to define the
175 static PredMap *createPredMap(const GR& g) {
176 return new PredMap(g);
179 /// \brief The type of the map that stores the distances of the nodes.
181 /// The type of the map that stores the distances of the nodes.
182 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
183 typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
185 /// \brief Instantiates a \c DistMap.
187 /// This function instantiates a \ref DistMap.
188 /// \param g is the digraph to which we would like to define the
190 static DistMap *createDistMap(const GR& g) {
191 return new DistMap(g);
196 /// \brief %BellmanFord algorithm class.
198 /// \ingroup shortest_path
199 /// This class provides an efficient implementation of the Bellman-Ford
200 /// algorithm. The maximum time complexity of the algorithm is
203 /// The Bellman-Ford algorithm solves the single-source shortest path
204 /// problem when the arcs can have negative lengths, but the digraph
205 /// should not contain directed cycles with negative total length.
206 /// If all arc costs are non-negative, consider to use the Dijkstra
207 /// algorithm instead, since it is more efficient.
209 /// The arc lengths are passed to the algorithm using a
210 /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
211 /// kind of length. The type of the length values is determined by the
212 /// \ref concepts::ReadMap::Value "Value" type of the length map.
214 /// There is also a \ref bellmanFord() "function-type interface" for the
215 /// Bellman-Ford algorithm, which is convenient in the simplier cases and
216 /// it can be used easier.
218 /// \tparam GR The type of the digraph the algorithm runs on.
219 /// The default type is \ref ListDigraph.
220 /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
221 /// the lengths of the arcs. The default map type is
222 /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
223 /// \tparam TR The traits class that defines various types used by the
224 /// algorithm. By default, it is \ref BellmanFordDefaultTraits
225 /// "BellmanFordDefaultTraits<GR, LEN>".
226 /// In most cases, this parameter should not be set directly,
227 /// consider to use the named template parameters instead.
229 template <typename GR, typename LEN, typename TR>
231 template <typename GR=ListDigraph,
232 typename LEN=typename GR::template ArcMap<int>,
233 typename TR=BellmanFordDefaultTraits<GR,LEN> >
238 ///The type of the underlying digraph.
239 typedef typename TR::Digraph Digraph;
241 /// \brief The type of the arc lengths.
242 typedef typename TR::LengthMap::Value Value;
243 /// \brief The type of the map that stores the arc lengths.
244 typedef typename TR::LengthMap LengthMap;
245 /// \brief The type of the map that stores the last
246 /// arcs of the shortest paths.
247 typedef typename TR::PredMap PredMap;
248 /// \brief The type of the map that stores the distances of the nodes.
249 typedef typename TR::DistMap DistMap;
250 /// The type of the paths.
251 typedef PredMapPath<Digraph, PredMap> Path;
252 ///\brief The \ref BellmanFordDefaultOperationTraits
253 /// "operation traits class" of the algorithm.
254 typedef typename TR::OperationTraits OperationTraits;
256 ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
261 typedef typename Digraph::Node Node;
262 typedef typename Digraph::NodeIt NodeIt;
263 typedef typename Digraph::Arc Arc;
264 typedef typename Digraph::OutArcIt OutArcIt;
266 // Pointer to the underlying digraph.
268 // Pointer to the length map
269 const LengthMap *_length;
270 // Pointer to the map of predecessors arcs.
272 // Indicates if _pred is locally allocated (true) or not.
274 // Pointer to the map of distances.
276 // Indicates if _dist is locally allocated (true) or not.
279 typedef typename Digraph::template NodeMap<bool> MaskMap;
282 std::vector<Node> _process;
284 // Creates the maps if necessary.
288 _pred = Traits::createPredMap(*_gr);
292 _dist = Traits::createDistMap(*_gr);
295 _mask = new MaskMap(*_gr);
301 typedef BellmanFord Create;
303 /// \name Named Template Parameters
308 struct SetPredMapTraits : public Traits {
310 static PredMap *createPredMap(const Digraph&) {
311 LEMON_ASSERT(false, "PredMap is not initialized");
312 return 0; // ignore warnings
316 /// \brief \ref named-templ-param "Named parameter" for setting
319 /// \ref named-templ-param "Named parameter" for setting
321 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
324 : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
325 typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
329 struct SetDistMapTraits : public Traits {
331 static DistMap *createDistMap(const Digraph&) {
332 LEMON_ASSERT(false, "DistMap is not initialized");
333 return 0; // ignore warnings
337 /// \brief \ref named-templ-param "Named parameter" for setting
340 /// \ref named-templ-param "Named parameter" for setting
342 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
345 : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
346 typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
350 struct SetOperationTraitsTraits : public Traits {
351 typedef T OperationTraits;
354 /// \brief \ref named-templ-param "Named parameter" for setting
355 /// \c OperationTraits type.
357 /// \ref named-templ-param "Named parameter" for setting
358 /// \c OperationTraits type.
359 /// For more information, see \ref BellmanFordDefaultOperationTraits.
361 struct SetOperationTraits
362 : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
363 typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
375 /// \brief Constructor.
378 /// \param g The digraph the algorithm runs on.
379 /// \param length The length map used by the algorithm.
380 BellmanFord(const Digraph& g, const LengthMap& length) :
381 _gr(&g), _length(&length),
382 _pred(0), _local_pred(false),
383 _dist(0), _local_dist(false), _mask(0) {}
387 if(_local_pred) delete _pred;
388 if(_local_dist) delete _dist;
389 if(_mask) delete _mask;
392 /// \brief Sets the length map.
394 /// Sets the length map.
395 /// \return <tt>(*this)</tt>
396 BellmanFord &lengthMap(const LengthMap &map) {
401 /// \brief Sets the map that stores the predecessor arcs.
403 /// Sets the map that stores the predecessor arcs.
404 /// If you don't use this function before calling \ref run()
405 /// or \ref init(), an instance will be allocated automatically.
406 /// The destructor deallocates this automatically allocated map,
408 /// \return <tt>(*this)</tt>
409 BellmanFord &predMap(PredMap &map) {
418 /// \brief Sets the map that stores the distances of the nodes.
420 /// Sets the map that stores the distances of the nodes calculated
421 /// by the algorithm.
422 /// If you don't use this function before calling \ref run()
423 /// or \ref init(), an instance will be allocated automatically.
424 /// The destructor deallocates this automatically allocated map,
426 /// \return <tt>(*this)</tt>
427 BellmanFord &distMap(DistMap &map) {
436 /// \name Execution Control
437 /// The simplest way to execute the Bellman-Ford algorithm is to use
438 /// one of the member functions called \ref run().\n
439 /// If you need better control on the execution, you have to call
440 /// \ref init() first, then you can add several source nodes
441 /// with \ref addSource(). Finally the actual path computation can be
442 /// performed with \ref start(), \ref checkedStart() or
443 /// \ref limitedStart().
447 /// \brief Initializes the internal data structures.
449 /// Initializes the internal data structures. The optional parameter
450 /// is the initial distance of each node.
451 void init(const Value value = OperationTraits::infinity()) {
453 for (NodeIt it(*_gr); it != INVALID; ++it) {
454 _pred->set(it, INVALID);
455 _dist->set(it, value);
458 if (OperationTraits::less(value, OperationTraits::infinity())) {
459 for (NodeIt it(*_gr); it != INVALID; ++it) {
460 _process.push_back(it);
461 _mask->set(it, true);
464 for (NodeIt it(*_gr); it != INVALID; ++it) {
465 _mask->set(it, false);
470 /// \brief Adds a new source node.
472 /// This function adds a new source node. The optional second parameter
473 /// is the initial distance of the node.
474 void addSource(Node source, Value dst = OperationTraits::zero()) {
475 _dist->set(source, dst);
476 if (!(*_mask)[source]) {
477 _process.push_back(source);
478 _mask->set(source, true);
482 /// \brief Executes one round from the Bellman-Ford algorithm.
484 /// If the algoritm calculated the distances in the previous round
485 /// exactly for the paths of at most \c k arcs, then this function
486 /// will calculate the distances exactly for the paths of at most
487 /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
488 /// calculates the shortest path distances exactly for the paths
489 /// consisting of at most \c k arcs.
491 /// \warning The paths with limited arc number cannot be retrieved
492 /// easily with \ref path() or \ref predArc() functions. If you also
493 /// need the shortest paths and not only the distances, you should
494 /// store the \ref predMap() "predecessor map" after each iteration
495 /// and build the path manually.
497 /// \return \c true when the algorithm have not found more shorter
501 bool processNextRound() {
502 for (int i = 0; i < int(_process.size()); ++i) {
503 _mask->set(_process[i], false);
505 std::vector<Node> nextProcess;
506 std::vector<Value> values(_process.size());
507 for (int i = 0; i < int(_process.size()); ++i) {
508 values[i] = (*_dist)[_process[i]];
510 for (int i = 0; i < int(_process.size()); ++i) {
511 for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
512 Node target = _gr->target(it);
513 Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
514 if (OperationTraits::less(relaxed, (*_dist)[target])) {
515 _pred->set(target, it);
516 _dist->set(target, relaxed);
517 if (!(*_mask)[target]) {
518 _mask->set(target, true);
519 nextProcess.push_back(target);
524 _process.swap(nextProcess);
525 return _process.empty();
528 /// \brief Executes one weak round from the Bellman-Ford algorithm.
530 /// If the algorithm calculated the distances in the previous round
531 /// at least for the paths of at most \c k arcs, then this function
532 /// will calculate the distances at least for the paths of at most
533 /// <tt>k+1</tt> arcs.
534 /// This function does not make it possible to calculate the shortest
535 /// path distances exactly for paths consisting of at most \c k arcs,
536 /// this is why it is called weak round.
538 /// \return \c true when the algorithm have not found more shorter
542 bool processNextWeakRound() {
543 for (int i = 0; i < int(_process.size()); ++i) {
544 _mask->set(_process[i], false);
546 std::vector<Node> nextProcess;
547 for (int i = 0; i < int(_process.size()); ++i) {
548 for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
549 Node target = _gr->target(it);
551 OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
552 if (OperationTraits::less(relaxed, (*_dist)[target])) {
553 _pred->set(target, it);
554 _dist->set(target, relaxed);
555 if (!(*_mask)[target]) {
556 _mask->set(target, true);
557 nextProcess.push_back(target);
562 _process.swap(nextProcess);
563 return _process.empty();
566 /// \brief Executes the algorithm.
568 /// Executes the algorithm.
570 /// This method runs the Bellman-Ford algorithm from the root node(s)
571 /// in order to compute the shortest path to each node.
573 /// The algorithm computes
574 /// - the shortest path tree (forest),
575 /// - the distance of each node from the root(s).
577 /// \pre init() must be called and at least one root node should be
578 /// added with addSource() before using this function.
580 int num = countNodes(*_gr) - 1;
581 for (int i = 0; i < num; ++i) {
582 if (processNextWeakRound()) break;
586 /// \brief Executes the algorithm and checks the negative cycles.
588 /// Executes the algorithm and checks the negative cycles.
590 /// This method runs the Bellman-Ford algorithm from the root node(s)
591 /// in order to compute the shortest path to each node and also checks
592 /// if the digraph contains cycles with negative total length.
594 /// The algorithm computes
595 /// - the shortest path tree (forest),
596 /// - the distance of each node from the root(s).
598 /// \return \c false if there is a negative cycle in the digraph.
600 /// \pre init() must be called and at least one root node should be
601 /// added with addSource() before using this function.
602 bool checkedStart() {
603 int num = countNodes(*_gr);
604 for (int i = 0; i < num; ++i) {
605 if (processNextWeakRound()) return true;
607 return _process.empty();
610 /// \brief Executes the algorithm with arc number limit.
612 /// Executes the algorithm with arc number limit.
614 /// This method runs the Bellman-Ford algorithm from the root node(s)
615 /// in order to compute the shortest path distance for each node
616 /// using only the paths consisting of at most \c num arcs.
618 /// The algorithm computes
619 /// - the limited distance of each node from the root(s),
620 /// - the predecessor arc for each node.
622 /// \warning The paths with limited arc number cannot be retrieved
623 /// easily with \ref path() or \ref predArc() functions. If you also
624 /// need the shortest paths and not only the distances, you should
625 /// store the \ref predMap() "predecessor map" after each iteration
626 /// and build the path manually.
628 /// \pre init() must be called and at least one root node should be
629 /// added with addSource() before using this function.
630 void limitedStart(int num) {
631 for (int i = 0; i < num; ++i) {
632 if (processNextRound()) break;
636 /// \brief Runs the algorithm from the given root node.
638 /// This method runs the Bellman-Ford algorithm from the given root
639 /// node \c s in order to compute the shortest path to each node.
641 /// The algorithm computes
642 /// - the shortest path tree (forest),
643 /// - the distance of each node from the root(s).
645 /// \note bf.run(s) is just a shortcut of the following code.
657 /// \brief Runs the algorithm from the given root node with arc
660 /// This method runs the Bellman-Ford algorithm from the given root
661 /// node \c s in order to compute the shortest path distance for each
662 /// node using only the paths consisting of at most \c num arcs.
664 /// The algorithm computes
665 /// - the limited distance of each node from the root(s),
666 /// - the predecessor arc for each node.
668 /// \warning The paths with limited arc number cannot be retrieved
669 /// easily with \ref path() or \ref predArc() functions. If you also
670 /// need the shortest paths and not only the distances, you should
671 /// store the \ref predMap() "predecessor map" after each iteration
672 /// and build the path manually.
674 /// \note bf.run(s, num) is just a shortcut of the following code.
678 /// bf.limitedStart(num);
680 void run(Node s, int num) {
688 /// \brief LEMON iterator for getting the active nodes.
690 /// This class provides a common style LEMON iterator that traverses
691 /// the active nodes of the Bellman-Ford algorithm after the last
692 /// phase. These nodes should be checked in the next phase to
693 /// find augmenting arcs outgoing from them.
697 /// \brief Constructor.
699 /// Constructor for getting the active nodes of the given BellmanFord
701 ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
703 _index = _algorithm->_process.size() - 1;
706 /// \brief Invalid constructor.
708 /// Invalid constructor.
709 ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
711 /// \brief Conversion to \c Node.
713 /// Conversion to \c Node.
714 operator Node() const {
715 return _index >= 0 ? _algorithm->_process[_index] : INVALID;
718 /// \brief Increment operator.
720 /// Increment operator.
721 ActiveIt& operator++() {
726 bool operator==(const ActiveIt& it) const {
727 return static_cast<Node>(*this) == static_cast<Node>(it);
729 bool operator!=(const ActiveIt& it) const {
730 return static_cast<Node>(*this) != static_cast<Node>(it);
732 bool operator<(const ActiveIt& it) const {
733 return static_cast<Node>(*this) < static_cast<Node>(it);
737 const BellmanFord* _algorithm;
741 /// \name Query Functions
742 /// The result of the Bellman-Ford algorithm can be obtained using these
744 /// Either \ref run() or \ref init() should be called before using them.
748 /// \brief The shortest path to the given node.
750 /// Gives back the shortest path to the given node from the root(s).
752 /// \warning \c t should be reached from the root(s).
754 /// \pre Either \ref run() or \ref init() must be called before
755 /// using this function.
756 Path path(Node t) const
758 return Path(*_gr, *_pred, t);
761 /// \brief The distance of the given node from the root(s).
763 /// Returns the distance of the given node from the root(s).
765 /// \warning If node \c v is not reached from the root(s), then
766 /// the return value of this function is undefined.
768 /// \pre Either \ref run() or \ref init() must be called before
769 /// using this function.
770 Value dist(Node v) const { return (*_dist)[v]; }
772 /// \brief Returns the 'previous arc' of the shortest path tree for
775 /// This function returns the 'previous arc' of the shortest path
776 /// tree for node \c v, i.e. it returns the last arc of a
777 /// shortest path from a root to \c v. It is \c INVALID if \c v
778 /// is not reached from the root(s) or if \c v is a root.
780 /// The shortest path tree used here is equal to the shortest path
781 /// tree used in \ref predNode() and \ref predMap().
783 /// \pre Either \ref run() or \ref init() must be called before
784 /// using this function.
785 Arc predArc(Node v) const { return (*_pred)[v]; }
787 /// \brief Returns the 'previous node' of the shortest path tree for
790 /// This function returns the 'previous node' of the shortest path
791 /// tree for node \c v, i.e. it returns the last but one node of
792 /// a shortest path from a root to \c v. It is \c INVALID if \c v
793 /// is not reached from the root(s) or if \c v is a root.
795 /// The shortest path tree used here is equal to the shortest path
796 /// tree used in \ref predArc() and \ref predMap().
798 /// \pre Either \ref run() or \ref init() must be called before
799 /// using this function.
800 Node predNode(Node v) const {
801 return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
804 /// \brief Returns a const reference to the node map that stores the
805 /// distances of the nodes.
807 /// Returns a const reference to the node map that stores the distances
808 /// of the nodes calculated by the algorithm.
810 /// \pre Either \ref run() or \ref init() must be called before
811 /// using this function.
812 const DistMap &distMap() const { return *_dist;}
814 /// \brief Returns a const reference to the node map that stores the
815 /// predecessor arcs.
817 /// Returns a const reference to the node map that stores the predecessor
818 /// arcs, which form the shortest path tree (forest).
820 /// \pre Either \ref run() or \ref init() must be called before
821 /// using this function.
822 const PredMap &predMap() const { return *_pred; }
824 /// \brief Checks if a node is reached from the root(s).
826 /// Returns \c true if \c v is reached from the root(s).
828 /// \pre Either \ref run() or \ref init() must be called before
829 /// using this function.
830 bool reached(Node v) const {
831 return (*_dist)[v] != OperationTraits::infinity();
834 /// \brief Gives back a negative cycle.
836 /// This function gives back a directed cycle with negative total
837 /// length if the algorithm has already found one.
838 /// Otherwise it gives back an empty path.
839 lemon::Path<Digraph> negativeCycle() const {
840 typename Digraph::template NodeMap<int> state(*_gr, -1);
841 lemon::Path<Digraph> cycle;
842 for (int i = 0; i < int(_process.size()); ++i) {
843 if (state[_process[i]] != -1) continue;
844 for (Node v = _process[i]; (*_pred)[v] != INVALID;
845 v = _gr->source((*_pred)[v])) {
847 cycle.addFront((*_pred)[v]);
848 for (Node u = _gr->source((*_pred)[v]); u != v;
849 u = _gr->source((*_pred)[u])) {
850 cycle.addFront((*_pred)[u]);
854 else if (state[v] >= 0) {
866 /// \brief Default traits class of bellmanFord() function.
868 /// Default traits class of bellmanFord() function.
869 /// \tparam GR The type of the digraph.
870 /// \tparam LEN The type of the length map.
871 template <typename GR, typename LEN>
872 struct BellmanFordWizardDefaultTraits {
873 /// The type of the digraph the algorithm runs on.
876 /// \brief The type of the map that stores the arc lengths.
878 /// The type of the map that stores the arc lengths.
879 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
880 typedef LEN LengthMap;
882 /// The type of the arc lengths.
883 typedef typename LEN::Value Value;
885 /// \brief Operation traits for Bellman-Ford algorithm.
887 /// It defines the used operations and the infinity value for the
888 /// given \c Value type.
889 /// \see BellmanFordDefaultOperationTraits,
890 /// BellmanFordToleranceOperationTraits
891 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
893 /// \brief The type of the map that stores the last
894 /// arcs of the shortest paths.
896 /// The type of the map that stores the last arcs of the shortest paths.
897 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
898 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
900 /// \brief Instantiates a \c PredMap.
902 /// This function instantiates a \ref PredMap.
903 /// \param g is the digraph to which we would like to define the
905 static PredMap *createPredMap(const GR &g) {
906 return new PredMap(g);
909 /// \brief The type of the map that stores the distances of the nodes.
911 /// The type of the map that stores the distances of the nodes.
912 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
913 typedef typename GR::template NodeMap<Value> DistMap;
915 /// \brief Instantiates a \c DistMap.
917 /// This function instantiates a \ref DistMap.
918 /// \param g is the digraph to which we would like to define the
920 static DistMap *createDistMap(const GR &g) {
921 return new DistMap(g);
924 ///The type of the shortest paths.
926 ///The type of the shortest paths.
927 ///It must meet the \ref concepts::Path "Path" concept.
928 typedef lemon::Path<Digraph> Path;
931 /// \brief Default traits class used by BellmanFordWizard.
933 /// Default traits class used by BellmanFordWizard.
934 /// \tparam GR The type of the digraph.
935 /// \tparam LEN The type of the length map.
936 template <typename GR, typename LEN>
937 class BellmanFordWizardBase
938 : public BellmanFordWizardDefaultTraits<GR, LEN> {
940 typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
942 // Type of the nodes in the digraph.
943 typedef typename Base::Digraph::Node Node;
945 // Pointer to the underlying digraph.
947 // Pointer to the length map
949 // Pointer to the map of predecessors arcs.
951 // Pointer to the map of distances.
953 //Pointer to the shortest path to the target node.
955 //Pointer to the distance of the target node.
961 /// This constructor does not require parameters, it initiates
962 /// all of the attributes to default values \c 0.
963 BellmanFordWizardBase() :
964 _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
968 /// This constructor requires two parameters,
969 /// others are initiated to \c 0.
970 /// \param gr The digraph the algorithm runs on.
971 /// \param len The length map.
972 BellmanFordWizardBase(const GR& gr,
974 _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
975 _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
976 _pred(0), _dist(0), _path(0), _di(0) {}
980 /// \brief Auxiliary class for the function-type interface of the
981 /// \ref BellmanFord "Bellman-Ford" algorithm.
983 /// This auxiliary class is created to implement the
984 /// \ref bellmanFord() "function-type interface" of the
985 /// \ref BellmanFord "Bellman-Ford" algorithm.
986 /// It does not have own \ref run() method, it uses the
987 /// functions and features of the plain \ref BellmanFord.
989 /// This class should only be used through the \ref bellmanFord()
990 /// function, which makes it easier to use the algorithm.
992 /// \tparam TR The traits class that defines various types used by the
995 class BellmanFordWizard : public TR {
998 typedef typename TR::Digraph Digraph;
1000 typedef typename Digraph::Node Node;
1001 typedef typename Digraph::NodeIt NodeIt;
1002 typedef typename Digraph::Arc Arc;
1003 typedef typename Digraph::OutArcIt ArcIt;
1005 typedef typename TR::LengthMap LengthMap;
1006 typedef typename LengthMap::Value Value;
1007 typedef typename TR::PredMap PredMap;
1008 typedef typename TR::DistMap DistMap;
1009 typedef typename TR::Path Path;
1013 BellmanFordWizard() : TR() {}
1015 /// \brief Constructor that requires parameters.
1017 /// Constructor that requires parameters.
1018 /// These parameters will be the default values for the traits class.
1019 /// \param gr The digraph the algorithm runs on.
1020 /// \param len The length map.
1021 BellmanFordWizard(const Digraph& gr, const LengthMap& len)
1024 /// \brief Copy constructor
1025 BellmanFordWizard(const TR &b) : TR(b) {}
1027 ~BellmanFordWizard() {}
1029 /// \brief Runs the Bellman-Ford algorithm from the given source node.
1031 /// This method runs the Bellman-Ford algorithm from the given source
1032 /// node in order to compute the shortest path to each node.
1034 BellmanFord<Digraph,LengthMap,TR>
1035 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1036 *reinterpret_cast<const LengthMap*>(Base::_length));
1037 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1038 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1042 /// \brief Runs the Bellman-Ford algorithm to find the shortest path
1043 /// between \c s and \c t.
1045 /// This method runs the Bellman-Ford algorithm from node \c s
1046 /// in order to compute the shortest path to node \c t.
1047 /// Actually, it computes the shortest path to each node, but using
1048 /// this function you can retrieve the distance and the shortest path
1049 /// for a single target node easier.
1051 /// \return \c true if \c t is reachable form \c s.
1052 bool run(Node s, Node t) {
1053 BellmanFord<Digraph,LengthMap,TR>
1054 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1055 *reinterpret_cast<const LengthMap*>(Base::_length));
1056 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1057 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1059 if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1060 if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1061 return bf.reached(t);
1065 struct SetPredMapBase : public Base {
1067 static PredMap *createPredMap(const Digraph &) { return 0; };
1068 SetPredMapBase(const TR &b) : TR(b) {}
1071 /// \brief \ref named-templ-param "Named parameter" for setting
1072 /// the predecessor map.
1074 /// \ref named-templ-param "Named parameter" for setting
1075 /// the map that stores the predecessor arcs of the nodes.
1077 BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1078 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1079 return BellmanFordWizard<SetPredMapBase<T> >(*this);
1083 struct SetDistMapBase : public Base {
1085 static DistMap *createDistMap(const Digraph &) { return 0; };
1086 SetDistMapBase(const TR &b) : TR(b) {}
1089 /// \brief \ref named-templ-param "Named parameter" for setting
1090 /// the distance map.
1092 /// \ref named-templ-param "Named parameter" for setting
1093 /// the map that stores the distances of the nodes calculated
1094 /// by the algorithm.
1096 BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1097 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1098 return BellmanFordWizard<SetDistMapBase<T> >(*this);
1102 struct SetPathBase : public Base {
1104 SetPathBase(const TR &b) : TR(b) {}
1107 /// \brief \ref named-func-param "Named parameter" for getting
1108 /// the shortest path to the target node.
1110 /// \ref named-func-param "Named parameter" for getting
1111 /// the shortest path to the target node.
1113 BellmanFordWizard<SetPathBase<T> > path(const T &t)
1115 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1116 return BellmanFordWizard<SetPathBase<T> >(*this);
1119 /// \brief \ref named-func-param "Named parameter" for getting
1120 /// the distance of the target node.
1122 /// \ref named-func-param "Named parameter" for getting
1123 /// the distance of the target node.
1124 BellmanFordWizard dist(const Value &d)
1126 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1132 /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1135 /// \ingroup shortest_path
1136 /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1139 /// This function also has several \ref named-templ-func-param
1140 /// "named parameters", they are declared as the members of class
1141 /// \ref BellmanFordWizard.
1142 /// The following examples show how to use these parameters.
1144 /// // Compute shortest path from node s to each node
1145 /// bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1147 /// // Compute shortest path from s to t
1148 /// bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1150 /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1151 /// to the end of the parameter list.
1152 /// \sa BellmanFordWizard
1154 template<typename GR, typename LEN>
1155 BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1156 bellmanFord(const GR& digraph,
1159 return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1162 } //END OF NAMESPACE LEMON