COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/floyd_warshall.h @ 2064:2c5f81b35269

Last change on this file since 2064:2c5f81b35269 was 2042:bdc953f2a449, checked in by Balazs Dezso, 14 years ago

New Algorithm group for matchings

LaTeX formulas
Bug fix => /\f$ will cause parsing error in doxygen

File size: 18.8 KB
Line 
1/* -*- C++ -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library
4 *
5 * Copyright (C) 2003-2006
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
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.
12 *
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
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_FLOYD_WARSHALL_H
20#define LEMON_FLOYD_WARSHALL_H
21
22///\ingroup flowalgs
23/// \file
24/// \brief FloydWarshall algorithm.
25///
26
27#include <lemon/list_graph.h>
28#include <lemon/graph_utils.h>
29#include <lemon/bits/invalid.h>
30#include <lemon/error.h>
31#include <lemon/matrix_maps.h>
32#include <lemon/maps.h>
33
34#include <limits>
35
36namespace lemon {
37
38  /// \brief Default OperationTraits for the FloydWarshall algorithm class.
39  /// 
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
44  /// infinity value.
45  template <
46    typename Value,
47    bool has_infinity = std::numeric_limits<Value>::has_infinity>
48  struct FloydWarshallDefaultOperationTraits {
49    /// \brief Gives back the zero value of the type.
50    static Value zero() {
51      return static_cast<Value>(0);
52    }
53    /// \brief Gives back the positive infinity value of the type.
54    static Value infinity() {
55      return std::numeric_limits<Value>::infinity();
56    }
57    /// \brief Gives back the sum of the given two elements.
58    static Value plus(const Value& left, const Value& right) {
59      return left + right;
60    }
61    /// \brief Gives back true only if the first value less than the second.
62    static bool less(const Value& left, const Value& right) {
63      return left < right;
64    }
65  };
66
67  template <typename Value>
68  struct FloydWarshallDefaultOperationTraits<Value, false> {
69    static Value zero() {
70      return static_cast<Value>(0);
71    }
72    static Value infinity() {
73      return std::numeric_limits<Value>::max();
74    }
75    static Value plus(const Value& left, const Value& right) {
76      if (left == infinity() || right == infinity()) return infinity();
77      return left + right;
78    }
79    static bool less(const Value& left, const Value& right) {
80      return left < right;
81    }
82  };
83 
84  /// \brief Default traits class of FloydWarshall class.
85  ///
86  /// Default traits class of FloydWarshall class.
87  /// \param _Graph Graph type.
88  /// \param _LegthMap Type of length map.
89  template<class _Graph, class _LengthMap>
90  struct FloydWarshallDefaultTraits {
91    /// The graph type the algorithm runs on.
92    typedef _Graph Graph;
93
94    /// \brief The type of the map that stores the edge lengths.
95    ///
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;
99
100    // The type of the length of the edges.
101    typedef typename _LengthMap::Value Value;
102
103    /// \brief Operation traits for floyd-warshall algorithm.
104    ///
105    /// It defines the infinity type on the given Value type
106    /// and the used operation.
107    /// \see FloydWarshallDefaultOperationTraits
108    typedef FloydWarshallDefaultOperationTraits<Value> OperationTraits;
109 
110    /// \brief The type of the matrix map that stores the last edges of the
111    /// shortest paths.
112    ///
113    /// The type of the map that stores the last edges of the shortest paths.
114    /// It must be a matrix map with \c Graph::Edge value type.
115    ///
116    typedef DynamicMatrixMap<Graph, typename Graph::Node,
117                             typename Graph::Edge> PredMap;
118
119    /// \brief Instantiates a PredMap.
120    ///
121    /// This function instantiates a \ref PredMap.
122    /// \param graph is the graph,
123    /// to which we would like to define the PredMap.
124    /// \todo The graph alone may be insufficient for the initialization
125    static PredMap *createPredMap(const _Graph& graph) {
126      return new PredMap(graph);
127    }
128
129    /// \brief The type of the map that stores the dists of the nodes.
130    ///
131    /// The type of the map that stores the dists of the nodes.
132    /// It must meet the \ref concept::WriteMatrixMap "WriteMatrixMap" concept.
133    ///
134    typedef DynamicMatrixMap<Graph, typename Graph::Node, Value> DistMap;
135
136    /// \brief Instantiates a DistMap.
137    ///
138    /// This function instantiates a \ref DistMap.
139    /// \param graph is the graph, to which we would like to define the
140    /// \ref DistMap
141    static DistMap *createDistMap(const _Graph& graph) {
142      return new DistMap(graph);
143    }
144
145  };
146 
147  /// \brief %FloydWarshall algorithm class.
148  ///
149  /// \ingroup flowalgs
150  /// This class provides an efficient implementation of \c Floyd-Warshall
151  /// algorithm. The edge lengths are passed to the algorithm using a
152  /// \ref concept::ReadMap "ReadMap", so it is easy to change it to any
153  /// kind of length.
154  ///
155  /// The algorithm solves the shortest path problem for each pair
156  /// of node when the edges can have negative length but the graph should
157  /// not contain cycles with negative sum of length. If we can assume
158  /// that all edge is non-negative in the graph then the dijkstra algorithm
159  /// should be used from each node rather and if the graph is sparse and
160  /// there are negative circles then the johnson algorithm.
161  ///
162  /// The complexity of this algorithm is \f$ O(n^3+e) \f$.
163  ///
164  /// The type of the length is determined by the
165  /// \ref concept::ReadMap::Value "Value" of the length map.
166  ///
167  /// \param _Graph The graph type the algorithm runs on. The default value
168  /// is \ref ListGraph. The value of _Graph is not used directly by
169  /// FloydWarshall, it is only passed to \ref FloydWarshallDefaultTraits.
170  /// \param _LengthMap This read-only EdgeMap determines the lengths of the
171  /// edges. It is read once for each edge, so the map may involve in
172  /// relatively time consuming process to compute the edge length if
173  /// it is necessary. The default map type is \ref
174  /// concept::StaticGraph::EdgeMap "Graph::EdgeMap<int>".  The value
175  /// of _LengthMap is not used directly by FloydWarshall, it is only passed
176  /// to \ref FloydWarshallDefaultTraits.  \param _Traits Traits class to set
177  /// various data types used by the algorithm.  The default traits
178  /// class is \ref FloydWarshallDefaultTraits
179  /// "FloydWarshallDefaultTraits<_Graph,_LengthMap>".  See \ref
180  /// FloydWarshallDefaultTraits for the documentation of a FloydWarshall
181  /// traits class.
182  ///
183  /// \author Balazs Dezso
184
185#ifdef DOXYGEN
186  template <typename _Graph, typename _LengthMap typename _Traits >
187#else
188  template <typename _Graph=ListGraph,
189            typename _LengthMap=typename _Graph::template EdgeMap<int>,
190            typename _Traits=FloydWarshallDefaultTraits<_Graph,_LengthMap> >
191#endif
192  class FloydWarshall {
193  public:
194   
195    /// \brief \ref Exception for uninitialized parameters.
196    ///
197    /// This error represents problems in the initialization
198    /// of the parameters of the algorithms.
199
200    class UninitializedParameter : public lemon::UninitializedParameter {
201    public:
202      virtual const char* exceptionName() const {
203        return "lemon::FloydWarshall::UninitializedParameter";
204      }
205    };
206
207    typedef _Traits Traits;
208    ///The type of the underlying graph.
209    typedef typename _Traits::Graph Graph;
210
211    typedef typename Graph::Node Node;
212    typedef typename Graph::NodeIt NodeIt;
213    typedef typename Graph::Edge Edge;
214    typedef typename Graph::EdgeIt EdgeIt;
215   
216    /// \brief The type of the length of the edges.
217    typedef typename _Traits::LengthMap::Value Value;
218    /// \brief The type of the map that stores the edge lengths.
219    typedef typename _Traits::LengthMap LengthMap;
220    /// \brief The type of the map that stores the last
221    /// edges of the shortest paths. The type of the PredMap
222    /// is a matrix map for Edges
223    typedef typename _Traits::PredMap PredMap;
224    /// \brief The type of the map that stores the dists of the nodes.
225    /// The type of the DistMap is a matrix map for Values
226    typedef typename _Traits::DistMap DistMap;
227    /// \brief The operation traits.
228    typedef typename _Traits::OperationTraits OperationTraits;
229  private:
230    /// Pointer to the underlying graph.
231    const Graph *graph;
232    /// Pointer to the length map
233    const LengthMap *length;
234    ///Pointer to the map of predecessors edges.
235    PredMap *_pred;
236    ///Indicates if \ref _pred is locally allocated (\c true) or not.
237    bool local_pred;
238    ///Pointer to the map of distances.
239    DistMap *_dist;
240    ///Indicates if \ref _dist is locally allocated (\c true) or not.
241    bool local_dist;
242
243    /// Creates the maps if necessary.
244    void create_maps() {
245      if(!_pred) {
246        local_pred = true;
247        _pred = Traits::createPredMap(*graph);
248      }
249      if(!_dist) {
250        local_dist = true;
251        _dist = Traits::createDistMap(*graph);
252      }
253    }
254   
255  public :
256 
257    /// \name Named template parameters
258
259    ///@{
260
261    template <class T>
262    struct DefPredMapTraits : public Traits {
263      typedef T PredMap;
264      static PredMap *createPredMap(const Graph& graph) {
265        throw UninitializedParameter();
266      }
267    };
268
269    /// \brief \ref named-templ-param "Named parameter" for setting PredMap
270    /// type
271    /// \ref named-templ-param "Named parameter" for setting PredMap type
272    ///
273    template <class T>
274    struct DefPredMap
275      : public FloydWarshall< Graph, LengthMap, DefPredMapTraits<T> > {
276      typedef FloydWarshall< Graph, LengthMap, DefPredMapTraits<T> > Create;
277    };
278   
279    template <class T>
280    struct DefDistMapTraits : public Traits {
281      typedef T DistMap;
282      static DistMap *createDistMap(const Graph& graph) {
283        throw UninitializedParameter();
284      }
285    };
286    /// \brief \ref named-templ-param "Named parameter" for setting DistMap
287    /// type
288    ///
289    /// \ref named-templ-param "Named parameter" for setting DistMap type
290    ///
291    template <class T>
292    struct DefDistMap
293      : public FloydWarshall< Graph, LengthMap, DefDistMapTraits<T> > {
294      typedef FloydWarshall< Graph, LengthMap, DefDistMapTraits<T> > Create;
295    };
296   
297    template <class T>
298    struct DefOperationTraitsTraits : public Traits {
299      typedef T OperationTraits;
300    };
301   
302    /// \brief \ref named-templ-param "Named parameter" for setting
303    /// OperationTraits type
304    ///
305    /// \ref named-templ-param "Named parameter" for setting PredMap type
306    template <class T>
307    struct DefOperationTraits
308      : public FloydWarshall< Graph, LengthMap, DefOperationTraitsTraits<T> > {
309      typedef FloydWarshall< Graph, LengthMap, DefOperationTraitsTraits<T> >
310      Create;
311    };
312   
313    ///@}
314
315  protected:
316
317    FloydWarshall() {}
318
319  public:     
320
321    typedef FloydWarshall Create;
322   
323    /// \brief Constructor.
324    ///
325    /// \param _graph the graph the algorithm will run on.
326    /// \param _length the length map used by the algorithm.
327    FloydWarshall(const Graph& _graph, const LengthMap& _length) :
328      graph(&_graph), length(&_length),
329      _pred(0), local_pred(false),
330      _dist(0), local_dist(false) {}
331   
332    ///Destructor.
333    ~FloydWarshall() {
334      if(local_pred) delete _pred;
335      if(local_dist) delete _dist;
336    }
337
338    /// \brief Sets the length map.
339    ///
340    /// Sets the length map.
341    /// \return \c (*this)
342    FloydWarshall &lengthMap(const LengthMap &m) {
343      length = &m;
344      return *this;
345    }
346
347    /// \brief Sets the map storing the predecessor edges.
348    ///
349    /// Sets the map storing the predecessor edges.
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    FloydWarshall &predMap(PredMap &m) {
355      if(local_pred) {
356        delete _pred;
357        local_pred=false;
358      }
359      _pred = &m;
360      return *this;
361    }
362
363    /// \brief Sets the map storing the distances calculated by the algorithm.
364    ///
365    /// Sets the map storing the distances calculated by the algorithm.
366    /// If you don't use this function before calling \ref run(),
367    /// it will allocate one. The destuctor deallocates this
368    /// automatically allocated map, of course.
369    /// \return \c (*this)
370    FloydWarshall &distMap(DistMap &m) {
371      if(local_dist) {
372        delete _dist;
373        local_dist=false;
374      }
375      _dist = &m;
376      return *this;
377    }
378
379    ///\name Execution control
380    /// The simplest way to execute the algorithm is to use
381    /// one of the member functions called \c run(...).
382    /// \n
383    /// If you need more control on the execution,
384    /// Finally \ref start() will perform the actual path
385    /// computation.
386
387    ///@{
388
389    /// \brief Initializes the internal data structures.
390    ///
391    /// Initializes the internal data structures.
392    void init() {
393      create_maps();
394      for (NodeIt it(*graph); it != INVALID; ++it) {
395        for (NodeIt jt(*graph); jt != INVALID; ++jt) {
396          _pred->set(it, jt, INVALID);
397          _dist->set(it, jt, OperationTraits::infinity());
398        }
399        _dist->set(it, it, OperationTraits::zero());
400      }
401      for (EdgeIt it(*graph); it != INVALID; ++it) {
402        Node source = graph->source(it);
403        Node target = graph->target(it);       
404        if (OperationTraits::less((*length)[it], (*_dist)(source, target))) {
405          _dist->set(source, target, (*length)[it]);
406          _pred->set(source, target, it);
407        }
408      }
409    }
410   
411    /// \brief Executes the algorithm.
412    ///
413    /// This method runs the %FloydWarshall algorithm in order to compute
414    /// the shortest path to each node pairs. The algorithm
415    /// computes
416    /// - The shortest path tree for each node.
417    /// - The distance between each node pairs.
418    void start() {
419      for (NodeIt kt(*graph); kt != INVALID; ++kt) {
420        for (NodeIt it(*graph); it != INVALID; ++it) {
421          for (NodeIt jt(*graph); jt != INVALID; ++jt) {
422            Value relaxed = OperationTraits::plus((*_dist)(it, kt),
423                                                  (*_dist)(kt, jt));
424            if (OperationTraits::less(relaxed, (*_dist)(it, jt))) {
425              _dist->set(it, jt, relaxed);
426              _pred->set(it, jt, (*_pred)(kt, jt));
427            }
428          }
429        }
430      }
431    }
432
433    /// \brief Executes the algorithm and checks the negative cycles.
434    ///
435    /// This method runs the %FloydWarshall algorithm in order to compute
436    /// the shortest path to each node pairs. If there is a negative cycle
437    /// in the graph it gives back false.
438    /// The algorithm computes
439    /// - The shortest path tree for each node.
440    /// - The distance between each node pairs.
441    bool checkedStart() {
442      start();
443      for (NodeIt it(*graph); it != INVALID; ++it) {
444        if (OperationTraits::less((*dist)(it, it), OperationTraits::zero())) {
445          return false;
446        }
447      }
448      return true;
449    }
450   
451    /// \brief Runs %FloydWarshall algorithm.
452    ///   
453    /// This method runs the %FloydWarshall algorithm from a each node
454    /// in order to compute the shortest path to each node pairs.
455    /// The algorithm computes
456    /// - The shortest path tree for each node.
457    /// - The distance between each node pairs.
458    ///
459    /// \note d.run(s) is just a shortcut of the following code.
460    ///\code
461    ///  d.init();
462    ///  d.start();
463    ///\endcode
464    void run() {
465      init();
466      start();
467    }
468   
469    ///@}
470
471    /// \name Query Functions
472    /// The result of the %FloydWarshall algorithm can be obtained using these
473    /// functions.\n
474    /// Before the use of these functions,
475    /// either run() or start() must be called.
476   
477    ///@{
478
479    /// \brief Copies the shortest path to \c t into \c p
480    ///   
481    /// This function copies the shortest path to \c t into \c p.
482    /// If it \c t is a source itself or unreachable, then it does not
483    /// alter \c p.
484    /// \return Returns \c true if a path to \c t was actually copied to \c p,
485    /// \c false otherwise.
486    /// \sa DirPath
487    template <typename Path>
488    bool getPath(Path &p, Node source, Node target) {
489      if (connected(source, target)) {
490        p.clear();
491        typename Path::Builder b(target);
492        for(b.setStartNode(target); predEdge(source, target) != INVALID;
493            target = predNode(target)) {
494          b.pushFront(predEdge(source, target));
495        }
496        b.commit();
497        return true;
498      }
499      return false;
500    }
501         
502    /// \brief The distance between two nodes.
503    ///
504    /// Returns the distance between two nodes.
505    /// \pre \ref run() must be called before using this function.
506    /// \warning If node \c v in unreachable from the root the return value
507    /// of this funcion is undefined.
508    Value dist(Node source, Node target) const {
509      return (*_dist)(source, target);
510    }
511
512    /// \brief Returns the 'previous edge' of the shortest path tree.
513    ///
514    /// For the node \c node it returns the 'previous edge' of the shortest
515    /// path tree to direction of the node \c root
516    /// i.e. it returns the last edge of a shortest path from the node \c root
517    /// to \c node. It is \ref INVALID if \c node is unreachable from the root
518    /// or if \c node=root. The shortest path tree used here is equal to the
519    /// shortest path tree used in \ref predNode().
520    /// \pre \ref run() must be called before using this function.
521    Edge predEdge(Node root, Node node) const {
522      return (*_pred)(root, node);
523    }
524
525    /// \brief Returns the 'previous node' of the shortest path tree.
526    ///
527    /// For a node \c node it returns the 'previous node' of the shortest path
528    /// tree to direction of the node \c root, i.e. it returns the last but
529    /// one node from a shortest path from the \c root to \c node. It is
530    /// INVALID if \c node is unreachable from the root or if \c node=root.
531    /// The shortest path tree used here is equal to the
532    /// shortest path tree used in \ref predEdge(). 
533    /// \pre \ref run() must be called before using this function.
534    Node predNode(Node root, Node node) const {
535      return (*_pred)(root, node) == INVALID ?
536      INVALID : graph->source((*_pred)(root, node));
537    }
538   
539    /// \brief Returns a reference to the matrix node map of distances.
540    ///
541    /// Returns a reference to the matrix node map of distances.
542    ///
543    /// \pre \ref run() must be called before using this function.
544    const DistMap &distMap() const { return *_dist;}
545 
546    /// \brief Returns a reference to the shortest path tree map.
547    ///
548    /// Returns a reference to the matrix node map of the edges of the
549    /// shortest path tree.
550    /// \pre \ref run() must be called before using this function.
551    const PredMap &predMap() const { return *_pred;}
552 
553    /// \brief Checks if a node is reachable from the root.
554    ///
555    /// Returns \c true if \c v is reachable from the root.
556    /// \pre \ref run() must be called before using this function.
557    ///
558    bool connected(Node source, Node target) {
559      return (*_dist)(source, target) != OperationTraits::infinity();
560    }
561   
562    ///@}
563  };
564 
565} //END OF NAMESPACE LEMON
566
567#endif
568
Note: See TracBrowser for help on using the repository browser.