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
170 template <typename _Graph=ListGraph,
171 typename _LengthMap=typename _Graph::template EdgeMap<int>,
172 typename _Traits=BelmannFordDefaultTraits<_Graph,_LengthMap> >
176 /// \brief \ref Exception for uninitialized parameters.
178 /// This error represents problems in the initialization
179 /// of the parameters of the algorithms.
181 class UninitializedParameter : public lemon::UninitializedParameter {
183 virtual const char* exceptionName() const {
184 return "lemon::BelmannFord::UninitializedParameter";
188 typedef _Traits Traits;
189 ///The type of the underlying graph.
190 typedef typename _Traits::Graph Graph;
192 typedef typename Graph::Node Node;
193 typedef typename Graph::NodeIt NodeIt;
194 typedef typename Graph::Edge Edge;
195 typedef typename Graph::EdgeIt EdgeIt;
197 /// \brief The type of the length of the edges.
198 typedef typename _Traits::LengthMap::Value Value;
199 /// \brief The type of the map that stores the edge lengths.
200 typedef typename _Traits::LengthMap LengthMap;
201 /// \brief The type of the map that stores the last
202 /// edges of the shortest paths.
203 typedef typename _Traits::PredMap PredMap;
204 /// \brief The type of the map that stores the dists of the nodes.
205 typedef typename _Traits::DistMap DistMap;
206 /// \brief The operation traits.
207 typedef typename _Traits::OperationTraits OperationTraits;
209 /// Pointer to the underlying graph.
211 /// Pointer to the length map
212 const LengthMap *length;
213 ///Pointer to the map of predecessors edges.
215 ///Indicates if \ref _pred is locally allocated (\c true) or not.
217 ///Pointer to the map of distances.
219 ///Indicates if \ref _dist is locally allocated (\c true) or not.
222 /// Creates the maps if necessary.
226 _pred = Traits::createPredMap(*graph);
230 _dist = Traits::createDistMap(*graph);
236 /// \name Named template parameters
241 struct DefPredMapTraits : public Traits {
243 static PredMap *createPredMap(const Graph& graph) {
244 throw UninitializedParameter();
248 /// \brief \ref named-templ-param "Named parameter" for setting PredMap
250 /// \ref named-templ-param "Named parameter" for setting PredMap type
254 : public BelmannFord< Graph, LengthMap, DefPredMapTraits<T> > {};
257 struct DefDistMapTraits : public Traits {
259 static DistMap *createDistMap(const Graph& graph) {
260 throw UninitializedParameter();
264 /// \brief \ref named-templ-param "Named parameter" for setting DistMap
267 /// \ref named-templ-param "Named parameter" for setting DistMap type
271 : public BelmannFord< Graph, LengthMap, DefDistMapTraits<T> > {};
274 struct DefOperationTraitsTraits : public Traits {
275 typedef T OperationTraits;
278 /// \brief \ref named-templ-param "Named parameter" for setting
279 /// OperationTraits type
281 /// \ref named-templ-param "Named parameter" for setting PredMap type
283 class DefOperationTraits
284 : public BelmannFord< Graph, LengthMap, DefOperationTraitsTraits<T> > {
286 typedef BelmannFord< Graph, LengthMap, DefOperationTraitsTraits<T> >
294 /// \brief Constructor.
296 /// \param _graph the graph the algorithm will run on.
297 /// \param _length the length map used by the algorithm.
298 BelmannFord(const Graph& _graph, const LengthMap& _length) :
299 graph(&_graph), length(&_length),
300 _pred(0), local_pred(false),
301 _dist(0), local_dist(false) {}
305 if(local_pred) delete _pred;
306 if(local_dist) delete _dist;
309 /// \brief Sets the length map.
311 /// Sets the length map.
312 /// \return \c (*this)
313 BelmannFord &lengthMap(const LengthMap &m) {
318 /// \brief Sets the map storing the predecessor edges.
320 /// Sets the map storing the predecessor edges.
321 /// If you don't use this function before calling \ref run(),
322 /// it will allocate one. The destuctor deallocates this
323 /// automatically allocated map, of course.
324 /// \return \c (*this)
325 BelmannFord &predMap(PredMap &m) {
334 /// \brief Sets the map storing the distances calculated by the algorithm.
336 /// Sets the map storing the distances calculated by the algorithm.
337 /// If you don't use this function before calling \ref run(),
338 /// it will allocate one. The destuctor deallocates this
339 /// automatically allocated map, of course.
340 /// \return \c (*this)
341 BelmannFord &distMap(DistMap &m) {
350 /// \name Execution control
351 /// The simplest way to execute the algorithm is to use
352 /// one of the member functions called \c run(...).
354 /// If you need more control on the execution,
355 /// first you must call \ref init(), then you can add several source nodes
356 /// with \ref addSource().
357 /// Finally \ref start() will perform the actual path
362 /// \brief Initializes the internal data structures.
364 /// Initializes the internal data structures.
367 for (NodeIt it(*graph); it != INVALID; ++it) {
368 _pred->set(it, INVALID);
369 _dist->set(it, OperationTraits::infinity());
373 /// \brief Adds a new source node.
375 /// The optional second parameter is the initial distance of the node.
376 /// It just sets the distance of the node to the given value.
377 void addSource(Node source, Value dst = OperationTraits::zero()) {
378 _dist->set(source, dst);
381 /// \brief Executes the algorithm.
383 /// \pre init() must be called and at least one node should be added
384 /// with addSource() before using this function.
386 /// This method runs the %BelmannFord algorithm from the root node(s)
387 /// in order to compute the shortest path to each node. The algorithm
389 /// - The shortest path tree.
390 /// - The distance of each node from the root(s).
395 for (EdgeIt it(*graph); it != INVALID; ++it) {
396 Node source = graph->source(it);
397 Node target = graph->target(it);
399 OperationTraits::plus((*_dist)[source], (*length)[it]);
400 if (OperationTraits::less(relaxed, (*_dist)[target])) {
401 _pred->set(target, it);
402 _dist->set(target, relaxed);
409 /// \brief Runs %BelmannFord algorithm from node \c s.
411 /// This method runs the %BelmannFord algorithm from a root node \c s
412 /// in order to compute the shortest path to each node. The algorithm
414 /// - The shortest path tree.
415 /// - The distance of each node from the root.
417 /// \note d.run(s) is just a shortcut of the following code.
431 /// \name Query Functions
432 /// The result of the %BelmannFord algorithm can be obtained using these
434 /// Before the use of these functions,
435 /// either run() or start() must be called.
439 /// \brief Copies the shortest path to \c t into \c p
441 /// This function copies the shortest path to \c t into \c p.
442 /// If it \c t is a source itself or unreachable, then it does not
444 /// \todo Is it the right way to handle unreachable nodes?
445 /// \return Returns \c true if a path to \c t was actually copied to \c p,
446 /// \c false otherwise.
448 template <typename Path>
449 bool getPath(Path &p, Node t) {
452 typename Path::Builder b(p);
453 for(b.setStartNode(t);pred(t)!=INVALID;t=predNode(t))
454 b.pushFront(pred(t));
461 /// \brief The distance of a node from the root.
463 /// Returns the distance of a node from the root.
464 /// \pre \ref run() must be called before using this function.
465 /// \warning If node \c v in unreachable from the root the return value
466 /// of this funcion is undefined.
467 Value dist(Node v) const { return (*_dist)[v]; }
469 /// \brief Returns the 'previous edge' of the shortest path tree.
471 /// For a node \c v it returns the 'previous edge' of the shortest path
472 /// tree, i.e. it returns the last edge of a shortest path from the root
473 /// to \c v. It is \ref INVALID if \c v is unreachable from the root or
474 /// if \c v=s. The shortest path tree used here is equal to the shortest
475 /// path tree used in \ref predNode().
476 /// \pre \ref run() must be called before using
478 /// \todo predEdge could be a better name.
479 Edge pred(Node v) const { return (*_pred)[v]; }
481 /// \brief Returns the 'previous node' of the shortest path tree.
483 /// For a node \c v it returns the 'previous node' of the shortest path
484 /// tree, i.e. it returns the last but one node from a shortest path from
485 /// the root to \c /v. It is INVALID if \c v is unreachable from the root
486 /// or if \c v=s. The shortest path tree used here is equal to the
487 /// shortest path tree used in \ref pred(). \pre \ref run() must be
488 /// called before using this function.
489 Node predNode(Node v) const {
490 return (*_pred)[v] == INVALID ? INVALID : graph->source((*_pred)[v]);
493 /// \brief Returns a reference to the NodeMap of distances.
495 /// Returns a reference to the NodeMap of distances. \pre \ref run() must
496 /// be called before using this function.
497 const DistMap &distMap() const { return *_dist;}
499 /// \brief Returns a reference to the shortest path tree map.
501 /// Returns a reference to the NodeMap of the edges of the
502 /// shortest path tree.
503 /// \pre \ref run() must be called before using this function.
504 const PredMap &predMap() const { return *_pred; }
506 /// \brief Checks if a node is reachable from the root.
508 /// Returns \c true if \c v is reachable from the root.
509 /// \pre \ref run() must be called before using this function.
511 bool reached(Node v) { return (*_dist)[v] != OperationTraits::infinity(); }
516 /// \brief Default traits class of BelmannFord function.
518 /// Default traits class of BelmannFord function.
519 /// \param _Graph Graph type.
520 /// \param _LengthMap Type of length map.
521 template <typename _Graph, typename _LengthMap>
522 struct BelmannFordWizardDefaultTraits {
523 /// \brief The graph type the algorithm runs on.
524 typedef _Graph Graph;
526 /// \brief The type of the map that stores the edge lengths.
528 /// The type of the map that stores the edge lengths.
529 /// It must meet the \ref concept::ReadMap "ReadMap" concept.
530 typedef _LengthMap LengthMap;
532 /// \brief The value type of the length map.
533 typedef typename _LengthMap::Value Value;
535 /// \brief Operation traits for belmann-ford algorithm.
537 /// It defines the infinity type on the given Value type
538 /// and the used operation.
539 /// \see BelmannFordDefaultOperationTraits
540 typedef BelmannFordDefaultOperationTraits<Value> OperationTraits;
542 /// \brief The type of the map that stores the last
543 /// edges of the shortest paths.
545 /// The type of the map that stores the last
546 /// edges of the shortest paths.
547 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
548 typedef NullMap <typename _Graph::Node,typename _Graph::Edge> PredMap;
550 /// \brief Instantiates a PredMap.
552 /// This function instantiates a \ref PredMap.
553 static PredMap *createPredMap(const _Graph &) {
554 return new PredMap();
556 /// \brief The type of the map that stores the dists of the nodes.
558 /// The type of the map that stores the dists of the nodes.
559 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
560 typedef NullMap<typename Graph::Node, Value> DistMap;
561 /// \brief Instantiates a DistMap.
563 /// This function instantiates a \ref DistMap.
564 static DistMap *createDistMap(const _Graph &) {
565 return new DistMap();
569 /// \brief Default traits used by \ref BelmannFordWizard
571 /// To make it easier to use BelmannFord algorithm
572 /// we have created a wizard class.
573 /// This \ref BelmannFordWizard class needs default traits,
574 /// as well as the \ref BelmannFord class.
575 /// The \ref BelmannFordWizardBase is a class to be the default traits of the
576 /// \ref BelmannFordWizard class.
577 /// \todo More named parameters are required...
578 template<class _Graph,class _LengthMap>
579 class BelmannFordWizardBase
580 : public BelmannFordWizardDefaultTraits<_Graph,_LengthMap> {
582 typedef BelmannFordWizardDefaultTraits<_Graph,_LengthMap> Base;
584 /// Type of the nodes in the graph.
585 typedef typename Base::Graph::Node Node;
587 /// Pointer to the underlying graph.
589 /// Pointer to the length map
591 ///Pointer to the map of predecessors edges.
593 ///Pointer to the map of distances.
595 ///Pointer to the source node.
601 /// This constructor does not require parameters, therefore it initiates
602 /// all of the attributes to default values (0, INVALID).
603 BelmannFordWizardBase() : _graph(0), _length(0), _pred(0),
604 _dist(0), _source(INVALID) {}
608 /// This constructor requires some parameters,
609 /// listed in the parameters list.
610 /// Others are initiated to 0.
611 /// \param graph is the initial value of \ref _graph
612 /// \param length is the initial value of \ref _length
613 /// \param source is the initial value of \ref _source
614 BelmannFordWizardBase(const _Graph& graph,
615 const _LengthMap& length,
616 Node source = INVALID) :
617 _graph((void *)&graph), _length((void *)&length), _pred(0),
618 _dist(0), _source(source) {}
622 /// A class to make the usage of BelmannFord algorithm easier
624 /// This class is created to make it easier to use BelmannFord algorithm.
625 /// It uses the functions and features of the plain \ref BelmannFord,
626 /// but it is much simpler to use it.
628 /// Simplicity means that the way to change the types defined
629 /// in the traits class is based on functions that returns the new class
630 /// and not on templatable built-in classes.
631 /// When using the plain \ref BelmannFord
632 /// the new class with the modified type comes from
633 /// the original class by using the ::
634 /// operator. In the case of \ref BelmannFordWizard only
635 /// a function have to be called and it will
636 /// return the needed class.
638 /// It does not have own \ref run method. When its \ref run method is called
639 /// it initiates a plain \ref BelmannFord class, and calls the \ref
640 /// BelmannFord::run method of it.
641 template<class _Traits>
642 class BelmannFordWizard : public _Traits {
643 typedef _Traits Base;
645 ///The type of the underlying graph.
646 typedef typename _Traits::Graph Graph;
648 typedef typename Graph::Node Node;
649 typedef typename Graph::NodeIt NodeIt;
650 typedef typename Graph::Edge Edge;
651 typedef typename Graph::OutEdgeIt EdgeIt;
653 ///The type of the map that stores the edge lengths.
654 typedef typename _Traits::LengthMap LengthMap;
656 ///The type of the length of the edges.
657 typedef typename LengthMap::Value Value;
659 ///\brief The type of the map that stores the last
660 ///edges of the shortest paths.
661 typedef typename _Traits::PredMap PredMap;
663 ///The type of the map that stores the dists of the nodes.
664 typedef typename _Traits::DistMap DistMap;
668 BelmannFordWizard() : _Traits() {}
670 /// \brief Constructor that requires parameters.
672 /// Constructor that requires parameters.
673 /// These parameters will be the default values for the traits class.
674 BelmannFordWizard(const Graph& graph, const LengthMap& length,
675 Node source = INVALID)
676 : _Traits(graph, length, source) {}
678 /// \brief Copy constructor
679 BelmannFordWizard(const _Traits &b) : _Traits(b) {}
681 ~BelmannFordWizard() {}
683 /// \brief Runs BelmannFord algorithm from a given node.
685 /// Runs BelmannFord algorithm from a given node.
686 /// The node can be given by the \ref source function.
688 if(Base::_source == INVALID) throw UninitializedParameter();
689 BelmannFord<Graph,LengthMap,_Traits>
690 bf(*(Graph*)Base::_graph, *(LengthMap*)Base::_length);
691 if (Base::_pred) bf.predMap(*(PredMap*)Base::_pred);
692 if (Base::_dist) bf.distMap(*(DistMap*)Base::_dist);
693 bf.run(Base::_source);
696 /// \brief Runs BelmannFord algorithm from the given node.
698 /// Runs BelmannFord algorithm from the given node.
699 /// \param s is the given source.
700 void run(Node source) {
701 Base::_source = source;
706 struct DefPredMapBase : public Base {
708 static PredMap *createPredMap(const Graph &) { return 0; };
709 DefPredMapBase(const _Traits &b) : _Traits(b) {}
712 ///\brief \ref named-templ-param "Named parameter"
713 ///function for setting PredMap type
715 /// \ref named-templ-param "Named parameter"
716 ///function for setting PredMap type
719 BelmannFordWizard<DefPredMapBase<T> > predMap(const T &t)
721 Base::_pred=(void *)&t;
722 return BelmannFordWizard<DefPredMapBase<T> >(*this);
726 struct DefDistMapBase : public Base {
728 static DistMap *createDistMap(const Graph &) { return 0; };
729 DefDistMapBase(const _Traits &b) : _Traits(b) {}
732 ///\brief \ref named-templ-param "Named parameter"
733 ///function for setting DistMap type
735 /// \ref named-templ-param "Named parameter"
736 ///function for setting DistMap type
739 BelmannFordWizard<DefDistMapBase<T> > distMap(const T &t) {
740 Base::_dist=(void *)&t;
741 return BelmannFordWizard<DefDistMapBase<T> >(*this);
744 /// \brief Sets the source node, from which the BelmannFord algorithm runs.
746 /// Sets the source node, from which the BelmannFord algorithm runs.
747 /// \param s is the source node.
748 BelmannFordWizard<_Traits>& source(Node source) {
749 Base::_source = source;
755 /// \brief Function type interface for BelmannFord algorithm.
757 /// \ingroup flowalgs
758 /// Function type interface for BelmannFord algorithm.
760 /// This function also has several \ref named-templ-func-param
761 /// "named parameters", they are declared as the members of class
762 /// \ref BelmannFordWizard.
764 /// example shows how to use these parameters.
766 /// belmannford(g,length,source).predMap(preds).run();
768 /// \warning Don't forget to put the \ref BelmannFordWizard::run() "run()"
769 /// to the end of the parameter list.
770 /// \sa BelmannFordWizard
772 template<class _Graph, class _LengthMap>
773 BelmannFordWizard<BelmannFordWizardBase<_Graph,_LengthMap> >
774 belmannFord(const _Graph& graph,
775 const _LengthMap& length,
776 typename _Graph::Node source = INVALID) {
777 return BelmannFordWizard<BelmannFordWizardBase<_Graph,_LengthMap> >
778 (graph, length, source);
781 } //END OF NAMESPACE LEMON