2 * lemon/belmann_ford.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
17 #ifndef LEMON_BELMANN_FORD_H
18 #define LEMON_BELMANN_FORD_H
22 /// \brief BelmannFord algorithm.
24 /// \todo getPath() should be implemented! (also for BFS and DFS)
26 #include <lemon/list_graph.h>
27 #include <lemon/invalid.h>
28 #include <lemon/error.h>
29 #include <lemon/maps.h>
35 /// \brief Default OperationTraits for the BelmannFord algorithm class.
37 /// It defines all computational operations and constants which are
38 /// used in the belmann ford algorithm. The default implementation
39 /// is based on the numeric_limits class. If the numeric type does not
40 /// have infinity value then the maximum value is used as extremal
44 bool has_infinity = std::numeric_limits<Value>::has_infinity>
45 struct BelmannFordDefaultOperationTraits {
46 /// \brief Gives back the zero value of the type.
48 return static_cast<Value>(0);
50 /// \brief Gives back the positive infinity value of the type.
51 static Value infinity() {
52 return std::numeric_limits<Value>::infinity();
54 /// \brief Gives back the sum of the given two elements.
55 static Value plus(const Value& left, const Value& right) {
58 /// \brief Gives back true only if the first value less than the second.
59 static bool less(const Value& left, const Value& right) {
64 template <typename Value>
65 struct BelmannFordDefaultOperationTraits<Value, false> {
67 return static_cast<Value>(0);
69 static Value infinity() {
70 return std::numeric_limits<Value>::max();
72 static Value plus(const Value& left, const Value& right) {
73 if (left == infinity() || right == infinity()) return infinity();
76 static bool less(const Value& left, const Value& right) {
81 /// \brief Default traits class of BelmannFord class.
83 /// Default traits class of BelmannFord class.
84 /// \param _Graph Graph type.
85 /// \param _LegthMap Type of length map.
86 template<class _Graph, class _LengthMap>
87 struct BelmannFordDefaultTraits {
88 /// The graph type the algorithm runs on.
91 /// \brief The type of the map that stores the edge lengths.
93 /// The type of the map that stores the edge lengths.
94 /// It must meet the \ref concept::ReadMap "ReadMap" concept.
95 typedef _LengthMap LengthMap;
97 // The type of the length of the edges.
98 typedef typename _LengthMap::Value Value;
100 /// \brief Operation traits for belmann-ford algorithm.
102 /// It defines the infinity type on the given Value type
103 /// and the used operation.
104 /// \see BelmannFordDefaultOperationTraits
105 typedef BelmannFordDefaultOperationTraits<Value> OperationTraits;
107 /// \brief The type of the map that stores the last edges of the
110 /// The type of the map that stores the last
111 /// edges of the shortest paths.
112 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
114 typedef typename Graph::template NodeMap<typename _Graph::Edge> PredMap;
116 /// \brief Instantiates a PredMap.
118 /// This function instantiates a \ref PredMap.
119 /// \param G is the graph, to which we would like to define the PredMap.
120 /// \todo The graph alone may be insufficient for the initialization
121 static PredMap *createPredMap(const _Graph& graph) {
122 return new PredMap(graph);
125 /// \brief The type of the map that stores the dists of the nodes.
127 /// The type of the map that stores the dists of the nodes.
128 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
130 typedef typename Graph::template NodeMap<typename _LengthMap::Value>
133 /// \brief Instantiates a DistMap.
135 /// This function instantiates a \ref DistMap.
136 /// \param G is the graph, to which we would like to define the
138 static DistMap *createDistMap(const _Graph& graph) {
139 return new DistMap(graph);
144 /// \brief BelmannFord algorithm class.
146 /// \ingroup flowalgs
147 /// This class provides an efficient implementation of \c BelmannFord
148 /// algorithm. The edge lengths are passed to the algorithm using a
149 /// \ref concept::ReadMap "ReadMap", so it is easy to change it to any
152 /// The type of the length is determined by the
153 /// \ref concept::ReadMap::Value "Value" of the length map.
155 /// \param _Graph The graph type the algorithm runs on. The default value
156 /// is \ref ListGraph. The value of _Graph is not used directly by
157 /// BelmannFord, it is only passed to \ref BelmannFordDefaultTraits.
158 /// \param _LengthMap This read-only EdgeMap determines the lengths of the
159 /// edges. The default map type is \ref concept::StaticGraph::EdgeMap
160 /// "Graph::EdgeMap<int>". The value of _LengthMap is not used directly
161 /// by BelmannFord, it is only passed to \ref BelmannFordDefaultTraits.
162 /// \param _Traits Traits class to set various data types used by the
163 /// algorithm. The default traits class is \ref BelmannFordDefaultTraits
164 /// "BelmannFordDefaultTraits<_Graph,_LengthMap>". See \ref
165 /// BelmannFordDefaultTraits for the documentation of a BelmannFord traits
168 /// \author Balazs Dezso
171 template <typename _Graph, typename _LengthMap, typename _Traits>
173 template <typename _Graph=ListGraph,
174 typename _LengthMap=typename _Graph::template EdgeMap<int>,
175 typename _Traits=BelmannFordDefaultTraits<_Graph,_LengthMap> >
180 /// \brief \ref Exception for uninitialized parameters.
182 /// This error represents problems in the initialization
183 /// of the parameters of the algorithms.
185 class UninitializedParameter : public lemon::UninitializedParameter {
187 virtual const char* exceptionName() const {
188 return "lemon::BelmannFord::UninitializedParameter";
192 typedef _Traits Traits;
193 ///The type of the underlying graph.
194 typedef typename _Traits::Graph Graph;
196 typedef typename Graph::Node Node;
197 typedef typename Graph::NodeIt NodeIt;
198 typedef typename Graph::Edge Edge;
199 typedef typename Graph::EdgeIt EdgeIt;
201 /// \brief The type of the length of the edges.
202 typedef typename _Traits::LengthMap::Value Value;
203 /// \brief The type of the map that stores the edge lengths.
204 typedef typename _Traits::LengthMap LengthMap;
205 /// \brief The type of the map that stores the last
206 /// edges of the shortest paths.
207 typedef typename _Traits::PredMap PredMap;
208 /// \brief The type of the map that stores the dists of the nodes.
209 typedef typename _Traits::DistMap DistMap;
210 /// \brief The operation traits.
211 typedef typename _Traits::OperationTraits OperationTraits;
213 /// Pointer to the underlying graph.
215 /// Pointer to the length map
216 const LengthMap *length;
217 ///Pointer to the map of predecessors edges.
219 ///Indicates if \ref _pred is locally allocated (\c true) or not.
221 ///Pointer to the map of distances.
223 ///Indicates if \ref _dist is locally allocated (\c true) or not.
226 /// Creates the maps if necessary.
230 _pred = Traits::createPredMap(*graph);
234 _dist = Traits::createDistMap(*graph);
240 typedef BelmannFord Create;
242 /// \name Named template parameters
247 struct DefPredMapTraits : public Traits {
249 static PredMap *createPredMap(const Graph&) {
250 throw UninitializedParameter();
254 /// \brief \ref named-templ-param "Named parameter" for setting PredMap
256 /// \ref named-templ-param "Named parameter" for setting PredMap type
260 typedef BelmannFord< Graph, LengthMap, DefPredMapTraits<T> > Create;
264 struct DefDistMapTraits : public Traits {
266 static DistMap *createDistMap(const Graph& graph) {
267 throw UninitializedParameter();
271 /// \brief \ref named-templ-param "Named parameter" for setting DistMap
274 /// \ref named-templ-param "Named parameter" for setting DistMap type
278 : public BelmannFord< Graph, LengthMap, DefDistMapTraits<T> > {
279 typedef BelmannFord< Graph, LengthMap, DefDistMapTraits<T> > Create;
283 struct DefOperationTraitsTraits : public Traits {
284 typedef T OperationTraits;
287 /// \brief \ref named-templ-param "Named parameter" for setting
288 /// OperationTraits type
290 /// \ref named-templ-param "Named parameter" for setting OperationTraits
293 struct DefOperationTraits
294 : public BelmannFord< Graph, LengthMap, DefOperationTraitsTraits<T> > {
295 typedef BelmannFord< Graph, LengthMap, DefOperationTraitsTraits<T> >
307 /// \brief Constructor.
309 /// \param _graph the graph the algorithm will run on.
310 /// \param _length the length map used by the algorithm.
311 BelmannFord(const Graph& _graph, const LengthMap& _length) :
312 graph(&_graph), length(&_length),
313 _pred(0), local_pred(false),
314 _dist(0), local_dist(false) {}
318 if(local_pred) delete _pred;
319 if(local_dist) delete _dist;
322 /// \brief Sets the length map.
324 /// Sets the length map.
325 /// \return \c (*this)
326 BelmannFord &lengthMap(const LengthMap &m) {
331 /// \brief Sets the map storing the predecessor edges.
333 /// Sets the map storing the predecessor edges.
334 /// If you don't use this function before calling \ref run(),
335 /// it will allocate one. The destuctor deallocates this
336 /// automatically allocated map, of course.
337 /// \return \c (*this)
338 BelmannFord &predMap(PredMap &m) {
347 /// \brief Sets the map storing the distances calculated by the algorithm.
349 /// Sets the map storing the distances calculated by the algorithm.
350 /// If you don't use this function before calling \ref run(),
351 /// it will allocate one. The destuctor deallocates this
352 /// automatically allocated map, of course.
353 /// \return \c (*this)
354 BelmannFord &distMap(DistMap &m) {
363 /// \name Execution control
364 /// The simplest way to execute the algorithm is to use
365 /// one of the member functions called \c run(...).
367 /// If you need more control on the execution,
368 /// first you must call \ref init(), then you can add several source nodes
369 /// with \ref addSource().
370 /// Finally \ref start() will perform the actual path
375 /// \brief Initializes the internal data structures.
377 /// Initializes the internal data structures.
378 void init(const Value value = OperationTraits::infinity()) {
380 for (NodeIt it(*graph); it != INVALID; ++it) {
381 _pred->set(it, INVALID);
382 _dist->set(it, value);
386 /// \brief Adds a new source node.
388 /// The optional second parameter is the initial distance of the node.
389 /// It just sets the distance of the node to the given value.
390 void addSource(Node source, Value dst = OperationTraits::zero()) {
391 _dist->set(source, dst);
394 /// \brief Executes the algorithm.
396 /// \pre init() must be called and at least one node should be added
397 /// with addSource() before using this function.
399 /// This method runs the %BelmannFord algorithm from the root node(s)
400 /// in order to compute the shortest path to each node. The algorithm
402 /// - The shortest path tree.
403 /// - The distance of each node from the root(s).
408 for (EdgeIt it(*graph); it != INVALID; ++it) {
409 Node source = graph->source(it);
410 Node target = graph->target(it);
412 OperationTraits::plus((*_dist)[source], (*length)[it]);
413 if (OperationTraits::less(relaxed, (*_dist)[target])) {
414 _pred->set(target, it);
415 _dist->set(target, relaxed);
422 /// \brief Runs %BelmannFord algorithm from node \c s.
424 /// This method runs the %BelmannFord algorithm from a root node \c s
425 /// in order to compute the shortest path to each node. The algorithm
427 /// - The shortest path tree.
428 /// - The distance of each node from the root.
430 /// \note d.run(s) is just a shortcut of the following code.
444 /// \name Query Functions
445 /// The result of the %BelmannFord algorithm can be obtained using these
447 /// Before the use of these functions,
448 /// either run() or start() must be called.
452 /// \brief Copies the shortest path to \c t into \c p
454 /// This function copies the shortest path to \c t into \c p.
455 /// If it \c t is a source itself or unreachable, then it does not
457 /// \todo Is it the right way to handle unreachable nodes?
458 /// \return Returns \c true if a path to \c t was actually copied to \c p,
459 /// \c false otherwise.
461 template <typename Path>
462 bool getPath(Path &p, Node t) {
465 typename Path::Builder b(p);
466 for(b.setStartNode(t);pred(t)!=INVALID;t=predNode(t))
467 b.pushFront(pred(t));
474 /// \brief The distance of a node from the root.
476 /// Returns the distance of a node from the root.
477 /// \pre \ref run() must be called before using this function.
478 /// \warning If node \c v in unreachable from the root the return value
479 /// of this funcion is undefined.
480 Value dist(Node v) const { return (*_dist)[v]; }
482 /// \brief Returns the 'previous edge' of the shortest path tree.
484 /// For a node \c v it returns the 'previous edge' of the shortest path
485 /// tree, i.e. it returns the last edge of a shortest path from the root
486 /// to \c v. It is \ref INVALID if \c v is unreachable from the root or
487 /// if \c v=s. The shortest path tree used here is equal to the shortest
488 /// path tree used in \ref predNode().
489 /// \pre \ref run() must be called before using
491 /// \todo predEdge could be a better name.
492 Edge pred(Node v) const { return (*_pred)[v]; }
494 /// \brief Returns the 'previous node' of the shortest path tree.
496 /// For a node \c v it returns the 'previous node' of the shortest path
497 /// tree, i.e. it returns the last but one node from a shortest path from
498 /// the root to \c /v. It is INVALID if \c v is unreachable from the root
499 /// or if \c v=s. The shortest path tree used here is equal to the
500 /// shortest path tree used in \ref pred(). \pre \ref run() must be
501 /// called before using this function.
502 Node predNode(Node v) const {
503 return (*_pred)[v] == INVALID ? INVALID : graph->source((*_pred)[v]);
506 /// \brief Returns a reference to the NodeMap of distances.
508 /// Returns a reference to the NodeMap of distances. \pre \ref run() must
509 /// be called before using this function.
510 const DistMap &distMap() const { return *_dist;}
512 /// \brief Returns a reference to the shortest path tree map.
514 /// Returns a reference to the NodeMap of the edges of the
515 /// shortest path tree.
516 /// \pre \ref run() must be called before using this function.
517 const PredMap &predMap() const { return *_pred; }
519 /// \brief Checks if a node is reachable from the root.
521 /// Returns \c true if \c v is reachable from the root.
522 /// \pre \ref run() must be called before using this function.
524 bool reached(Node v) { return (*_dist)[v] != OperationTraits::infinity(); }
529 /// \brief Default traits class of BelmannFord function.
531 /// Default traits class of BelmannFord function.
532 /// \param _Graph Graph type.
533 /// \param _LengthMap Type of length map.
534 template <typename _Graph, typename _LengthMap>
535 struct BelmannFordWizardDefaultTraits {
536 /// \brief The graph type the algorithm runs on.
537 typedef _Graph Graph;
539 /// \brief The type of the map that stores the edge lengths.
541 /// The type of the map that stores the edge lengths.
542 /// It must meet the \ref concept::ReadMap "ReadMap" concept.
543 typedef _LengthMap LengthMap;
545 /// \brief The value type of the length map.
546 typedef typename _LengthMap::Value Value;
548 /// \brief Operation traits for belmann-ford algorithm.
550 /// It defines the infinity type on the given Value type
551 /// and the used operation.
552 /// \see BelmannFordDefaultOperationTraits
553 typedef BelmannFordDefaultOperationTraits<Value> OperationTraits;
555 /// \brief The type of the map that stores the last
556 /// edges of the shortest paths.
558 /// The type of the map that stores the last
559 /// edges of the shortest paths.
560 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
561 typedef NullMap <typename _Graph::Node,typename _Graph::Edge> PredMap;
563 /// \brief Instantiates a PredMap.
565 /// This function instantiates a \ref PredMap.
566 static PredMap *createPredMap(const _Graph &) {
567 return new PredMap();
569 /// \brief The type of the map that stores the dists of the nodes.
571 /// The type of the map that stores the dists of the nodes.
572 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
573 typedef NullMap<typename Graph::Node, Value> DistMap;
574 /// \brief Instantiates a DistMap.
576 /// This function instantiates a \ref DistMap.
577 static DistMap *createDistMap(const _Graph &) {
578 return new DistMap();
582 /// \brief Default traits used by \ref BelmannFordWizard
584 /// To make it easier to use BelmannFord algorithm
585 /// we have created a wizard class.
586 /// This \ref BelmannFordWizard class needs default traits,
587 /// as well as the \ref BelmannFord class.
588 /// The \ref BelmannFordWizardBase is a class to be the default traits of the
589 /// \ref BelmannFordWizard class.
590 /// \todo More named parameters are required...
591 template<class _Graph,class _LengthMap>
592 class BelmannFordWizardBase
593 : public BelmannFordWizardDefaultTraits<_Graph,_LengthMap> {
595 typedef BelmannFordWizardDefaultTraits<_Graph,_LengthMap> Base;
597 /// Type of the nodes in the graph.
598 typedef typename Base::Graph::Node Node;
600 /// Pointer to the underlying graph.
602 /// Pointer to the length map
604 ///Pointer to the map of predecessors edges.
606 ///Pointer to the map of distances.
608 ///Pointer to the source node.
614 /// This constructor does not require parameters, therefore it initiates
615 /// all of the attributes to default values (0, INVALID).
616 BelmannFordWizardBase() : _graph(0), _length(0), _pred(0),
617 _dist(0), _source(INVALID) {}
621 /// This constructor requires some parameters,
622 /// listed in the parameters list.
623 /// Others are initiated to 0.
624 /// \param graph is the initial value of \ref _graph
625 /// \param length is the initial value of \ref _length
626 /// \param source is the initial value of \ref _source
627 BelmannFordWizardBase(const _Graph& graph,
628 const _LengthMap& length,
629 Node source = INVALID) :
630 _graph((void *)&graph), _length((void *)&length), _pred(0),
631 _dist(0), _source(source) {}
635 /// A class to make the usage of BelmannFord algorithm easier
637 /// This class is created to make it easier to use BelmannFord algorithm.
638 /// It uses the functions and features of the plain \ref BelmannFord,
639 /// but it is much simpler to use it.
641 /// Simplicity means that the way to change the types defined
642 /// in the traits class is based on functions that returns the new class
643 /// and not on templatable built-in classes.
644 /// When using the plain \ref BelmannFord
645 /// the new class with the modified type comes from
646 /// the original class by using the ::
647 /// operator. In the case of \ref BelmannFordWizard only
648 /// a function have to be called and it will
649 /// return the needed class.
651 /// It does not have own \ref run method. When its \ref run method is called
652 /// it initiates a plain \ref BelmannFord class, and calls the \ref
653 /// BelmannFord::run method of it.
654 template<class _Traits>
655 class BelmannFordWizard : public _Traits {
656 typedef _Traits Base;
658 ///The type of the underlying graph.
659 typedef typename _Traits::Graph Graph;
661 typedef typename Graph::Node Node;
662 typedef typename Graph::NodeIt NodeIt;
663 typedef typename Graph::Edge Edge;
664 typedef typename Graph::OutEdgeIt EdgeIt;
666 ///The type of the map that stores the edge lengths.
667 typedef typename _Traits::LengthMap LengthMap;
669 ///The type of the length of the edges.
670 typedef typename LengthMap::Value Value;
672 ///\brief The type of the map that stores the last
673 ///edges of the shortest paths.
674 typedef typename _Traits::PredMap PredMap;
676 ///The type of the map that stores the dists of the nodes.
677 typedef typename _Traits::DistMap DistMap;
681 BelmannFordWizard() : _Traits() {}
683 /// \brief Constructor that requires parameters.
685 /// Constructor that requires parameters.
686 /// These parameters will be the default values for the traits class.
687 BelmannFordWizard(const Graph& graph, const LengthMap& length,
688 Node source = INVALID)
689 : _Traits(graph, length, source) {}
691 /// \brief Copy constructor
692 BelmannFordWizard(const _Traits &b) : _Traits(b) {}
694 ~BelmannFordWizard() {}
696 /// \brief Runs BelmannFord algorithm from a given node.
698 /// Runs BelmannFord algorithm from a given node.
699 /// The node can be given by the \ref source function.
701 if(Base::_source == INVALID) throw UninitializedParameter();
702 BelmannFord<Graph,LengthMap,_Traits>
703 bf(*(Graph*)Base::_graph, *(LengthMap*)Base::_length);
704 if (Base::_pred) bf.predMap(*(PredMap*)Base::_pred);
705 if (Base::_dist) bf.distMap(*(DistMap*)Base::_dist);
706 bf.run(Base::_source);
709 /// \brief Runs BelmannFord algorithm from the given node.
711 /// Runs BelmannFord algorithm from the given node.
712 /// \param s is the given source.
713 void run(Node source) {
714 Base::_source = source;
719 struct DefPredMapBase : public Base {
721 static PredMap *createPredMap(const Graph &) { return 0; };
722 DefPredMapBase(const _Traits &b) : _Traits(b) {}
725 ///\brief \ref named-templ-param "Named parameter"
726 ///function for setting PredMap type
728 /// \ref named-templ-param "Named parameter"
729 ///function for setting PredMap type
732 BelmannFordWizard<DefPredMapBase<T> > predMap(const T &t)
734 Base::_pred=(void *)&t;
735 return BelmannFordWizard<DefPredMapBase<T> >(*this);
739 struct DefDistMapBase : public Base {
741 static DistMap *createDistMap(const Graph &) { return 0; };
742 DefDistMapBase(const _Traits &b) : _Traits(b) {}
745 ///\brief \ref named-templ-param "Named parameter"
746 ///function for setting DistMap type
748 /// \ref named-templ-param "Named parameter"
749 ///function for setting DistMap type
752 BelmannFordWizard<DefDistMapBase<T> > distMap(const T &t) {
753 Base::_dist=(void *)&t;
754 return BelmannFordWizard<DefDistMapBase<T> >(*this);
758 struct DefOperationTraitsBase : public Base {
759 typedef T OperationTraits;
760 DefOperationTraitsBase(const _Traits &b) : _Traits(b) {}
763 ///\brief \ref named-templ-param "Named parameter"
764 ///function for setting OperationTraits type
766 /// \ref named-templ-param "Named parameter"
767 ///function for setting OperationTraits type
770 BelmannFordWizard<DefOperationTraitsBase<T> > distMap() {
771 return BelmannFordWizard<DefDistMapBase<T> >(*this);
774 /// \brief Sets the source node, from which the BelmannFord algorithm runs.
776 /// Sets the source node, from which the BelmannFord algorithm runs.
777 /// \param s is the source node.
778 BelmannFordWizard<_Traits>& source(Node source) {
779 Base::_source = source;
785 /// \brief Function type interface for BelmannFord algorithm.
787 /// \ingroup flowalgs
788 /// Function type interface for BelmannFord algorithm.
790 /// This function also has several \ref named-templ-func-param
791 /// "named parameters", they are declared as the members of class
792 /// \ref BelmannFordWizard.
794 /// example shows how to use these parameters.
796 /// belmannford(g,length,source).predMap(preds).run();
798 /// \warning Don't forget to put the \ref BelmannFordWizard::run() "run()"
799 /// to the end of the parameter list.
800 /// \sa BelmannFordWizard
802 template<class _Graph, class _LengthMap>
803 BelmannFordWizard<BelmannFordWizardBase<_Graph,_LengthMap> >
804 belmannFord(const _Graph& graph,
805 const _LengthMap& length,
806 typename _Graph::Node source = INVALID) {
807 return BelmannFordWizard<BelmannFordWizardBase<_Graph,_LengthMap> >
808 (graph, length, source);
811 } //END OF NAMESPACE LEMON