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/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>".
174 /// \tparam TR The traits class that defines various types used by the
175 /// algorithm. By default, it is \ref BellmanFordDefaultTraits
176 /// "BellmanFordDefaultTraits<GR, LEN>".
177 /// In most cases, this parameter should not be set directly,
178 /// consider to use the named template parameters instead.
180 template <typename GR, typename LEN, typename TR>
182 template <typename GR=ListDigraph,
183 typename LEN=typename GR::template ArcMap<int>,
184 typename TR=BellmanFordDefaultTraits<GR,LEN> >
189 ///The type of the underlying digraph.
190 typedef typename TR::Digraph Digraph;
192 /// \brief The type of the arc lengths.
193 typedef typename TR::LengthMap::Value Value;
194 /// \brief The type of the map that stores the arc lengths.
195 typedef typename TR::LengthMap LengthMap;
196 /// \brief The type of the map that stores the last
197 /// arcs of the shortest paths.
198 typedef typename TR::PredMap PredMap;
199 /// \brief The type of the map that stores the distances of the nodes.
200 typedef typename TR::DistMap DistMap;
201 /// The type of the paths.
202 typedef PredMapPath<Digraph, PredMap> Path;
203 ///\brief The \ref lemon::BellmanFordDefaultOperationTraits
204 /// "operation traits class" of the algorithm.
205 typedef typename TR::OperationTraits OperationTraits;
207 ///\brief The \ref lemon::BellmanFordDefaultTraits "traits class"
213 typedef typename Digraph::Node Node;
214 typedef typename Digraph::NodeIt NodeIt;
215 typedef typename Digraph::Arc Arc;
216 typedef typename Digraph::OutArcIt OutArcIt;
218 // Pointer to the underlying digraph.
220 // Pointer to the length map
221 const LengthMap *_length;
222 // Pointer to the map of predecessors arcs.
224 // Indicates if _pred is locally allocated (true) or not.
226 // Pointer to the map of distances.
228 // Indicates if _dist is locally allocated (true) or not.
231 typedef typename Digraph::template NodeMap<bool> MaskMap;
234 std::vector<Node> _process;
236 // Creates the maps if necessary.
240 _pred = Traits::createPredMap(*_gr);
244 _dist = Traits::createDistMap(*_gr);
247 _mask = new MaskMap(*_gr);
253 typedef BellmanFord Create;
255 /// \name Named Template Parameters
260 struct SetPredMapTraits : public Traits {
262 static PredMap *createPredMap(const Digraph&) {
263 LEMON_ASSERT(false, "PredMap is not initialized");
264 return 0; // ignore warnings
268 /// \brief \ref named-templ-param "Named parameter" for setting
271 /// \ref named-templ-param "Named parameter" for setting
273 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
276 : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
277 typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
281 struct SetDistMapTraits : public Traits {
283 static DistMap *createDistMap(const Digraph&) {
284 LEMON_ASSERT(false, "DistMap is not initialized");
285 return 0; // ignore warnings
289 /// \brief \ref named-templ-param "Named parameter" for setting
292 /// \ref named-templ-param "Named parameter" for setting
294 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
297 : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
298 typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
302 struct SetOperationTraitsTraits : public Traits {
303 typedef T OperationTraits;
306 /// \brief \ref named-templ-param "Named parameter" for setting
307 /// \c OperationTraits type.
309 /// \ref named-templ-param "Named parameter" for setting
310 /// \c OperationTraits type.
311 /// For more information, see \ref BellmanFordDefaultOperationTraits.
313 struct SetOperationTraits
314 : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
315 typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
327 /// \brief Constructor.
330 /// \param g The digraph the algorithm runs on.
331 /// \param length The length map used by the algorithm.
332 BellmanFord(const Digraph& g, const LengthMap& length) :
333 _gr(&g), _length(&length),
334 _pred(0), _local_pred(false),
335 _dist(0), _local_dist(false), _mask(0) {}
339 if(_local_pred) delete _pred;
340 if(_local_dist) delete _dist;
341 if(_mask) delete _mask;
344 /// \brief Sets the length map.
346 /// Sets the length map.
347 /// \return <tt>(*this)</tt>
348 BellmanFord &lengthMap(const LengthMap &map) {
353 /// \brief Sets the map that stores the predecessor arcs.
355 /// Sets the map that stores the predecessor arcs.
356 /// If you don't use this function before calling \ref run()
357 /// or \ref init(), an instance will be allocated automatically.
358 /// The destructor deallocates this automatically allocated map,
360 /// \return <tt>(*this)</tt>
361 BellmanFord &predMap(PredMap &map) {
370 /// \brief Sets the map that stores the distances of the nodes.
372 /// Sets the map that stores the distances of the nodes calculated
373 /// by the algorithm.
374 /// If you don't use this function before calling \ref run()
375 /// or \ref init(), an instance will be allocated automatically.
376 /// The destructor deallocates this automatically allocated map,
378 /// \return <tt>(*this)</tt>
379 BellmanFord &distMap(DistMap &map) {
388 /// \name Execution Control
389 /// The simplest way to execute the Bellman-Ford algorithm is to use
390 /// one of the member functions called \ref run().\n
391 /// If you need better control on the execution, you have to call
392 /// \ref init() first, then you can add several source nodes
393 /// with \ref addSource(). Finally the actual path computation can be
394 /// performed with \ref start(), \ref checkedStart() or
395 /// \ref limitedStart().
399 /// \brief Initializes the internal data structures.
401 /// Initializes the internal data structures. The optional parameter
402 /// is the initial distance of each node.
403 void init(const Value value = OperationTraits::infinity()) {
405 for (NodeIt it(*_gr); it != INVALID; ++it) {
406 _pred->set(it, INVALID);
407 _dist->set(it, value);
410 if (OperationTraits::less(value, OperationTraits::infinity())) {
411 for (NodeIt it(*_gr); it != INVALID; ++it) {
412 _process.push_back(it);
413 _mask->set(it, true);
416 for (NodeIt it(*_gr); it != INVALID; ++it) {
417 _mask->set(it, false);
422 /// \brief Adds a new source node.
424 /// This function adds a new source node. The optional second parameter
425 /// is the initial distance of the node.
426 void addSource(Node source, Value dst = OperationTraits::zero()) {
427 _dist->set(source, dst);
428 if (!(*_mask)[source]) {
429 _process.push_back(source);
430 _mask->set(source, true);
434 /// \brief Executes one round from the Bellman-Ford algorithm.
436 /// If the algoritm calculated the distances in the previous round
437 /// exactly for the paths of at most \c k arcs, then this function
438 /// will calculate the distances exactly for the paths of at most
439 /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
440 /// calculates the shortest path distances exactly for the paths
441 /// consisting of at most \c k arcs.
443 /// \warning The paths with limited arc number cannot be retrieved
444 /// easily with \ref path() or \ref predArc() functions. If you also
445 /// need the shortest paths and not only the distances, you should
446 /// store the \ref predMap() "predecessor map" after each iteration
447 /// and build the path manually.
449 /// \return \c true when the algorithm have not found more shorter
453 bool processNextRound() {
454 for (int i = 0; i < int(_process.size()); ++i) {
455 _mask->set(_process[i], false);
457 std::vector<Node> nextProcess;
458 std::vector<Value> values(_process.size());
459 for (int i = 0; i < int(_process.size()); ++i) {
460 values[i] = (*_dist)[_process[i]];
462 for (int i = 0; i < int(_process.size()); ++i) {
463 for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
464 Node target = _gr->target(it);
465 Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
466 if (OperationTraits::less(relaxed, (*_dist)[target])) {
467 _pred->set(target, it);
468 _dist->set(target, relaxed);
469 if (!(*_mask)[target]) {
470 _mask->set(target, true);
471 nextProcess.push_back(target);
476 _process.swap(nextProcess);
477 return _process.empty();
480 /// \brief Executes one weak round from the Bellman-Ford algorithm.
482 /// If the algorithm calculated the distances in the previous round
483 /// at least for the paths of at most \c k arcs, then this function
484 /// will calculate the distances at least for the paths of at most
485 /// <tt>k+1</tt> arcs.
486 /// This function does not make it possible to calculate the shortest
487 /// path distances exactly for paths consisting of at most \c k arcs,
488 /// this is why it is called weak round.
490 /// \return \c true when the algorithm have not found more shorter
494 bool processNextWeakRound() {
495 for (int i = 0; i < int(_process.size()); ++i) {
496 _mask->set(_process[i], false);
498 std::vector<Node> nextProcess;
499 for (int i = 0; i < int(_process.size()); ++i) {
500 for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
501 Node target = _gr->target(it);
503 OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
504 if (OperationTraits::less(relaxed, (*_dist)[target])) {
505 _pred->set(target, it);
506 _dist->set(target, relaxed);
507 if (!(*_mask)[target]) {
508 _mask->set(target, true);
509 nextProcess.push_back(target);
514 _process.swap(nextProcess);
515 return _process.empty();
518 /// \brief Executes the algorithm.
520 /// Executes the algorithm.
522 /// This method runs the Bellman-Ford algorithm from the root node(s)
523 /// in order to compute the shortest path to each node.
525 /// The algorithm computes
526 /// - the shortest path tree (forest),
527 /// - the distance of each node from the root(s).
529 /// \pre init() must be called and at least one root node should be
530 /// added with addSource() before using this function.
532 int num = countNodes(*_gr) - 1;
533 for (int i = 0; i < num; ++i) {
534 if (processNextWeakRound()) break;
538 /// \brief Executes the algorithm and checks the negative cycles.
540 /// Executes the algorithm and checks the negative cycles.
542 /// This method runs the Bellman-Ford algorithm from the root node(s)
543 /// in order to compute the shortest path to each node and also checks
544 /// if the digraph contains cycles with negative total length.
546 /// The algorithm computes
547 /// - the shortest path tree (forest),
548 /// - the distance of each node from the root(s).
550 /// \return \c false if there is a negative cycle in the digraph.
552 /// \pre init() must be called and at least one root node should be
553 /// added with addSource() before using this function.
554 bool checkedStart() {
555 int num = countNodes(*_gr);
556 for (int i = 0; i < num; ++i) {
557 if (processNextWeakRound()) return true;
559 return _process.empty();
562 /// \brief Executes the algorithm with arc number limit.
564 /// Executes the algorithm with arc number limit.
566 /// This method runs the Bellman-Ford algorithm from the root node(s)
567 /// in order to compute the shortest path distance for each node
568 /// using only the paths consisting of at most \c num arcs.
570 /// The algorithm computes
571 /// - the limited distance of each node from the root(s),
572 /// - the predecessor arc for each node.
574 /// \warning The paths with limited arc number cannot be retrieved
575 /// easily with \ref path() or \ref predArc() functions. If you also
576 /// need the shortest paths and not only the distances, you should
577 /// store the \ref predMap() "predecessor map" after each iteration
578 /// and build the path manually.
580 /// \pre init() must be called and at least one root node should be
581 /// added with addSource() before using this function.
582 void limitedStart(int num) {
583 for (int i = 0; i < num; ++i) {
584 if (processNextRound()) break;
588 /// \brief Runs the algorithm from the given root node.
590 /// This method runs the Bellman-Ford algorithm from the given root
591 /// node \c s in order to compute the shortest path to each node.
593 /// The algorithm computes
594 /// - the shortest path tree (forest),
595 /// - the distance of each node from the root(s).
597 /// \note bf.run(s) is just a shortcut of the following code.
609 /// \brief Runs the algorithm from the given root node with arc
612 /// This method runs the Bellman-Ford algorithm from the given root
613 /// node \c s in order to compute the shortest path distance for each
614 /// node using only the paths consisting of at most \c num arcs.
616 /// The algorithm computes
617 /// - the limited distance of each node from the root(s),
618 /// - the predecessor arc for each node.
620 /// \warning The paths with limited arc number cannot be retrieved
621 /// easily with \ref path() or \ref predArc() functions. If you also
622 /// need the shortest paths and not only the distances, you should
623 /// store the \ref predMap() "predecessor map" after each iteration
624 /// and build the path manually.
626 /// \note bf.run(s, num) is just a shortcut of the following code.
630 /// bf.limitedStart(num);
632 void run(Node s, int num) {
640 /// \brief LEMON iterator for getting the active nodes.
642 /// This class provides a common style LEMON iterator that traverses
643 /// the active nodes of the Bellman-Ford algorithm after the last
644 /// phase. These nodes should be checked in the next phase to
645 /// find augmenting arcs outgoing from them.
649 /// \brief Constructor.
651 /// Constructor for getting the active nodes of the given BellmanFord
653 ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
655 _index = _algorithm->_process.size() - 1;
658 /// \brief Invalid constructor.
660 /// Invalid constructor.
661 ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
663 /// \brief Conversion to \c Node.
665 /// Conversion to \c Node.
666 operator Node() const {
667 return _index >= 0 ? _algorithm->_process[_index] : INVALID;
670 /// \brief Increment operator.
672 /// Increment operator.
673 ActiveIt& operator++() {
678 bool operator==(const ActiveIt& it) const {
679 return static_cast<Node>(*this) == static_cast<Node>(it);
681 bool operator!=(const ActiveIt& it) const {
682 return static_cast<Node>(*this) != static_cast<Node>(it);
684 bool operator<(const ActiveIt& it) const {
685 return static_cast<Node>(*this) < static_cast<Node>(it);
689 const BellmanFord* _algorithm;
693 /// \name Query Functions
694 /// The result of the Bellman-Ford algorithm can be obtained using these
696 /// Either \ref run() or \ref init() should be called before using them.
700 /// \brief The shortest path to the given node.
702 /// Gives back the shortest path to the given node from the root(s).
704 /// \warning \c t should be reached from the root(s).
706 /// \pre Either \ref run() or \ref init() must be called before
707 /// using this function.
708 Path path(Node t) const
710 return Path(*_gr, *_pred, t);
713 /// \brief The distance of the given node from the root(s).
715 /// Returns the distance of the given node from the root(s).
717 /// \warning If node \c v is not reached from the root(s), then
718 /// the return value of this function is undefined.
720 /// \pre Either \ref run() or \ref init() must be called before
721 /// using this function.
722 Value dist(Node v) const { return (*_dist)[v]; }
724 /// \brief Returns the 'previous arc' of the shortest path tree for
727 /// This function returns the 'previous arc' of the shortest path
728 /// tree for node \c v, i.e. it returns the last arc of a
729 /// shortest path from a root to \c v. It is \c INVALID if \c v
730 /// is not reached from the root(s) or if \c v is a root.
732 /// The shortest path tree used here is equal to the shortest path
733 /// tree used in \ref predNode() and \ref predMap().
735 /// \pre Either \ref run() or \ref init() must be called before
736 /// using this function.
737 Arc predArc(Node v) const { return (*_pred)[v]; }
739 /// \brief Returns the 'previous node' of the shortest path tree for
742 /// This function returns the 'previous node' of the shortest path
743 /// tree for node \c v, i.e. it returns the last but one node of
744 /// a shortest path from a root to \c v. It is \c INVALID if \c v
745 /// is not reached from the root(s) or if \c v is a root.
747 /// The shortest path tree used here is equal to the shortest path
748 /// tree used in \ref predArc() and \ref predMap().
750 /// \pre Either \ref run() or \ref init() must be called before
751 /// using this function.
752 Node predNode(Node v) const {
753 return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
756 /// \brief Returns a const reference to the node map that stores the
757 /// distances of the nodes.
759 /// Returns a const reference to the node map that stores the distances
760 /// of the nodes calculated by the algorithm.
762 /// \pre Either \ref run() or \ref init() must be called before
763 /// using this function.
764 const DistMap &distMap() const { return *_dist;}
766 /// \brief Returns a const reference to the node map that stores the
767 /// predecessor arcs.
769 /// Returns a const reference to the node map that stores the predecessor
770 /// arcs, which form the shortest path tree (forest).
772 /// \pre Either \ref run() or \ref init() must be called before
773 /// using this function.
774 const PredMap &predMap() const { return *_pred; }
776 /// \brief Checks if a node is reached from the root(s).
778 /// Returns \c true if \c v is reached from the root(s).
780 /// \pre Either \ref run() or \ref init() must be called before
781 /// using this function.
782 bool reached(Node v) const {
783 return (*_dist)[v] != OperationTraits::infinity();
786 /// \brief Gives back a negative cycle.
788 /// This function gives back a directed cycle with negative total
789 /// length if the algorithm has already found one.
790 /// Otherwise it gives back an empty path.
791 lemon::Path<Digraph> negativeCycle() const {
792 typename Digraph::template NodeMap<int> state(*_gr, -1);
793 lemon::Path<Digraph> cycle;
794 for (int i = 0; i < int(_process.size()); ++i) {
795 if (state[_process[i]] != -1) continue;
796 for (Node v = _process[i]; (*_pred)[v] != INVALID;
797 v = _gr->source((*_pred)[v])) {
799 cycle.addFront((*_pred)[v]);
800 for (Node u = _gr->source((*_pred)[v]); u != v;
801 u = _gr->source((*_pred)[u])) {
802 cycle.addFront((*_pred)[u]);
806 else if (state[v] >= 0) {
818 /// \brief Default traits class of bellmanFord() function.
820 /// Default traits class of bellmanFord() function.
821 /// \tparam GR The type of the digraph.
822 /// \tparam LEN The type of the length map.
823 template <typename GR, typename LEN>
824 struct BellmanFordWizardDefaultTraits {
825 /// The type of the digraph the algorithm runs on.
828 /// \brief The type of the map that stores the arc lengths.
830 /// The type of the map that stores the arc lengths.
831 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
832 typedef LEN LengthMap;
834 /// The type of the arc lengths.
835 typedef typename LEN::Value Value;
837 /// \brief Operation traits for Bellman-Ford algorithm.
839 /// It defines the used operations and the infinity value for the
840 /// given \c Value type.
841 /// \see BellmanFordDefaultOperationTraits
842 typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
844 /// \brief The type of the map that stores the last
845 /// arcs of the shortest paths.
847 /// The type of the map that stores the last arcs of the shortest paths.
848 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
849 typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
851 /// \brief Instantiates a \c PredMap.
853 /// This function instantiates a \ref PredMap.
854 /// \param g is the digraph to which we would like to define the
856 static PredMap *createPredMap(const GR &g) {
857 return new PredMap(g);
860 /// \brief The type of the map that stores the distances of the nodes.
862 /// The type of the map that stores the distances of the nodes.
863 /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
864 typedef typename GR::template NodeMap<Value> DistMap;
866 /// \brief Instantiates a \c DistMap.
868 /// This function instantiates a \ref DistMap.
869 /// \param g is the digraph to which we would like to define the
871 static DistMap *createDistMap(const GR &g) {
872 return new DistMap(g);
875 ///The type of the shortest paths.
877 ///The type of the shortest paths.
878 ///It must meet the \ref concepts::Path "Path" concept.
879 typedef lemon::Path<Digraph> Path;
882 /// \brief Default traits class used by BellmanFordWizard.
884 /// Default traits class used by BellmanFordWizard.
885 /// \tparam GR The type of the digraph.
886 /// \tparam LEN The type of the length map.
887 template <typename GR, typename LEN>
888 class BellmanFordWizardBase
889 : public BellmanFordWizardDefaultTraits<GR, LEN> {
891 typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
893 // Type of the nodes in the digraph.
894 typedef typename Base::Digraph::Node Node;
896 // Pointer to the underlying digraph.
898 // Pointer to the length map
900 // Pointer to the map of predecessors arcs.
902 // Pointer to the map of distances.
904 //Pointer to the shortest path to the target node.
906 //Pointer to the distance of the target node.
912 /// This constructor does not require parameters, it initiates
913 /// all of the attributes to default values \c 0.
914 BellmanFordWizardBase() :
915 _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
919 /// This constructor requires two parameters,
920 /// others are initiated to \c 0.
921 /// \param gr The digraph the algorithm runs on.
922 /// \param len The length map.
923 BellmanFordWizardBase(const GR& gr,
925 _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
926 _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
927 _pred(0), _dist(0), _path(0), _di(0) {}
931 /// \brief Auxiliary class for the function-type interface of the
932 /// \ref BellmanFord "Bellman-Ford" algorithm.
934 /// This auxiliary class is created to implement the
935 /// \ref bellmanFord() "function-type interface" of the
936 /// \ref BellmanFord "Bellman-Ford" algorithm.
937 /// It does not have own \ref run() method, it uses the
938 /// functions and features of the plain \ref BellmanFord.
940 /// This class should only be used through the \ref bellmanFord()
941 /// function, which makes it easier to use the algorithm.
943 /// \tparam TR The traits class that defines various types used by the
946 class BellmanFordWizard : public TR {
949 typedef typename TR::Digraph Digraph;
951 typedef typename Digraph::Node Node;
952 typedef typename Digraph::NodeIt NodeIt;
953 typedef typename Digraph::Arc Arc;
954 typedef typename Digraph::OutArcIt ArcIt;
956 typedef typename TR::LengthMap LengthMap;
957 typedef typename LengthMap::Value Value;
958 typedef typename TR::PredMap PredMap;
959 typedef typename TR::DistMap DistMap;
960 typedef typename TR::Path Path;
964 BellmanFordWizard() : TR() {}
966 /// \brief Constructor that requires parameters.
968 /// Constructor that requires parameters.
969 /// These parameters will be the default values for the traits class.
970 /// \param gr The digraph the algorithm runs on.
971 /// \param len The length map.
972 BellmanFordWizard(const Digraph& gr, const LengthMap& len)
975 /// \brief Copy constructor
976 BellmanFordWizard(const TR &b) : TR(b) {}
978 ~BellmanFordWizard() {}
980 /// \brief Runs the Bellman-Ford algorithm from the given source node.
982 /// This method runs the Bellman-Ford algorithm from the given source
983 /// node in order to compute the shortest path to each node.
985 BellmanFord<Digraph,LengthMap,TR>
986 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
987 *reinterpret_cast<const LengthMap*>(Base::_length));
988 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
989 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
993 /// \brief Runs the Bellman-Ford algorithm to find the shortest path
994 /// between \c s and \c t.
996 /// This method runs the Bellman-Ford algorithm from node \c s
997 /// in order to compute the shortest path to node \c t.
998 /// Actually, it computes the shortest path to each node, but using
999 /// this function you can retrieve the distance and the shortest path
1000 /// for a single target node easier.
1002 /// \return \c true if \c t is reachable form \c s.
1003 bool run(Node s, Node t) {
1004 BellmanFord<Digraph,LengthMap,TR>
1005 bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1006 *reinterpret_cast<const LengthMap*>(Base::_length));
1007 if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1008 if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1010 if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1011 if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1012 return bf.reached(t);
1016 struct SetPredMapBase : public Base {
1018 static PredMap *createPredMap(const Digraph &) { return 0; };
1019 SetPredMapBase(const TR &b) : TR(b) {}
1022 /// \brief \ref named-templ-param "Named parameter" for setting
1023 /// the predecessor map.
1025 /// \ref named-templ-param "Named parameter" for setting
1026 /// the map that stores the predecessor arcs of the nodes.
1028 BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1029 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1030 return BellmanFordWizard<SetPredMapBase<T> >(*this);
1034 struct SetDistMapBase : public Base {
1036 static DistMap *createDistMap(const Digraph &) { return 0; };
1037 SetDistMapBase(const TR &b) : TR(b) {}
1040 /// \brief \ref named-templ-param "Named parameter" for setting
1041 /// the distance map.
1043 /// \ref named-templ-param "Named parameter" for setting
1044 /// the map that stores the distances of the nodes calculated
1045 /// by the algorithm.
1047 BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1048 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1049 return BellmanFordWizard<SetDistMapBase<T> >(*this);
1053 struct SetPathBase : public Base {
1055 SetPathBase(const TR &b) : TR(b) {}
1058 /// \brief \ref named-func-param "Named parameter" for getting
1059 /// the shortest path to the target node.
1061 /// \ref named-func-param "Named parameter" for getting
1062 /// the shortest path to the target node.
1064 BellmanFordWizard<SetPathBase<T> > path(const T &t)
1066 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1067 return BellmanFordWizard<SetPathBase<T> >(*this);
1070 /// \brief \ref named-func-param "Named parameter" for getting
1071 /// the distance of the target node.
1073 /// \ref named-func-param "Named parameter" for getting
1074 /// the distance of the target node.
1075 BellmanFordWizard dist(const Value &d)
1077 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1083 /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1086 /// \ingroup shortest_path
1087 /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1090 /// This function also has several \ref named-templ-func-param
1091 /// "named parameters", they are declared as the members of class
1092 /// \ref BellmanFordWizard.
1093 /// The following examples show how to use these parameters.
1095 /// // Compute shortest path from node s to each node
1096 /// bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1098 /// // Compute shortest path from s to t
1099 /// bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1101 /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1102 /// to the end of the parameter list.
1103 /// \sa BellmanFordWizard
1105 template<typename GR, typename LEN>
1106 BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1107 bellmanFord(const GR& digraph,
1110 return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1113 } //END OF NAMESPACE LEMON