2 * lemon/johnson.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_JOHNSON_H
18 #define LEMON_JOHNSON_H
22 /// \brief Johnson algorithm.
25 #include <lemon/list_graph.h>
26 #include <lemon/graph_utils.h>
27 #include <lemon/dfs.h>
28 #include <lemon/dijkstra.h>
29 #include <lemon/belmann_ford.h>
30 #include <lemon/invalid.h>
31 #include <lemon/error.h>
32 #include <lemon/maps.h>
38 /// \brief Default OperationTraits for the Johnson algorithm class.
40 /// It defines all computational operations and constants which are
41 /// used in the Floyd-Warshall algorithm. The default implementation
42 /// is based on the numeric_limits class. If the numeric type does not
43 /// have infinity value then the maximum value is used as extremal
47 bool has_infinity = std::numeric_limits<Value>::has_infinity>
48 struct JohnsonDefaultOperationTraits {
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 true only if the first value less than the second.
62 static bool less(const Value& left, const Value& right) {
67 template <typename Value>
68 struct JohnsonDefaultOperationTraits<Value, false> {
70 return static_cast<Value>(0);
72 static Value infinity() {
73 return std::numeric_limits<Value>::max();
75 static Value plus(const Value& left, const Value& right) {
76 if (left == infinity() || right == infinity()) return infinity();
79 static bool less(const Value& left, const Value& right) {
84 /// \brief Default traits class of Johnson class.
86 /// Default traits class of Johnson class.
87 /// \param _Graph Graph type.
88 /// \param _LegthMap Type of length map.
89 template<class _Graph, class _LengthMap>
90 struct JohnsonDefaultTraits {
91 /// The graph type the algorithm runs on.
94 /// \brief The type of the map that stores the edge lengths.
96 /// The type of the map that stores the edge lengths.
97 /// It must meet the \ref concept::ReadMap "ReadMap" concept.
98 typedef _LengthMap LengthMap;
100 // The type of the length of the edges.
101 typedef typename _LengthMap::Value Value;
103 /// \brief Operation traits for belmann-ford algorithm.
105 /// It defines the infinity type on the given Value type
106 /// and the used operation.
107 /// \see JohnsonDefaultOperationTraits
108 typedef JohnsonDefaultOperationTraits<Value> OperationTraits;
110 /// \brief The type of the map that stores the last edges of the
113 /// The type of the map that stores the last
114 /// edges of the shortest paths.
115 /// It must be a matrix map with \c Graph::Edge value type.
117 typedef NodeMatrixMap<Graph, typename Graph::Edge> PredMap;
119 /// \brief Instantiates a PredMap.
121 /// This function instantiates a \ref PredMap.
122 /// \param G is the graph, to which we would like to define the PredMap.
123 /// \todo The graph alone may be insufficient for the initialization
124 static PredMap *createPredMap(const _Graph& graph) {
125 return new PredMap(graph);
128 /// \brief The type of the map that stores the dists of the nodes.
130 /// The type of the map that stores the dists of the nodes.
131 /// It must meet the \ref concept::WriteMap "WriteMap" concept.
133 typedef NodeMatrixMap<Graph, Value> DistMap;
135 /// \brief Instantiates a DistMap.
137 /// This function instantiates a \ref DistMap.
138 /// \param G is the graph, to which we would like to define the
140 static DistMap *createDistMap(const _Graph& graph) {
141 return new DistMap(graph);
146 /// \brief Johnson algorithm class.
148 /// \ingroup flowalgs
149 /// This class provides an efficient implementation of \c Johnson
150 /// algorithm. The edge lengths are passed to the algorithm using a
151 /// \ref concept::ReadMap "ReadMap", so it is easy to change it to any
154 /// The type of the length is determined by the
155 /// \ref concept::ReadMap::Value "Value" of the length map.
157 /// \param _Graph The graph type the algorithm runs on. The default value
158 /// is \ref ListGraph. The value of _Graph is not used directly by
159 /// Johnson, it is only passed to \ref JohnsonDefaultTraits.
160 /// \param _LengthMap This read-only EdgeMap determines the lengths of the
161 /// edges. It is read once for each edge, so the map may involve in
162 /// relatively time consuming process to compute the edge length if
163 /// it is necessary. The default map type is \ref
164 /// concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>". The value
165 /// of _LengthMap is not used directly by Johnson, it is only passed
166 /// to \ref JohnsonDefaultTraits. \param _Traits Traits class to set
167 /// various data types used by the algorithm. The default traits
168 /// class is \ref JohnsonDefaultTraits
169 /// "JohnsonDefaultTraits<_Graph,_LengthMap>". See \ref
170 /// JohnsonDefaultTraits for the documentation of a Johnson traits
173 /// \author Balazs Dezso
175 template <typename _Graph=ListGraph,
176 typename _LengthMap=typename _Graph::template EdgeMap<int>,
177 typename _Traits=JohnsonDefaultTraits<_Graph,_LengthMap> >
181 /// \brief \ref Exception for uninitialized parameters.
183 /// This error represents problems in the initialization
184 /// of the parameters of the algorithms.
186 class UninitializedParameter : public lemon::UninitializedParameter {
188 virtual const char* exceptionName() const {
189 return "lemon::Johnson::UninitializedParameter";
193 typedef _Traits Traits;
194 ///The type of the underlying graph.
195 typedef typename _Traits::Graph Graph;
197 typedef typename Graph::Node Node;
198 typedef typename Graph::NodeIt NodeIt;
199 typedef typename Graph::Edge Edge;
200 typedef typename Graph::EdgeIt EdgeIt;
202 /// \brief The type of the length of the edges.
203 typedef typename _Traits::LengthMap::Value Value;
204 /// \brief The type of the map that stores the edge lengths.
205 typedef typename _Traits::LengthMap LengthMap;
206 /// \brief The type of the map that stores the last
207 /// edges of the shortest paths. The type of the PredMap
208 /// is a matrix map for Edges
209 typedef typename _Traits::PredMap PredMap;
210 /// \brief The type of the map that stores the dists of the nodes.
211 /// The type of the DistMap is a matrix map for Values
212 typedef typename _Traits::DistMap DistMap;
213 /// \brief The operation traits.
214 typedef typename _Traits::OperationTraits OperationTraits;
216 /// Pointer to the underlying graph.
218 /// Pointer to the length map
219 const LengthMap *length;
220 ///Pointer to the map of predecessors edges.
222 ///Indicates if \ref _pred is locally allocated (\c true) or not.
224 ///Pointer to the map of distances.
226 ///Indicates if \ref _dist is locally allocated (\c true) or not.
229 /// Creates the maps if necessary.
233 _pred = Traits::createPredMap(*graph);
237 _dist = Traits::createDistMap(*graph);
243 /// \name Named template parameters
248 struct DefPredMapTraits : public Traits {
250 static PredMap *createPredMap(const Graph& graph) {
251 throw UninitializedParameter();
255 /// \brief \ref named-templ-param "Named parameter" for setting PredMap
257 /// \ref named-templ-param "Named parameter" for setting PredMap type
261 : public Johnson< Graph, LengthMap, DefPredMapTraits<T> > {};
264 struct DefDistMapTraits : public Traits {
266 static DistMap *createDistMap(const Graph& graph) {
267 throw UninitializedParameter();
270 /// \brief \ref named-templ-param "Named parameter" for setting DistMap
273 /// \ref named-templ-param "Named parameter" for setting DistMap type
277 : public Johnson< Graph, LengthMap, DefDistMapTraits<T> > {};
280 struct DefOperationTraitsTraits : public Traits {
281 typedef T OperationTraits;
284 /// \brief \ref named-templ-param "Named parameter" for setting
285 /// OperationTraits type
287 /// \ref named-templ-param "Named parameter" for setting PredMap type
289 class DefOperationTraits
290 : public Johnson< Graph, LengthMap, DefOperationTraitsTraits<T> > {};
296 /// \brief Constructor.
298 /// \param _graph the graph the algorithm will run on.
299 /// \param _length the length map used by the algorithm.
300 Johnson(const Graph& _graph, const LengthMap& _length) :
301 graph(&_graph), length(&_length),
302 _pred(0), local_pred(false),
303 _dist(0), local_dist(false) {}
307 if(local_pred) delete _pred;
308 if(local_dist) delete _dist;
311 /// \brief Sets the length map.
313 /// Sets the length map.
314 /// \return \c (*this)
315 Johnson &lengthMap(const LengthMap &m) {
320 /// \brief Sets the map storing the predecessor edges.
322 /// Sets the map storing the predecessor edges.
323 /// If you don't use this function before calling \ref run(),
324 /// it will allocate one. The destuctor deallocates this
325 /// automatically allocated map, of course.
326 /// \return \c (*this)
327 Johnson &predMap(PredMap &m) {
336 /// \brief Sets the map storing the distances calculated by the algorithm.
338 /// Sets the map storing the distances calculated by the algorithm.
339 /// If you don't use this function before calling \ref run(),
340 /// it will allocate one. The destuctor deallocates this
341 /// automatically allocated map, of course.
342 /// \return \c (*this)
343 Johnson &distMap(DistMap &m) {
352 ///\name Execution control
353 /// The simplest way to execute the algorithm is to use
354 /// one of the member functions called \c run(...).
356 /// If you need more control on the execution,
357 /// Finally \ref start() will perform the actual path
362 /// \brief Initializes the internal data structures.
364 /// Initializes the internal data structures.
369 /// \brief Executes the algorithm.
371 /// This method runs the %Johnson algorithm in order to compute
372 /// the shortest path to each node pairs. The algorithm
374 /// - The shortest path tree for each node.
375 /// - The distance between each node pairs.
377 typename BelmannFord<Graph, LengthMap>::
378 template DefOperationTraits<OperationTraits>::
379 BelmannFord belmannford(*graph, *length);
383 typename Graph::template NodeMap<bool> initial(*graph, false);
386 Dfs<Graph> dfs(*graph);
389 for (NodeIt it(*graph); it != INVALID; ++it) {
390 if (!dfs.reached(it)) {
392 while (!dfs.emptyQueue()) {
393 Edge edge = dfs.processNextEdge();
394 initial.set(graph->target(edge), false);
396 initial.set(it, true);
399 for (NodeIt it(*graph); it != INVALID; ++it) {
401 belmannford.addSource(it);
408 for (NodeIt it(*graph); it != INVALID; ++it) {
409 typedef PotentialDifferenceMap<Graph,
410 typename BelmannFord<Graph, LengthMap>::DistMap> PotDiffMap;
411 PotDiffMap potdiff(*graph, belmannford.distMap());
412 typedef SubMap<LengthMap, PotDiffMap> ShiftLengthMap;
413 ShiftLengthMap shiftlen(*length, potdiff);
414 Dijkstra<Graph, ShiftLengthMap> dijkstra(*graph, shiftlen);
416 for (NodeIt jt(*graph); jt != INVALID; ++jt) {
417 if (dijkstra.reached(jt)) {
418 _dist->set(it, jt, dijkstra.dist(jt) +
419 belmannford.dist(jt) - belmannford.dist(it));
420 _pred->set(it, jt, dijkstra.pred(jt));
422 _dist->set(it, jt, OperationTraits::infinity());
423 _pred->set(it, jt, INVALID);
429 /// \brief Runs %Johnson algorithm.
431 /// This method runs the %Johnson algorithm from a each node
432 /// in order to compute the shortest path to each node pairs.
433 /// The algorithm computes
434 /// - The shortest path tree for each node.
435 /// - The distance between each node pairs.
437 /// \note d.run(s) is just a shortcut of the following code.
449 /// \name Query Functions
450 /// The result of the %Johnson algorithm can be obtained using these
452 /// Before the use of these functions,
453 /// either run() or start() must be called.
457 /// \brief Copies the shortest path to \c t into \c p
459 /// This function copies the shortest path to \c t into \c p.
460 /// If it \c t is a source itself or unreachable, then it does not
462 /// \todo Is it the right way to handle unreachable nodes?
463 /// \return Returns \c true if a path to \c t was actually copied to \c p,
464 /// \c false otherwise.
466 template <typename Path>
467 bool getPath(Path &p, Node source, Node target) {
468 if (connected(source, target)) {
470 typename Path::Builder b(target);
471 for(b.setStartNode(target); pred(source, target) != INVALID;
472 target = predNode(target)) {
473 b.pushFront(pred(source, target));
481 /// \brief The distance between two nodes.
483 /// Returns the distance between two nodes.
484 /// \pre \ref run() must be called before using this function.
485 /// \warning If node \c v in unreachable from the root the return value
486 /// of this funcion is undefined.
487 Value dist(Node source, Node target) const {
488 return (*_dist)(source, target);
491 /// \brief Returns the 'previous edge' of the shortest path tree.
493 /// For the node \c node it returns the 'previous edge' of the shortest
494 /// path tree to direction of the node \c root
495 /// i.e. it returns the last edge of a shortest path from the node \c root
496 /// to \c node. It is \ref INVALID if \c node is unreachable from the root
497 /// or if \c node=root. The shortest path tree used here is equal to the
498 /// shortest path tree used in \ref predNode().
499 /// \pre \ref run() must be called before using this function.
500 /// \todo predEdge could be a better name.
501 Edge pred(Node root, Node node) const {
502 return (*_pred)(root, node);
505 /// \brief Returns the 'previous node' of the shortest path tree.
507 /// For a node \c node it returns the 'previous node' of the shortest path
508 /// tree to direction of the node \c root, i.e. it returns the last but
509 /// one node from a shortest path from the \c root to \c node. It is
510 /// INVALID if \c node is unreachable from the root or if \c node=root.
511 /// The shortest path tree used here is equal to the
512 /// shortest path tree used in \ref pred().
513 /// \pre \ref run() must be called before using this function.
514 Node predNode(Node root, Node node) const {
515 return (*_pred)(root, node) == INVALID ?
516 INVALID : graph->source((*_pred)(root, node));
519 /// \brief Returns a reference to the matrix node map of distances.
521 /// Returns a reference to the matrix node map of distances.
523 /// \pre \ref run() must be called before using this function.
524 const DistMap &distMap() const { return *_dist;}
526 /// \brief Returns a reference to the shortest path tree map.
528 /// Returns a reference to the matrix node map of the edges of the
529 /// shortest path tree.
530 /// \pre \ref run() must be called before using this function.
531 const PredMap &predMap() const { return *_pred;}
533 /// \brief Checks if a node is reachable from the root.
535 /// Returns \c true if \c v is reachable from the root.
536 /// \pre \ref run() must be called before using this function.
538 bool connected(Node source, Node target) {
539 return (*_dist)(source, target) != OperationTraits::infinity();
545 } //END OF NAMESPACE LEMON