3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
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/path.h>
37 /// \brief Default OperationTraits for the BellmanFord algorithm class.
39 /// This operation traits class defines all computational operations
40 /// and constants that are used in the Bellman-Ford algorithm.
41 /// The default implementation is based on the \c numeric_limits class.
42 /// If the numeric type does not have infinity value, then the maximum
43 /// value is used as extremal infinity value.
46 bool has_inf = std::numeric_limits<V>::has_infinity>
47 struct BellmanFordDefaultOperationTraits {
50 /// \brief Gives back the zero value of the type.
52 return static_cast<Value>(0);
54 /// \brief Gives back the positive infinity value of the type.
55 static Value infinity() {
56 return std::numeric_limits<Value>::infinity();
58 /// \brief Gives back the sum of the given two elements.
59 static Value plus(const Value& left, const Value& right) {
62 /// \brief Gives back \c true only if the first value is less than
64 static bool less(const Value& left, const Value& right) {
70 struct BellmanFordDefaultOperationTraits<V, false> {
73 return static_cast<Value>(0);
75 static Value infinity() {
76 return std::numeric_limits<Value>::max();
78 static Value plus(const Value& left, const Value& right) {
79 if (left == infinity() || right == infinity()) return infinity();
82 static bool less(const Value& left, const Value& right) {
87 /// \brief Default traits class of BellmanFord class.
89 /// Default traits class of BellmanFord class.
90 /// \param GR The type of the digraph.
91 /// \param LEN The type of the length map.
92 template<typename GR, typename LEN>
93 struct BellmanFordDefaultTraits {
94 /// The type of the digraph the algorithm runs on.
97 /// \brief The type of the map that stores the arc lengths.
99 /// The type of the map that stores the arc lengths.
100 /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
101 typedef LEN LengthMap;
103 /// The type of the arc lengths.
104 typedef typename LEN::Value Value;
106 /// \brief Operation traits for Bellman-Ford algorithm.
108 /// It defines the used operations and the infinity value for the
109 /// given \c Value type.
110 /// \see BellmanFordDefaultOperationTraits
111 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
113 /// \brief The type of the map that stores the last arcs of the
116 /// The type of the map that stores the last
117 /// arcs of the shortest paths.
118 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
119 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
121 /// \brief Instantiates a \c PredMap.
123 /// This function instantiates a \ref PredMap.
124 /// \param g is the digraph to which we would like to define the
126 static PredMap *createPredMap(const GR& g) {
127 return new PredMap(g);
130 /// \brief The type of the map that stores the distances of the nodes.
132 /// The type of the map that stores the distances of the nodes.
133 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
134 typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
136 /// \brief Instantiates a \c DistMap.
138 /// This function instantiates a \ref DistMap.
139 /// \param g is the digraph to which we would like to define the
141 static DistMap *createDistMap(const GR& g) {
142 return new DistMap(g);
147 /// \brief %BellmanFord algorithm class.
149 /// \ingroup shortest_path
150 /// This class provides an efficient implementation of the Bellman-Ford
151 /// algorithm. The maximum time complexity of the algorithm is
154 /// The Bellman-Ford algorithm solves the single-source shortest path
155 /// problem when the arcs can have negative lengths, but the digraph
156 /// should not contain directed cycles with negative total length.
157 /// If all arc costs are non-negative, consider to use the Dijkstra
158 /// algorithm instead, since it is more efficient.
160 /// The arc lengths are passed to the algorithm using a
161 /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
162 /// kind of length. The type of the length values is determined by the
163 /// \ref concepts::ReadMap::Value "Value" type of the length map.
165 /// There is also a \ref bellmanFord() "function-type interface" for the
166 /// Bellman-Ford algorithm, which is convenient in the simplier cases and
167 /// it can be used easier.
169 /// \tparam GR The type of the digraph the algorithm runs on.
170 /// The default type is \ref ListDigraph.
171 /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
172 /// the lengths of the arcs. The default map type is
173 /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
175 template <typename GR, typename LEN, typename TR>
177 template <typename GR=ListDigraph,
178 typename LEN=typename GR::template ArcMap<int>,
179 typename TR=BellmanFordDefaultTraits<GR,LEN> >
184 ///The type of the underlying digraph.
185 typedef typename TR::Digraph Digraph;
187 /// \brief The type of the arc lengths.
188 typedef typename TR::LengthMap::Value Value;
189 /// \brief The type of the map that stores the arc lengths.
190 typedef typename TR::LengthMap LengthMap;
191 /// \brief The type of the map that stores the last
192 /// arcs of the shortest paths.
193 typedef typename TR::PredMap PredMap;
194 /// \brief The type of the map that stores the distances of the nodes.
195 typedef typename TR::DistMap DistMap;
196 /// The type of the paths.
197 typedef PredMapPath<Digraph, PredMap> Path;
198 ///\brief The \ref BellmanFordDefaultOperationTraits
199 /// "operation traits class" of the algorithm.
200 typedef typename TR::OperationTraits OperationTraits;
202 ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
207 typedef typename Digraph::Node Node;
208 typedef typename Digraph::NodeIt NodeIt;
209 typedef typename Digraph::Arc Arc;
210 typedef typename Digraph::OutArcIt OutArcIt;
212 // Pointer to the underlying digraph.
214 // Pointer to the length map
215 const LengthMap *_length;
216 // Pointer to the map of predecessors arcs.
218 // Indicates if _pred is locally allocated (true) or not.
220 // Pointer to the map of distances.
222 // Indicates if _dist is locally allocated (true) or not.
225 typedef typename Digraph::template NodeMap<bool> MaskMap;
228 std::vector<Node> _process;
230 // Creates the maps if necessary.
234 _pred = Traits::createPredMap(*_gr);
238 _dist = Traits::createDistMap(*_gr);
241 _mask = new MaskMap(*_gr);
247 typedef BellmanFord Create;
249 /// \name Named Template Parameters
254 struct SetPredMapTraits : public Traits {
256 static PredMap *createPredMap(const Digraph&) {
257 LEMON_ASSERT(false, "PredMap is not initialized");
258 return 0; // ignore warnings
262 /// \brief \ref named-templ-param "Named parameter" for setting
265 /// \ref named-templ-param "Named parameter" for setting
267 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
270 : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
271 typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
275 struct SetDistMapTraits : public Traits {
277 static DistMap *createDistMap(const Digraph&) {
278 LEMON_ASSERT(false, "DistMap is not initialized");
279 return 0; // ignore warnings
283 /// \brief \ref named-templ-param "Named parameter" for setting
286 /// \ref named-templ-param "Named parameter" for setting
288 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
291 : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
292 typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
296 struct SetOperationTraitsTraits : public Traits {
297 typedef T OperationTraits;
300 /// \brief \ref named-templ-param "Named parameter" for setting
301 /// \c OperationTraits type.
303 /// \ref named-templ-param "Named parameter" for setting
304 /// \c OperationTraits type.
305 /// For more information, see \ref BellmanFordDefaultOperationTraits.
307 struct SetOperationTraits
308 : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
309 typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
321 /// \brief Constructor.
324 /// \param g The digraph the algorithm runs on.
325 /// \param length The length map used by the algorithm.
326 BellmanFord(const Digraph& g, const LengthMap& length) :
327 _gr(&g), _length(&length),
328 _pred(0), _local_pred(false),
329 _dist(0), _local_dist(false), _mask(0) {}
333 if(_local_pred) delete _pred;
334 if(_local_dist) delete _dist;
335 if(_mask) delete _mask;
338 /// \brief Sets the length map.
340 /// Sets the length map.
341 /// \return <tt>(*this)</tt>
342 BellmanFord &lengthMap(const LengthMap &map) {
347 /// \brief Sets the map that stores the predecessor arcs.
349 /// Sets the map that stores the predecessor arcs.
350 /// If you don't use this function before calling \ref run()
351 /// or \ref init(), an instance will be allocated automatically.
352 /// The destructor deallocates this automatically allocated map,
354 /// \return <tt>(*this)</tt>
355 BellmanFord &predMap(PredMap &map) {
364 /// \brief Sets the map that stores the distances of the nodes.
366 /// Sets the map that stores the distances of the nodes calculated
367 /// by the algorithm.
368 /// If you don't use this function before calling \ref run()
369 /// or \ref init(), an instance will be allocated automatically.
370 /// The destructor deallocates this automatically allocated map,
372 /// \return <tt>(*this)</tt>
373 BellmanFord &distMap(DistMap &map) {
382 /// \name Execution Control
383 /// The simplest way to execute the Bellman-Ford algorithm is to use
384 /// one of the member functions called \ref run().\n
385 /// If you need better control on the execution, you have to call
386 /// \ref init() first, then you can add several source nodes
387 /// with \ref addSource(). Finally the actual path computation can be
388 /// performed with \ref start(), \ref checkedStart() or
389 /// \ref limitedStart().
393 /// \brief Initializes the internal data structures.
395 /// Initializes the internal data structures. The optional parameter
396 /// is the initial distance of each node.
397 void init(const Value value = OperationTraits::infinity()) {
399 for (NodeIt it(*_gr); it != INVALID; ++it) {
400 _pred->set(it, INVALID);
401 _dist->set(it, value);
404 if (OperationTraits::less(value, OperationTraits::infinity())) {
405 for (NodeIt it(*_gr); it != INVALID; ++it) {
406 _process.push_back(it);
407 _mask->set(it, true);
410 for (NodeIt it(*_gr); it != INVALID; ++it) {
411 _mask->set(it, false);
416 /// \brief Adds a new source node.
418 /// This function adds a new source node. The optional second parameter
419 /// is the initial distance of the node.
420 void addSource(Node source, Value dst = OperationTraits::zero()) {
421 _dist->set(source, dst);
422 if (!(*_mask)[source]) {
423 _process.push_back(source);
424 _mask->set(source, true);
428 /// \brief Executes one round from the Bellman-Ford algorithm.
430 /// If the algoritm calculated the distances in the previous round
431 /// exactly for the paths of at most \c k arcs, then this function
432 /// will calculate the distances exactly for the paths of at most
433 /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
434 /// calculates the shortest path distances exactly for the paths
435 /// consisting of at most \c k arcs.
437 /// \warning The paths with limited arc number cannot be retrieved
438 /// easily with \ref path() or \ref predArc() functions. If you also
439 /// need the shortest paths and not only the distances, you should
440 /// store the \ref predMap() "predecessor map" after each iteration
441 /// and build the path manually.
443 /// \return \c true when the algorithm have not found more shorter
447 bool processNextRound() {
448 for (int i = 0; i < int(_process.size()); ++i) {
449 _mask->set(_process[i], false);
451 std::vector<Node> nextProcess;
452 std::vector<Value> values(_process.size());
453 for (int i = 0; i < int(_process.size()); ++i) {
454 values[i] = (*_dist)[_process[i]];
456 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);
470 _process.swap(nextProcess);
471 return _process.empty();
474 /// \brief Executes one weak round from the Bellman-Ford algorithm.
476 /// If the algorithm calculated the distances in the previous round
477 /// at least for the paths of at most \c k arcs, then this function
478 /// will calculate the distances at least for the paths of at most
479 /// <tt>k+1</tt> arcs.
480 /// This function does not make it possible to calculate the shortest
481 /// path distances exactly for paths consisting of at most \c k arcs,
482 /// this is why it is called weak round.
484 /// \return \c true when the algorithm have not found more shorter
488 bool processNextWeakRound() {
489 for (int i = 0; i < int(_process.size()); ++i) {
490 _mask->set(_process[i], false);
492 std::vector<Node> nextProcess;
493 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);
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);
508 _process.swap(nextProcess);
509 return _process.empty();
512 /// \brief Executes the algorithm.
514 /// Executes the algorithm.
516 /// This method runs the Bellman-Ford algorithm from the root node(s)
517 /// in order to compute the shortest path to each node.
519 /// The algorithm computes
520 /// - the shortest path tree (forest),
521 /// - the distance of each node from the root(s).
523 /// \pre init() must be called and at least one root node should be
524 /// added with addSource() before using this function.
526 int num = countNodes(*_gr) - 1;
527 for (int i = 0; i < num; ++i) {
528 if (processNextWeakRound()) break;
532 /// \brief Executes the algorithm and checks the negative cycles.
534 /// Executes the algorithm and checks the negative cycles.
536 /// This method runs the Bellman-Ford algorithm from the root node(s)
537 /// in order to compute the shortest path to each node and also checks
538 /// if the digraph contains cycles with negative total length.
540 /// The algorithm computes
541 /// - the shortest path tree (forest),
542 /// - the distance of each node from the root(s).
544 /// \return \c false if there is a negative cycle in the digraph.
546 /// \pre init() must be called and at least one root node should be
547 /// added with addSource() before using this function.
548 bool checkedStart() {
549 int num = countNodes(*_gr);
550 for (int i = 0; i < num; ++i) {
551 if (processNextWeakRound()) return true;
553 return _process.empty();
556 /// \brief Executes the algorithm with arc number limit.
558 /// Executes the algorithm with arc number limit.
560 /// This method runs the Bellman-Ford algorithm from the root node(s)
561 /// in order to compute the shortest path distance for each node
562 /// using only the paths consisting of at most \c num arcs.
564 /// The algorithm computes
565 /// - the limited distance of each node from the root(s),
566 /// - the predecessor arc for each node.
568 /// \warning The paths with limited arc number cannot be retrieved
569 /// easily with \ref path() or \ref predArc() functions. If you also
570 /// need the shortest paths and not only the distances, you should
571 /// store the \ref predMap() "predecessor map" after each iteration
572 /// and build the path manually.
574 /// \pre init() must be called and at least one root node should be
575 /// added with addSource() before using this function.
576 void limitedStart(int num) {
577 for (int i = 0; i < num; ++i) {
578 if (processNextRound()) break;
582 /// \brief Runs the algorithm from the given root node.
584 /// This method runs the Bellman-Ford algorithm from the given root
585 /// node \c s in order to compute the shortest path to each node.
587 /// The algorithm computes
588 /// - the shortest path tree (forest),
589 /// - the distance of each node from the root(s).
591 /// \note bf.run(s) is just a shortcut of the following code.
603 /// \brief Runs the algorithm from the given root node with arc
606 /// This method runs the Bellman-Ford algorithm from the given root
607 /// node \c s in order to compute the shortest path distance for each
608 /// node using only the paths consisting of at most \c num arcs.
610 /// The algorithm computes
611 /// - the limited distance of each node from the root(s),
612 /// - the predecessor arc for each node.
614 /// \warning The paths with limited arc number cannot be retrieved
615 /// easily with \ref path() or \ref predArc() functions. If you also
616 /// need the shortest paths and not only the distances, you should
617 /// store the \ref predMap() "predecessor map" after each iteration
618 /// and build the path manually.
620 /// \note bf.run(s, num) is just a shortcut of the following code.
624 /// bf.limitedStart(num);
626 void run(Node s, int num) {
634 /// \brief LEMON iterator for getting the active nodes.
636 /// This class provides a common style LEMON iterator that traverses
637 /// the active nodes of the Bellman-Ford algorithm after the last
638 /// phase. These nodes should be checked in the next phase to
639 /// find augmenting arcs outgoing from them.
643 /// \brief Constructor.
645 /// Constructor for getting the active nodes of the given BellmanFord
647 ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
649 _index = _algorithm->_process.size() - 1;
652 /// \brief Invalid constructor.
654 /// Invalid constructor.
655 ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
657 /// \brief Conversion to \c Node.
659 /// Conversion to \c Node.
660 operator Node() const {
661 return _index >= 0 ? _algorithm->_process[_index] : INVALID;
664 /// \brief Increment operator.
666 /// Increment operator.
667 ActiveIt& operator++() {
672 bool operator==(const ActiveIt& it) const {
673 return static_cast<Node>(*this) == static_cast<Node>(it);
675 bool operator!=(const ActiveIt& it) const {
676 return static_cast<Node>(*this) != static_cast<Node>(it);
678 bool operator<(const ActiveIt& it) const {
679 return static_cast<Node>(*this) < static_cast<Node>(it);
683 const BellmanFord* _algorithm;
687 /// \name Query Functions
688 /// The result of the Bellman-Ford algorithm can be obtained using these
690 /// Either \ref run() or \ref init() should be called before using them.
694 /// \brief The shortest path to the given node.
696 /// Gives back the shortest path to the given node from the root(s).
698 /// \warning \c t should be reached from the root(s).
700 /// \pre Either \ref run() or \ref init() must be called before
701 /// using this function.
702 Path path(Node t) const
704 return Path(*_gr, *_pred, t);
707 /// \brief The distance of the given node from the root(s).
709 /// Returns the distance of the given node from the root(s).
711 /// \warning If node \c v is not reached from the root(s), then
712 /// the return value of this function is undefined.
714 /// \pre Either \ref run() or \ref init() must be called before
715 /// using this function.
716 Value dist(Node v) const { return (*_dist)[v]; }
718 /// \brief Returns the 'previous arc' of the shortest path tree for
721 /// This function returns the 'previous arc' of the shortest path
722 /// tree for node \c v, i.e. it returns the last arc of a
723 /// shortest path from a root to \c v. It is \c INVALID if \c v
724 /// is not reached from the root(s) or if \c v is a root.
726 /// The shortest path tree used here is equal to the shortest path
727 /// tree used in \ref predNode() and \ref predMap().
729 /// \pre Either \ref run() or \ref init() must be called before
730 /// using this function.
731 Arc predArc(Node v) const { return (*_pred)[v]; }
733 /// \brief Returns the 'previous node' of the shortest path tree for
736 /// This function returns the 'previous node' of the shortest path
737 /// tree for node \c v, i.e. it returns the last but one node of
738 /// a shortest path from a root to \c v. It is \c INVALID if \c v
739 /// is not reached from the root(s) or if \c v is a root.
741 /// The shortest path tree used here is equal to the shortest path
742 /// tree used in \ref predArc() and \ref predMap().
744 /// \pre Either \ref run() or \ref init() must be called before
745 /// using this function.
746 Node predNode(Node v) const {
747 return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
750 /// \brief Returns a const reference to the node map that stores the
751 /// distances of the nodes.
753 /// Returns a const reference to the node map that stores the distances
754 /// of the nodes calculated by the algorithm.
756 /// \pre Either \ref run() or \ref init() must be called before
757 /// using this function.
758 const DistMap &distMap() const { return *_dist;}
760 /// \brief Returns a const reference to the node map that stores the
761 /// predecessor arcs.
763 /// Returns a const reference to the node map that stores the predecessor
764 /// arcs, which form the shortest path tree (forest).
766 /// \pre Either \ref run() or \ref init() must be called before
767 /// using this function.
768 const PredMap &predMap() const { return *_pred; }
770 /// \brief Checks if a node is reached from the root(s).
772 /// Returns \c true if \c v is reached from the root(s).
774 /// \pre Either \ref run() or \ref init() must be called before
775 /// using this function.
776 bool reached(Node v) const {
777 return (*_dist)[v] != OperationTraits::infinity();
780 /// \brief Gives back a negative cycle.
782 /// This function gives back a directed cycle with negative total
783 /// length if the algorithm has already found one.
784 /// Otherwise it gives back an empty path.
785 lemon::Path<Digraph> negativeCycle() const {
786 typename Digraph::template NodeMap<int> state(*_gr, -1);
787 lemon::Path<Digraph> cycle;
788 for (int i = 0; i < int(_process.size()); ++i) {
789 if (state[_process[i]] != -1) continue;
790 for (Node v = _process[i]; (*_pred)[v] != INVALID;
791 v = _gr->source((*_pred)[v])) {
793 cycle.addFront((*_pred)[v]);
794 for (Node u = _gr->source((*_pred)[v]); u != v;
795 u = _gr->source((*_pred)[u])) {
796 cycle.addFront((*_pred)[u]);
800 else if (state[v] >= 0) {
812 /// \brief Default traits class of bellmanFord() function.
814 /// Default traits class of bellmanFord() function.
815 /// \tparam GR The type of the digraph.
816 /// \tparam LEN The type of the length map.
817 template <typename GR, typename LEN>
818 struct BellmanFordWizardDefaultTraits {
819 /// The type of the digraph the algorithm runs on.
822 /// \brief The type of the map that stores the arc lengths.
824 /// The type of the map that stores the arc lengths.
825 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
826 typedef LEN LengthMap;
828 /// The type of the arc lengths.
829 typedef typename LEN::Value Value;
831 /// \brief Operation traits for Bellman-Ford algorithm.
833 /// It defines the used operations and the infinity value for the
834 /// given \c Value type.
835 /// \see BellmanFordDefaultOperationTraits
836 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
838 /// \brief The type of the map that stores the last
839 /// arcs of the shortest paths.
841 /// The type of the map that stores the last arcs of the shortest paths.
842 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
843 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
845 /// \brief Instantiates a \c PredMap.
847 /// This function instantiates a \ref PredMap.
848 /// \param g is the digraph to which we would like to define the
850 static PredMap *createPredMap(const GR &g) {
851 return new PredMap(g);
854 /// \brief The type of the map that stores the distances of the nodes.
856 /// The type of the map that stores the distances of the nodes.
857 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
858 typedef typename GR::template NodeMap<Value> DistMap;
860 /// \brief Instantiates a \c DistMap.
862 /// This function instantiates a \ref DistMap.
863 /// \param g is the digraph to which we would like to define the
865 static DistMap *createDistMap(const GR &g) {
866 return new DistMap(g);
869 ///The type of the shortest paths.
871 ///The type of the shortest paths.
872 ///It must meet the \ref concepts::Path "Path" concept.
873 typedef lemon::Path<Digraph> Path;
876 /// \brief Default traits class used by BellmanFordWizard.
878 /// Default traits class used by BellmanFordWizard.
879 /// \tparam GR The type of the digraph.
880 /// \tparam LEN The type of the length map.
881 template <typename GR, typename LEN>
882 class BellmanFordWizardBase
883 : public BellmanFordWizardDefaultTraits<GR, LEN> {
885 typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
887 // Type of the nodes in the digraph.
888 typedef typename Base::Digraph::Node Node;
890 // Pointer to the underlying digraph.
892 // Pointer to the length map
894 // Pointer to the map of predecessors arcs.
896 // Pointer to the map of distances.
898 //Pointer to the shortest path to the target node.
900 //Pointer to the distance of the target node.
906 /// This constructor does not require parameters, it initiates
907 /// all of the attributes to default values \c 0.
908 BellmanFordWizardBase() :
909 _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
913 /// This constructor requires two parameters,
914 /// others are initiated to \c 0.
915 /// \param gr The digraph the algorithm runs on.
916 /// \param len The length map.
917 BellmanFordWizardBase(const GR& gr,
919 _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
920 _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
921 _pred(0), _dist(0), _path(0), _di(0) {}
925 /// \brief Auxiliary class for the function-type interface of the
926 /// \ref BellmanFord "Bellman-Ford" algorithm.
928 /// This auxiliary class is created to implement the
929 /// \ref bellmanFord() "function-type interface" of the
930 /// \ref BellmanFord "Bellman-Ford" algorithm.
931 /// It does not have own \ref run() method, it uses the
932 /// functions and features of the plain \ref BellmanFord.
934 /// This class should only be used through the \ref bellmanFord()
935 /// function, which makes it easier to use the algorithm.
937 class BellmanFordWizard : public TR {
940 typedef typename TR::Digraph Digraph;
942 typedef typename Digraph::Node Node;
943 typedef typename Digraph::NodeIt NodeIt;
944 typedef typename Digraph::Arc Arc;
945 typedef typename Digraph::OutArcIt ArcIt;
947 typedef typename TR::LengthMap LengthMap;
948 typedef typename LengthMap::Value Value;
949 typedef typename TR::PredMap PredMap;
950 typedef typename TR::DistMap DistMap;
951 typedef typename TR::Path Path;
955 BellmanFordWizard() : TR() {}
957 /// \brief Constructor that requires parameters.
959 /// Constructor that requires parameters.
960 /// These parameters will be the default values for the traits class.
961 /// \param gr The digraph the algorithm runs on.
962 /// \param len The length map.
963 BellmanFordWizard(const Digraph& gr, const LengthMap& len)
966 /// \brief Copy constructor
967 BellmanFordWizard(const TR &b) : TR(b) {}
969 ~BellmanFordWizard() {}
971 /// \brief Runs the Bellman-Ford algorithm from the given source node.
973 /// This method runs the Bellman-Ford algorithm from the given source
974 /// node in order to compute the shortest path to each node.
976 BellmanFord<Digraph,LengthMap,TR>
977 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
978 *reinterpret_cast<const LengthMap*>(Base::_length));
979 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
980 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
984 /// \brief Runs the Bellman-Ford algorithm to find the shortest path
985 /// between \c s and \c t.
987 /// This method runs the Bellman-Ford algorithm from node \c s
988 /// in order to compute the shortest path to node \c t.
989 /// Actually, it computes the shortest path to each node, but using
990 /// this function you can retrieve the distance and the shortest path
991 /// for a single target node easier.
993 /// \return \c true if \c t is reachable form \c s.
994 bool run(Node s, Node t) {
995 BellmanFord<Digraph,LengthMap,TR>
996 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
997 *reinterpret_cast<const LengthMap*>(Base::_length));
998 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
999 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1001 if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1002 if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1003 return bf.reached(t);
1007 struct SetPredMapBase : public Base {
1009 static PredMap *createPredMap(const Digraph &) { return 0; };
1010 SetPredMapBase(const TR &b) : TR(b) {}
1013 /// \brief \ref named-templ-param "Named parameter" for setting
1014 /// the predecessor map.
1016 /// \ref named-templ-param "Named parameter" for setting
1017 /// the map that stores the predecessor arcs of the nodes.
1019 BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1020 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1021 return BellmanFordWizard<SetPredMapBase<T> >(*this);
1025 struct SetDistMapBase : public Base {
1027 static DistMap *createDistMap(const Digraph &) { return 0; };
1028 SetDistMapBase(const TR &b) : TR(b) {}
1031 /// \brief \ref named-templ-param "Named parameter" for setting
1032 /// the distance map.
1034 /// \ref named-templ-param "Named parameter" for setting
1035 /// the map that stores the distances of the nodes calculated
1036 /// by the algorithm.
1038 BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1039 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1040 return BellmanFordWizard<SetDistMapBase<T> >(*this);
1044 struct SetPathBase : public Base {
1046 SetPathBase(const TR &b) : TR(b) {}
1049 /// \brief \ref named-func-param "Named parameter" for getting
1050 /// the shortest path to the target node.
1052 /// \ref named-func-param "Named parameter" for getting
1053 /// the shortest path to the target node.
1055 BellmanFordWizard<SetPathBase<T> > path(const T &t)
1057 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1058 return BellmanFordWizard<SetPathBase<T> >(*this);
1061 /// \brief \ref named-func-param "Named parameter" for getting
1062 /// the distance of the target node.
1064 /// \ref named-func-param "Named parameter" for getting
1065 /// the distance of the target node.
1066 BellmanFordWizard dist(const Value &d)
1068 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1074 /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1077 /// \ingroup shortest_path
1078 /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1081 /// This function also has several \ref named-templ-func-param
1082 /// "named parameters", they are declared as the members of class
1083 /// \ref BellmanFordWizard.
1084 /// The following examples show how to use these parameters.
1086 /// // Compute shortest path from node s to each node
1087 /// bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1089 /// // Compute shortest path from s to t
1090 /// bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1092 /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1093 /// to the end of the parameter list.
1094 /// \sa BellmanFordWizard
1096 template<typename GR, typename LEN>
1097 BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1098 bellmanFord(const GR& digraph,
1101 return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1104 } //END OF NAMESPACE LEMON