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/bits/path_dump.h>
27 #include <lemon/core.h>
28 #include <lemon/error.h>
29 #include <lemon/maps.h>
30 #include <lemon/path.h>
36 /// \brief Default OperationTraits for the BellmanFord algorithm class.
38 /// This operation traits class defines all computational operations
39 /// and constants that are used in the Bellman-Ford algorithm.
40 /// The default implementation is based on the \c numeric_limits class.
41 /// If the numeric type does not have infinity value, then the maximum
42 /// value is used as extremal infinity value.
45 bool has_inf = std::numeric_limits<V>::has_infinity>
46 struct BellmanFordDefaultOperationTraits {
49 /// \brief Gives back the zero value of the type.
51 return static_cast<Value>(0);
53 /// \brief Gives back the positive infinity value of the type.
54 static Value infinity() {
55 return std::numeric_limits<Value>::infinity();
57 /// \brief Gives back the sum of the given two elements.
58 static Value plus(const Value& left, const Value& right) {
61 /// \brief Gives back \c true only if the first value is less than
63 static bool less(const Value& left, const Value& right) {
69 struct BellmanFordDefaultOperationTraits<V, false> {
72 return static_cast<Value>(0);
74 static Value infinity() {
75 return std::numeric_limits<Value>::max();
77 static Value plus(const Value& left, const Value& right) {
78 if (left == infinity() || right == infinity()) return infinity();
81 static bool less(const Value& left, const Value& right) {
86 /// \brief Default traits class of BellmanFord class.
88 /// Default traits class of BellmanFord class.
89 /// \param GR The type of the digraph.
90 /// \param LEN The type of the length map.
91 template<typename GR, typename LEN>
92 struct BellmanFordDefaultTraits {
93 /// The type of the digraph the algorithm runs on.
96 /// \brief The type of the map that stores the arc lengths.
98 /// The type of the map that stores the arc lengths.
99 /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
100 typedef LEN LengthMap;
102 /// The type of the arc lengths.
103 typedef typename LEN::Value Value;
105 /// \brief Operation traits for Bellman-Ford algorithm.
107 /// It defines the used operations and the infinity value for the
108 /// given \c Value type.
109 /// \see BellmanFordDefaultOperationTraits
110 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
112 /// \brief The type of the map that stores the last arcs of the
115 /// The type of the map that stores the last
116 /// arcs of the shortest paths.
117 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
118 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
120 /// \brief Instantiates a \c PredMap.
122 /// This function instantiates a \ref PredMap.
123 /// \param g is the digraph to which we would like to define the
125 static PredMap *createPredMap(const GR& g) {
126 return new PredMap(g);
129 /// \brief The type of the map that stores the distances of the nodes.
131 /// The type of the map that stores the distances of the nodes.
132 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
133 typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
135 /// \brief Instantiates a \c DistMap.
137 /// This function instantiates a \ref DistMap.
138 /// \param g is the digraph to which we would like to define the
140 static DistMap *createDistMap(const GR& g) {
141 return new DistMap(g);
146 /// \brief %BellmanFord algorithm class.
148 /// \ingroup shortest_path
149 /// This class provides an efficient implementation of the Bellman-Ford
150 /// algorithm. The maximum time complexity of the algorithm is
153 /// The Bellman-Ford algorithm solves the single-source shortest path
154 /// problem when the arcs can have negative lengths, but the digraph
155 /// should not contain directed cycles with negative total length.
156 /// If all arc costs are non-negative, consider to use the Dijkstra
157 /// algorithm instead, since it is more efficient.
159 /// The arc lengths are passed to the algorithm using a
160 /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
161 /// kind of length. The type of the length values is determined by the
162 /// \ref concepts::ReadMap::Value "Value" type of the length map.
164 /// There is also a \ref bellmanFord() "function-type interface" for the
165 /// Bellman-Ford algorithm, which is convenient in the simplier cases and
166 /// it can be used easier.
168 /// \tparam GR The type of the digraph the algorithm runs on.
169 /// The default type is \ref ListDigraph.
170 /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
171 /// the lengths of the arcs. The default map type is
172 /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
174 template <typename GR, typename LEN, typename TR>
176 template <typename GR=ListDigraph,
177 typename LEN=typename GR::template ArcMap<int>,
178 typename TR=BellmanFordDefaultTraits<GR,LEN> >
183 ///The type of the underlying digraph.
184 typedef typename TR::Digraph Digraph;
186 /// \brief The type of the arc lengths.
187 typedef typename TR::LengthMap::Value Value;
188 /// \brief The type of the map that stores the arc lengths.
189 typedef typename TR::LengthMap LengthMap;
190 /// \brief The type of the map that stores the last
191 /// arcs of the shortest paths.
192 typedef typename TR::PredMap PredMap;
193 /// \brief The type of the map that stores the distances of the nodes.
194 typedef typename TR::DistMap DistMap;
195 /// The type of the paths.
196 typedef PredMapPath<Digraph, PredMap> Path;
197 ///\brief The \ref BellmanFordDefaultOperationTraits
198 /// "operation traits class" of the algorithm.
199 typedef typename TR::OperationTraits OperationTraits;
201 ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
206 typedef typename Digraph::Node Node;
207 typedef typename Digraph::NodeIt NodeIt;
208 typedef typename Digraph::Arc Arc;
209 typedef typename Digraph::OutArcIt OutArcIt;
211 // Pointer to the underlying digraph.
213 // Pointer to the length map
214 const LengthMap *_length;
215 // Pointer to the map of predecessors arcs.
217 // Indicates if _pred is locally allocated (true) or not.
219 // Pointer to the map of distances.
221 // Indicates if _dist is locally allocated (true) or not.
224 typedef typename Digraph::template NodeMap<bool> MaskMap;
227 std::vector<Node> _process;
229 // Creates the maps if necessary.
233 _pred = Traits::createPredMap(*_gr);
237 _dist = Traits::createDistMap(*_gr);
239 _mask = new MaskMap(*_gr, false);
244 typedef BellmanFord Create;
246 /// \name Named Template Parameters
251 struct SetPredMapTraits : public Traits {
253 static PredMap *createPredMap(const Digraph&) {
254 LEMON_ASSERT(false, "PredMap is not initialized");
255 return 0; // ignore warnings
259 /// \brief \ref named-templ-param "Named parameter" for setting
262 /// \ref named-templ-param "Named parameter" for setting
264 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
267 : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
268 typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
272 struct SetDistMapTraits : public Traits {
274 static DistMap *createDistMap(const Digraph&) {
275 LEMON_ASSERT(false, "DistMap is not initialized");
276 return 0; // ignore warnings
280 /// \brief \ref named-templ-param "Named parameter" for setting
283 /// \ref named-templ-param "Named parameter" for setting
285 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
288 : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
289 typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
293 struct SetOperationTraitsTraits : public Traits {
294 typedef T OperationTraits;
297 /// \brief \ref named-templ-param "Named parameter" for setting
298 /// \c OperationTraits type.
300 /// \ref named-templ-param "Named parameter" for setting
301 /// \c OperationTraits type.
302 /// For more information see \ref BellmanFordDefaultOperationTraits.
304 struct SetOperationTraits
305 : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
306 typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
318 /// \brief Constructor.
321 /// \param g The digraph the algorithm runs on.
322 /// \param length The length map used by the algorithm.
323 BellmanFord(const Digraph& g, const LengthMap& length) :
324 _gr(&g), _length(&length),
325 _pred(0), _local_pred(false),
326 _dist(0), _local_dist(false), _mask(0) {}
330 if(_local_pred) delete _pred;
331 if(_local_dist) delete _dist;
332 if(_mask) delete _mask;
335 /// \brief Sets the length map.
337 /// Sets the length map.
338 /// \return <tt>(*this)</tt>
339 BellmanFord &lengthMap(const LengthMap &map) {
344 /// \brief Sets the map that stores the predecessor arcs.
346 /// Sets the map that stores the predecessor arcs.
347 /// If you don't use this function before calling \ref run()
348 /// or \ref init(), an instance will be allocated automatically.
349 /// The destructor deallocates this automatically allocated map,
351 /// \return <tt>(*this)</tt>
352 BellmanFord &predMap(PredMap &map) {
361 /// \brief Sets the map that stores the distances of the nodes.
363 /// Sets the map that stores the distances of the nodes calculated
364 /// by the algorithm.
365 /// If you don't use this function before calling \ref run()
366 /// or \ref init(), an instance will be allocated automatically.
367 /// The destructor deallocates this automatically allocated map,
369 /// \return <tt>(*this)</tt>
370 BellmanFord &distMap(DistMap &map) {
379 /// \name Execution Control
380 /// The simplest way to execute the Bellman-Ford algorithm is to use
381 /// one of the member functions called \ref run().\n
382 /// If you need better control on the execution, you have to call
383 /// \ref init() first, then you can add several source nodes
384 /// with \ref addSource(). Finally the actual path computation can be
385 /// performed with \ref start(), \ref checkedStart() or
386 /// \ref limitedStart().
390 /// \brief Initializes the internal data structures.
392 /// Initializes the internal data structures. The optional parameter
393 /// is the initial distance of each node.
394 void init(const Value value = OperationTraits::infinity()) {
396 for (NodeIt it(*_gr); it != INVALID; ++it) {
397 _pred->set(it, INVALID);
398 _dist->set(it, value);
401 if (OperationTraits::less(value, OperationTraits::infinity())) {
402 for (NodeIt it(*_gr); it != INVALID; ++it) {
403 _process.push_back(it);
404 _mask->set(it, true);
409 /// \brief Adds a new source node.
411 /// This function adds a new source node. The optional second parameter
412 /// is the initial distance of the node.
413 void addSource(Node source, Value dst = OperationTraits::zero()) {
414 _dist->set(source, dst);
415 if (!(*_mask)[source]) {
416 _process.push_back(source);
417 _mask->set(source, true);
421 /// \brief Executes one round from the Bellman-Ford algorithm.
423 /// If the algoritm calculated the distances in the previous round
424 /// exactly for the paths of at most \c k arcs, then this function
425 /// will calculate the distances exactly for the paths of at most
426 /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
427 /// calculates the shortest path distances exactly for the paths
428 /// consisting of at most \c k arcs.
430 /// \warning The paths with limited arc number cannot be retrieved
431 /// easily with \ref path() or \ref predArc() functions. If you also
432 /// need the shortest paths and not only the distances, you should
433 /// store the \ref predMap() "predecessor map" after each iteration
434 /// and build the path manually.
436 /// \return \c true when the algorithm have not found more shorter
440 bool processNextRound() {
441 for (int i = 0; i < int(_process.size()); ++i) {
442 _mask->set(_process[i], false);
444 std::vector<Node> nextProcess;
445 std::vector<Value> values(_process.size());
446 for (int i = 0; i < int(_process.size()); ++i) {
447 values[i] = (*_dist)[_process[i]];
449 for (int i = 0; i < int(_process.size()); ++i) {
450 for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
451 Node target = _gr->target(it);
452 Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
453 if (OperationTraits::less(relaxed, (*_dist)[target])) {
454 _pred->set(target, it);
455 _dist->set(target, relaxed);
456 if (!(*_mask)[target]) {
457 _mask->set(target, true);
458 nextProcess.push_back(target);
463 _process.swap(nextProcess);
464 return _process.empty();
467 /// \brief Executes one weak round from the Bellman-Ford algorithm.
469 /// If the algorithm calculated the distances in the previous round
470 /// at least for the paths of at most \c k arcs, then this function
471 /// will calculate the distances at least for the paths of at most
472 /// <tt>k+1</tt> arcs.
473 /// This function does not make it possible to calculate the shortest
474 /// path distances exactly for paths consisting of at most \c k arcs,
475 /// this is why it is called weak round.
477 /// \return \c true when the algorithm have not found more shorter
481 bool processNextWeakRound() {
482 for (int i = 0; i < int(_process.size()); ++i) {
483 _mask->set(_process[i], false);
485 std::vector<Node> nextProcess;
486 for (int i = 0; i < int(_process.size()); ++i) {
487 for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
488 Node target = _gr->target(it);
490 OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
491 if (OperationTraits::less(relaxed, (*_dist)[target])) {
492 _pred->set(target, it);
493 _dist->set(target, relaxed);
494 if (!(*_mask)[target]) {
495 _mask->set(target, true);
496 nextProcess.push_back(target);
501 _process.swap(nextProcess);
502 return _process.empty();
505 /// \brief Executes the algorithm.
507 /// Executes the algorithm.
509 /// This method runs the Bellman-Ford algorithm from the root node(s)
510 /// in order to compute the shortest path to each node.
512 /// The algorithm computes
513 /// - the shortest path tree (forest),
514 /// - the distance of each node from the root(s).
516 /// \pre init() must be called and at least one root node should be
517 /// added with addSource() before using this function.
519 int num = countNodes(*_gr) - 1;
520 for (int i = 0; i < num; ++i) {
521 if (processNextWeakRound()) break;
525 /// \brief Executes the algorithm and checks the negative cycles.
527 /// Executes the algorithm and checks the negative cycles.
529 /// This method runs the Bellman-Ford algorithm from the root node(s)
530 /// in order to compute the shortest path to each node and also checks
531 /// if the digraph contains cycles with negative total length.
533 /// The algorithm computes
534 /// - the shortest path tree (forest),
535 /// - the distance of each node from the root(s).
537 /// \return \c false if there is a negative cycle in the digraph.
539 /// \pre init() must be called and at least one root node should be
540 /// added with addSource() before using this function.
541 bool checkedStart() {
542 int num = countNodes(*_gr);
543 for (int i = 0; i < num; ++i) {
544 if (processNextWeakRound()) return true;
546 return _process.empty();
549 /// \brief Executes the algorithm with arc number limit.
551 /// Executes the algorithm with arc number limit.
553 /// This method runs the Bellman-Ford algorithm from the root node(s)
554 /// in order to compute the shortest path distance for each node
555 /// using only the paths consisting of at most \c num arcs.
557 /// The algorithm computes
558 /// - the limited distance of each node from the root(s),
559 /// - the predecessor arc for each node.
561 /// \warning The paths with limited arc number cannot be retrieved
562 /// easily with \ref path() or \ref predArc() functions. If you also
563 /// need the shortest paths and not only the distances, you should
564 /// store the \ref predMap() "predecessor map" after each iteration
565 /// and build the path manually.
567 /// \pre init() must be called and at least one root node should be
568 /// added with addSource() before using this function.
569 void limitedStart(int num) {
570 for (int i = 0; i < num; ++i) {
571 if (processNextRound()) break;
575 /// \brief Runs the algorithm from the given root node.
577 /// This method runs the Bellman-Ford algorithm from the given root
578 /// node \c s in order to compute the shortest path to each node.
580 /// The algorithm computes
581 /// - the shortest path tree (forest),
582 /// - the distance of each node from the root(s).
584 /// \note bf.run(s) is just a shortcut of the following code.
596 /// \brief Runs the algorithm from the given root node with arc
599 /// This method runs the Bellman-Ford algorithm from the given root
600 /// node \c s in order to compute the shortest path distance for each
601 /// node using only the paths consisting of at most \c num arcs.
603 /// The algorithm computes
604 /// - the limited distance of each node from the root(s),
605 /// - the predecessor arc for each node.
607 /// \warning The paths with limited arc number cannot be retrieved
608 /// easily with \ref path() or \ref predArc() functions. If you also
609 /// need the shortest paths and not only the distances, you should
610 /// store the \ref predMap() "predecessor map" after each iteration
611 /// and build the path manually.
613 /// \note bf.run(s, num) is just a shortcut of the following code.
617 /// bf.limitedStart(num);
619 void run(Node s, int num) {
627 /// \brief LEMON iterator for getting the active nodes.
629 /// This class provides a common style LEMON iterator that traverses
630 /// the active nodes of the Bellman-Ford algorithm after the last
631 /// phase. These nodes should be checked in the next phase to
632 /// find augmenting arcs outgoing from them.
636 /// \brief Constructor.
638 /// Constructor for getting the active nodes of the given BellmanFord
640 ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
642 _index = _algorithm->_process.size() - 1;
645 /// \brief Invalid constructor.
647 /// Invalid constructor.
648 ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
650 /// \brief Conversion to \c Node.
652 /// Conversion to \c Node.
653 operator Node() const {
654 return _index >= 0 ? _algorithm->_process[_index] : INVALID;
657 /// \brief Increment operator.
659 /// Increment operator.
660 ActiveIt& operator++() {
665 bool operator==(const ActiveIt& it) const {
666 return static_cast<Node>(*this) == static_cast<Node>(it);
668 bool operator!=(const ActiveIt& it) const {
669 return static_cast<Node>(*this) != static_cast<Node>(it);
671 bool operator<(const ActiveIt& it) const {
672 return static_cast<Node>(*this) < static_cast<Node>(it);
676 const BellmanFord* _algorithm;
680 /// \name Query Functions
681 /// The result of the Bellman-Ford algorithm can be obtained using these
683 /// Either \ref run() or \ref init() should be called before using them.
687 /// \brief The shortest path to the given node.
689 /// Gives back the shortest path to the given node from the root(s).
691 /// \warning \c t should be reached from the root(s).
693 /// \pre Either \ref run() or \ref init() must be called before
694 /// using this function.
695 Path path(Node t) const
697 return Path(*_gr, *_pred, t);
700 /// \brief The distance of the given node from the root(s).
702 /// Returns the distance of the given node from the root(s).
704 /// \warning If node \c v is not reached from the root(s), then
705 /// the return value of this function is undefined.
707 /// \pre Either \ref run() or \ref init() must be called before
708 /// using this function.
709 Value dist(Node v) const { return (*_dist)[v]; }
711 /// \brief Returns the 'previous arc' of the shortest path tree for
714 /// This function returns the 'previous arc' of the shortest path
715 /// tree for node \c v, i.e. it returns the last arc of a
716 /// shortest path from a root to \c v. It is \c INVALID if \c v
717 /// is not reached from the root(s) or if \c v is a root.
719 /// The shortest path tree used here is equal to the shortest path
720 /// tree used in \ref predNode() and \predMap().
722 /// \pre Either \ref run() or \ref init() must be called before
723 /// using this function.
724 Arc predArc(Node v) const { return (*_pred)[v]; }
726 /// \brief Returns the 'previous node' of the shortest path tree for
729 /// This function returns the 'previous node' of the shortest path
730 /// tree for node \c v, i.e. it returns the last but one node of
731 /// a shortest path from a root to \c v. It is \c INVALID if \c v
732 /// is not reached from the root(s) or if \c v is a root.
734 /// The shortest path tree used here is equal to the shortest path
735 /// tree used in \ref predArc() and \predMap().
737 /// \pre Either \ref run() or \ref init() must be called before
738 /// using this function.
739 Node predNode(Node v) const {
740 return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
743 /// \brief Returns a const reference to the node map that stores the
744 /// distances of the nodes.
746 /// Returns a const reference to the node map that stores the distances
747 /// of the nodes calculated by the algorithm.
749 /// \pre Either \ref run() or \ref init() must be called before
750 /// using this function.
751 const DistMap &distMap() const { return *_dist;}
753 /// \brief Returns a const reference to the node map that stores the
754 /// predecessor arcs.
756 /// Returns a const reference to the node map that stores the predecessor
757 /// arcs, which form the shortest path tree (forest).
759 /// \pre Either \ref run() or \ref init() must be called before
760 /// using this function.
761 const PredMap &predMap() const { return *_pred; }
763 /// \brief Checks if a node is reached from the root(s).
765 /// Returns \c true if \c v is reached from the root(s).
767 /// \pre Either \ref run() or \ref init() must be called before
768 /// using this function.
769 bool reached(Node v) const {
770 return (*_dist)[v] != OperationTraits::infinity();
773 // TODO: implement negative cycle
774 // /// \brief Gives back a negative cycle.
776 // /// This function gives back a negative cycle.
777 // /// If the algorithm have not found yet negative cycle it will give back
778 // /// an empty path.
779 // Path negativeCycle() {
780 // typename Digraph::template NodeMap<int> state(*digraph, 0);
781 // for (ActiveIt it(*this); it != INVALID; ++it) {
782 // if (state[it] == 0) {
783 // for (Node t = it; predArc(t) != INVALID; t = predNode(t)) {
784 // if (state[t] == 0) {
786 // } else if (state[t] == 2) {
790 // typename Path::Builder b(p);
791 // b.setStartNode(t);
792 // b.pushFront(predArc(t));
793 // for(Node s = predNode(t); s != t; s = predNode(s)) {
794 // b.pushFront(predArc(s));
800 // for (Node t = it; predArc(t) != INVALID; t = predNode(t)) {
801 // if (state[t] == 1) {
815 /// \brief Default traits class of bellmanFord() function.
817 /// Default traits class of bellmanFord() function.
818 /// \tparam GR The type of the digraph.
819 /// \tparam LEN The type of the length map.
820 template <typename GR, typename LEN>
821 struct BellmanFordWizardDefaultTraits {
822 /// The type of the digraph the algorithm runs on.
825 /// \brief The type of the map that stores the arc lengths.
827 /// The type of the map that stores the arc lengths.
828 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
829 typedef LEN LengthMap;
831 /// The type of the arc lengths.
832 typedef typename LEN::Value Value;
834 /// \brief Operation traits for Bellman-Ford algorithm.
836 /// It defines the used operations and the infinity value for the
837 /// given \c Value type.
838 /// \see BellmanFordDefaultOperationTraits
839 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
841 /// \brief The type of the map that stores the last
842 /// arcs of the shortest paths.
844 /// The type of the map that stores the last arcs of the shortest paths.
845 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
846 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
848 /// \brief Instantiates a \c PredMap.
850 /// This function instantiates a \ref PredMap.
851 /// \param g is the digraph to which we would like to define the
853 static PredMap *createPredMap(const GR &g) {
854 return new PredMap(g);
857 /// \brief The type of the map that stores the distances of the nodes.
859 /// The type of the map that stores the distances of the nodes.
860 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
861 typedef typename GR::template NodeMap<Value> DistMap;
863 /// \brief Instantiates a \c DistMap.
865 /// This function instantiates a \ref DistMap.
866 /// \param g is the digraph to which we would like to define the
868 static DistMap *createDistMap(const GR &g) {
869 return new DistMap(g);
872 ///The type of the shortest paths.
874 ///The type of the shortest paths.
875 ///It must meet the \ref concepts::Path "Path" concept.
876 typedef lemon::Path<Digraph> Path;
879 /// \brief Default traits class used by BellmanFordWizard.
881 /// Default traits class used by BellmanFordWizard.
882 /// \tparam GR The type of the digraph.
883 /// \tparam LEN The type of the length map.
884 template <typename GR, typename LEN>
885 class BellmanFordWizardBase
886 : public BellmanFordWizardDefaultTraits<GR, LEN> {
888 typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
890 // Type of the nodes in the digraph.
891 typedef typename Base::Digraph::Node Node;
893 // Pointer to the underlying digraph.
895 // Pointer to the length map
897 // Pointer to the map of predecessors arcs.
899 // Pointer to the map of distances.
901 //Pointer to the shortest path to the target node.
903 //Pointer to the distance of the target node.
909 /// This constructor does not require parameters, it initiates
910 /// all of the attributes to default values \c 0.
911 BellmanFordWizardBase() :
912 _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
916 /// This constructor requires two parameters,
917 /// others are initiated to \c 0.
918 /// \param gr The digraph the algorithm runs on.
919 /// \param len The length map.
920 BellmanFordWizardBase(const GR& gr,
922 _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
923 _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
924 _pred(0), _dist(0), _path(0), _di(0) {}
928 /// \brief Auxiliary class for the function-type interface of the
929 /// \ref BellmanFord "Bellman-Ford" algorithm.
931 /// This auxiliary class is created to implement the
932 /// \ref bellmanFord() "function-type interface" of the
933 /// \ref BellmanFord "Bellman-Ford" algorithm.
934 /// It does not have own \ref run() method, it uses the
935 /// functions and features of the plain \ref BellmanFord.
937 /// This class should only be used through the \ref bellmanFord()
938 /// function, which makes it easier to use the algorithm.
940 class BellmanFordWizard : public TR {
943 typedef typename TR::Digraph Digraph;
945 typedef typename Digraph::Node Node;
946 typedef typename Digraph::NodeIt NodeIt;
947 typedef typename Digraph::Arc Arc;
948 typedef typename Digraph::OutArcIt ArcIt;
950 typedef typename TR::LengthMap LengthMap;
951 typedef typename LengthMap::Value Value;
952 typedef typename TR::PredMap PredMap;
953 typedef typename TR::DistMap DistMap;
954 typedef typename TR::Path Path;
958 BellmanFordWizard() : TR() {}
960 /// \brief Constructor that requires parameters.
962 /// Constructor that requires parameters.
963 /// These parameters will be the default values for the traits class.
964 /// \param gr The digraph the algorithm runs on.
965 /// \param len The length map.
966 BellmanFordWizard(const Digraph& gr, const LengthMap& len)
969 /// \brief Copy constructor
970 BellmanFordWizard(const TR &b) : TR(b) {}
972 ~BellmanFordWizard() {}
974 /// \brief Runs the Bellman-Ford algorithm from the given source node.
976 /// This method runs the Bellman-Ford algorithm from the given source
977 /// node in order to compute the shortest path to each node.
979 BellmanFord<Digraph,LengthMap,TR>
980 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
981 *reinterpret_cast<const LengthMap*>(Base::_length));
982 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
983 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
987 /// \brief Runs the Bellman-Ford algorithm to find the shortest path
988 /// between \c s and \c t.
990 /// This method runs the Bellman-Ford algorithm from node \c s
991 /// in order to compute the shortest path to node \c t.
992 /// Actually, it computes the shortest path to each node, but using
993 /// this function you can retrieve the distance and the shortest path
994 /// for a single target node easier.
996 /// \return \c true if \c t is reachable form \c s.
997 bool run(Node s, Node t) {
998 BellmanFord<Digraph,LengthMap,TR>
999 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1000 *reinterpret_cast<const LengthMap*>(Base::_length));
1001 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1002 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1004 if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1005 if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1006 return bf.reached(t);
1010 struct SetPredMapBase : public Base {
1012 static PredMap *createPredMap(const Digraph &) { return 0; };
1013 SetPredMapBase(const TR &b) : TR(b) {}
1016 /// \brief \ref named-templ-param "Named parameter" for setting
1017 /// the predecessor map.
1019 /// \ref named-templ-param "Named parameter" for setting
1020 /// the map that stores the predecessor arcs of the nodes.
1022 BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1023 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1024 return BellmanFordWizard<SetPredMapBase<T> >(*this);
1028 struct SetDistMapBase : public Base {
1030 static DistMap *createDistMap(const Digraph &) { return 0; };
1031 SetDistMapBase(const TR &b) : TR(b) {}
1034 /// \brief \ref named-templ-param "Named parameter" for setting
1035 /// the distance map.
1037 /// \ref named-templ-param "Named parameter" for setting
1038 /// the map that stores the distances of the nodes calculated
1039 /// by the algorithm.
1041 BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1042 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1043 return BellmanFordWizard<SetDistMapBase<T> >(*this);
1047 struct SetPathBase : public Base {
1049 SetPathBase(const TR &b) : TR(b) {}
1052 /// \brief \ref named-func-param "Named parameter" for getting
1053 /// the shortest path to the target node.
1055 /// \ref named-func-param "Named parameter" for getting
1056 /// the shortest path to the target node.
1058 BellmanFordWizard<SetPathBase<T> > path(const T &t)
1060 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1061 return BellmanFordWizard<SetPathBase<T> >(*this);
1064 /// \brief \ref named-func-param "Named parameter" for getting
1065 /// the distance of the target node.
1067 /// \ref named-func-param "Named parameter" for getting
1068 /// the distance of the target node.
1069 BellmanFordWizard dist(const Value &d)
1071 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1077 /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1080 /// \ingroup shortest_path
1081 /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1084 /// This function also has several \ref named-templ-func-param
1085 /// "named parameters", they are declared as the members of class
1086 /// \ref BellmanFordWizard.
1087 /// The following examples show how to use these parameters.
1089 /// // Compute shortest path from node s to each node
1090 /// bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1092 /// // Compute shortest path from s to t
1093 /// bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1095 /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1096 /// to the end of the parameter list.
1097 /// \sa BellmanFordWizard
1099 template<typename GR, typename LEN>
1100 BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1101 bellmanFord(const GR& digraph,
1104 return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1107 } //END OF NAMESPACE LEMON