COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dag_shortest_path.h @ 1950:a1a6f5b788bd

Last change on this file since 1950:a1a6f5b788bd was 1946:17eb3eaad9f8, checked in by Alpar Juttner, 18 years ago
  • workaround for a Doxygen 1.4.6 bug
  • other doc fixes
File size: 37.5 KB
Line 
1/* -*- C++ -*-
2 * lemon/dag_shortest_path.h - Part of LEMON, a generic C++ optimization library
3 *
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
6 *
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.
10 *
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
13 * purpose.
14 *
15 */
16
17#ifndef LEMON_DAG_SHORTEST_PATH_H
18#define LEMON_DAG_SHORTEST_PATH_H
19
20///\ingroup flowalgs
21/// \file
22/// \brief DagShortestPath algorithm.
23///
24
25#include <lemon/list_graph.h>
26#include <lemon/invalid.h>
27#include <lemon/error.h>
28#include <lemon/maps.h>
29#include <lemon/topology.h>
30
31#include <limits>
32
33namespace lemon {
34
35  /// \brief Default OperationTraits for the DagShortestPath algorithm class.
36  /// 
37  /// It defines all computational operations and constants which are
38  /// used in the dag shortest path 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
41  /// infinity value.
42  template <
43    typename Value,
44    bool has_infinity = std::numeric_limits<Value>::has_infinity>
45  struct DagShortestPathDefaultOperationTraits {
46    /// \brief Gives back the zero value of the type.
47    static Value zero() {
48      return static_cast<Value>(0);
49    }
50    /// \brief Gives back the positive infinity value of the type.
51    static Value infinity() {
52      return std::numeric_limits<Value>::infinity();
53    }
54    /// \brief Gives back the sum of the given two elements.
55    static Value plus(const Value& left, const Value& right) {
56      return left + right;
57    }
58    /// \brief Gives back true only if the first value less than the second.
59    static bool less(const Value& left, const Value& right) {
60      return left < right;
61    }
62  };
63
64  template <typename Value>
65  struct DagShortestPathDefaultOperationTraits<Value, false> {
66    static Value zero() {
67      return static_cast<Value>(0);
68    }
69    static Value infinity() {
70      return std::numeric_limits<Value>::max();
71    }
72    static Value plus(const Value& left, const Value& right) {
73      if (left == infinity() || right == infinity()) return infinity();
74      return left + right;
75    }
76    static bool less(const Value& left, const Value& right) {
77      return left < right;
78    }
79  };
80 
81  /// \brief Default traits class of DagShortestPath class.
82  ///
83  /// Default traits class of DagShortestPath class.
84  /// \param _Graph Graph type.
85  /// \param _LegthMap Type of length map.
86  template<class _Graph, class _LengthMap>
87  struct DagShortestPathDefaultTraits {
88    /// The graph type the algorithm runs on.
89    typedef _Graph Graph;
90
91    /// \brief The type of the map that stores the edge lengths.
92    ///
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;
96
97    // The type of the length of the edges.
98    typedef typename _LengthMap::Value Value;
99
100    /// \brief Operation traits for dag shortest path algorithm.
101    ///
102    /// It defines the infinity type on the given Value type
103    /// and the used operation.
104    /// \see DagShortestPathDefaultOperationTraits
105    typedef DagShortestPathDefaultOperationTraits<Value> OperationTraits;
106 
107    /// \brief The type of the map that stores the last edges of the
108    /// shortest paths.
109    ///
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.
113    ///
114    typedef typename Graph::template NodeMap<typename _Graph::Edge> PredMap;
115
116    /// \brief Instantiates a PredMap.
117    ///
118    /// This function instantiates a \ref PredMap.
119    /// \param graph is the graph, to which we would
120    /// like to define the PredMap.
121    /// \todo The graph alone may be insufficient for the initialization
122    static PredMap *createPredMap(const _Graph& graph) {
123      return new PredMap(graph);
124    }
125
126    /// \brief The type of the map that stores the dists of the nodes.
127    ///
128    /// The type of the map that stores the dists of the nodes.
129    /// It must meet the \ref concept::WriteMap "WriteMap" concept.
130    ///
131    typedef typename Graph::template NodeMap<typename _LengthMap::Value>
132    DistMap;
133
134    /// \brief Instantiates a DistMap.
135    ///
136    /// This function instantiates a \ref DistMap.
137    /// \param graph is the graph, to which we would like to define the
138    /// \ref DistMap
139    static DistMap *createDistMap(const _Graph& graph) {
140      return new DistMap(graph);
141    }
142
143  };
144 
145  /// \brief Inverse OperationTraits for the DagShortestPath algorithm class.
146  ///
147  /// It defines all computational operations and constants which are
148  /// used in the dag shortest path algorithm. It is the inverse of
149  /// \ref DagShortestPathDefaultOperationTraits, so it can be used to
150  /// calculate the longest path. The default implementation
151  /// is based on the numeric_limits class. If the numeric type does not
152  /// have infinity value then the minimum value is used as extremal
153  /// infinity value.
154  template <
155    typename Value,
156    bool has_infinity = std::numeric_limits<Value>::has_infinity>
157  struct DagLongestPathOperationTraits {
158    /// \brief Gives back the zero value of the type.
159    static Value zero() {
160      return static_cast<Value>(0);
161    }
162    /// \brief Gives back the negative infinity value of the type.
163    static Value infinity() {
164      return -(std::numeric_limits<Value>::infinity());
165    }
166    /// \brief Gives back the sum of the given two elements.
167    static Value plus(const Value& left, const Value& right) {
168      return left + right;
169    }
170    /// \brief Gives back true only if the first value less than the second.
171    static bool less(const Value& left, const Value& right) {
172      return left > right;
173    }
174  };
175
176  template <typename Value>
177  struct DagLongestPathOperationTraits<Value, false> {
178    static Value zero() {
179      return static_cast<Value>(0);
180    }
181    static Value infinity() {
182      return std::numeric_limits<Value>::min();
183    }
184    static Value plus(const Value& left, const Value& right) {
185      if (left == infinity() || right == infinity()) return infinity();
186      return left + right;
187    }
188    static bool less(const Value& left, const Value& right) {
189      return left > right;
190    }
191  };
192
193  /// \brief Inverse traits class of DagShortestPath class.
194  ///
195  /// Inverse traits class of DagShortestPath class.
196  /// \param _Graph Graph type.
197  /// \param _LegthMap Type of length map.
198  template<class _Graph, class _LengthMap>
199  struct DagLongestPathTraits {
200    /// The graph type the algorithm runs on.
201    typedef _Graph Graph;
202
203    /// \brief The type of the map that stores the edge lengths.
204    ///
205    /// The type of the map that stores the edge lengths.
206    /// It must meet the \ref concept::ReadMap "ReadMap" concept.
207    typedef _LengthMap LengthMap;
208
209    // The type of the length of the edges.
210    typedef typename _LengthMap::Value Value;
211
212    /// \brief Inverse operation traits for dag shortest path algorithm.
213    ///
214    /// It defines the infinity type on the given Value type
215    /// and the used operation.
216    /// \see DagLongestPathOperationTraits
217    typedef DagLongestPathOperationTraits<Value> OperationTraits;
218 
219    /// \brief The type of the map that stores the last edges of the
220    /// longest paths.
221    ///
222    /// The type of the map that stores the last
223    /// edges of the longest paths.
224    /// It must meet the \ref concept::WriteMap "WriteMap" concept.
225    ///
226    typedef typename Graph::template NodeMap<typename _Graph::Edge> PredMap;
227
228    /// \brief Instantiates a PredMap.
229    ///
230    /// This function instantiates a \ref PredMap.
231    /// \param graph is the graph,
232    /// to which we would like to define the PredMap.
233    /// \todo The graph alone may be insufficient for the initialization
234    static PredMap *createPredMap(const _Graph& graph) {
235      return new PredMap(graph);
236    }
237
238    /// \brief The type of the map that stores the dists of the nodes.
239    ///
240    /// The type of the map that stores the dists of the nodes.
241    /// It must meet the \ref concept::WriteMap "WriteMap" concept.
242    ///
243    typedef typename Graph::template NodeMap<typename _LengthMap::Value>
244    DistMap;
245
246    /// \brief Instantiates a DistMap.
247    ///
248    /// This function instantiates a \ref DistMap.
249    /// \param graph is the graph, to which we would like to define the
250    /// \ref DistMap
251    static DistMap *createDistMap(const _Graph& graph) {
252      return new DistMap(graph);
253    }
254
255  };
256 
257
258  /// \brief %DagShortestPath algorithm class.
259  ///
260  /// \ingroup flowalgs
261  /// This class provides an efficient implementation of a Dag sortest path
262  /// searching algorithm. The edge lengths are passed to the algorithm
263  /// using a \ref concept::ReadMap "ReadMap", so it is easy to change it
264  /// to any kind of length.
265  ///
266  /// The complexity of the algorithm is O(n + e).
267  ///
268  /// The type of the length is determined by the
269  /// \ref concept::ReadMap::Value "Value" of the length map.
270  ///
271  /// \param _Graph The graph type the algorithm runs on. The default value
272  /// is \ref ListGraph. The value of _Graph is not used directly by
273  /// DagShortestPath, it is only passed to \ref DagShortestPathDefaultTraits.
274  /// \param _LengthMap This read-only EdgeMap determines the lengths of the
275  /// edges. The default map type is \ref concept::StaticGraph::EdgeMap
276  /// "Graph::EdgeMap<int>".  The value of _LengthMap is not used directly
277  /// by DagShortestPath, it is only passed to \ref DagShortestPathDefaultTraits. 
278  /// \param _Traits Traits class to set various data types used by the
279  /// algorithm.  The default traits class is \ref DagShortestPathDefaultTraits
280  /// "DagShortestPathDefaultTraits<_Graph,_LengthMap>".  See \ref
281  /// DagShortestPathDefaultTraits for the documentation of a DagShortestPath traits
282  /// class.
283  ///
284  /// \author Balazs Attila Mihaly (based on Balazs Dezso's work)
285
286#ifdef DOXYGEN
287  template <typename _Graph, typename _LengthMap, typename _Traits>
288#else
289  template <typename _Graph=ListGraph,
290            typename _LengthMap=typename _Graph::template EdgeMap<int>,
291            typename _Traits=DagShortestPathDefaultTraits<_Graph,_LengthMap> >
292#endif
293  class DagShortestPath {
294  public:
295   
296    /// \brief \ref Exception for uninitialized parameters.
297    ///
298    /// This error represents problems in the initialization
299    /// of the parameters of the algorithms.
300
301    class UninitializedParameter : public lemon::UninitializedParameter {
302    public:
303      virtual const char* exceptionName() const {
304        return "lemon::DagShortestPath::UninitializedParameter";
305      }
306    };
307
308    typedef _Traits Traits;
309    ///The type of the underlying graph.
310    typedef typename _Traits::Graph Graph;
311
312    typedef typename Graph::Node Node;
313    typedef typename Graph::NodeIt NodeIt;
314    typedef typename Graph::Edge Edge;
315    typedef typename Graph::EdgeIt EdgeIt;
316    typedef typename Graph::OutEdgeIt OutEdgeIt;
317   
318    /// \brief The type of the length of the edges.
319    typedef typename _Traits::LengthMap::Value Value;
320    /// \brief The type of the map that stores the edge lengths.
321    typedef typename _Traits::LengthMap LengthMap;
322    /// \brief The type of the map that stores the last
323    /// edges of the shortest paths.
324    typedef typename _Traits::PredMap PredMap;
325    /// \brief The type of the map that stores the dists of the nodes.
326    typedef typename _Traits::DistMap DistMap;
327    /// \brief The operation traits.
328    typedef typename _Traits::OperationTraits OperationTraits;
329    /// \brief The Node weight map.
330    typedef typename Graph::NodeMap<Value> WeightMap;
331  private:
332    /// Pointer to the underlying graph
333    const Graph *graph;
334    /// Pointer to the length map
335    const LengthMap *length;
336    ///Pointer to the map of predecessors edges
337    PredMap *_pred;
338    ///Indicates if \ref _pred is locally allocated (\c true) or not
339    bool local_pred;
340    ///Pointer to the map of distances
341    DistMap *_dist;
342    ///Indicates if \ref _dist is locally allocated (\c true) or not
343    bool local_dist;
344    ///Process step counter
345    unsigned int _process_step;
346
347    std::vector<Node> _node_order;
348
349    /// Creates the maps if necessary.
350    void create_maps() {
351      if(!_pred) {
352        local_pred = true;
353        _pred = Traits::createPredMap(*graph);
354      }
355      if(!_dist) {
356        local_dist = true;
357        _dist = Traits::createDistMap(*graph);
358      }
359    }
360   
361  public :
362 
363    typedef DagShortestPath Create;
364
365    /// \name Named template parameters
366
367    ///@{
368
369    template <class T>
370    struct DefPredMapTraits : public Traits {
371      typedef T PredMap;
372      static PredMap *createPredMap(const Graph&) {
373        throw UninitializedParameter();
374      }
375    };
376
377    /// \brief \ref named-templ-param "Named parameter" for setting PredMap
378    /// type
379    /// \ref named-templ-param "Named parameter" for setting PredMap type
380    ///
381    template <class T>
382    struct DefPredMap {
383      typedef DagShortestPath< Graph, LengthMap, DefPredMapTraits<T> > Create;
384    };
385   
386    template <class T>
387    struct DefDistMapTraits : public Traits {
388      typedef T DistMap;
389      static DistMap *createDistMap(const Graph& graph) {
390        throw UninitializedParameter();
391      }
392    };
393
394    /// \brief \ref named-templ-param "Named parameter" for setting DistMap
395    /// type
396    ///
397    /// \ref named-templ-param "Named parameter" for setting DistMap type
398    ///
399    template <class T>
400    struct DefDistMap
401      : public DagShortestPath< Graph, LengthMap, DefDistMapTraits<T> > {
402      typedef DagShortestPath< Graph, LengthMap, DefDistMapTraits<T> > Create;
403    };
404   
405    template <class T>
406    struct DefOperationTraitsTraits : public Traits {
407      typedef T OperationTraits;
408    };
409   
410    /// \brief \ref named-templ-param "Named parameter" for setting
411    /// OperationTraits type
412    ///
413    /// \ref named-templ-param "Named parameter" for setting OperationTraits
414    /// type
415    template <class T>
416    struct DefOperationTraits
417      : public DagShortestPath< Graph, LengthMap, DefOperationTraitsTraits<T> > {
418      typedef DagShortestPath< Graph, LengthMap, DefOperationTraitsTraits<T> >
419      Create;
420    };
421   
422    ///@}
423
424  protected:
425   
426    DagShortestPath() {}
427
428  public:     
429   
430    /// \brief Constructor.
431    ///
432    /// \param _graph the graph the algorithm will run on.
433    /// \param _length the length map used by the algorithm.
434    DagShortestPath(const Graph& _graph, const LengthMap& _length) :
435      graph(&_graph), length(&_length),
436      _pred(0), local_pred(false),
437      _dist(0), local_dist(false){}
438
439    /// \brief Constructor with node weight map.
440    ///
441    /// \param _graph the graph the algorithm will run on.
442    /// \param _length the length map used by the algorithm.
443    /// The NodeMap _length will be used as the weight map.
444    /// Each edge will have the weight of its target node.
445    DagShortestPath(const Graph& _graph, const WeightMap& _length) :
446      graph(&_graph),
447      _pred(0), local_pred(false),
448      _dist(0), local_dist(false){
449      length=new LengthMap(_graph);
450      _dist=new DistMap(_graph);
451      for(EdgeIt eit(_graph);eit!=INVALID;++eit)
452        (const_cast<LengthMap*>(length))->set(eit,_length[_graph.target(eit)]);
453      }
454
455    ///Destructor.
456    ~DagShortestPath() {
457      if(local_pred) delete _pred;
458      if(local_dist) delete _dist;
459    }
460
461    /// \brief Sets the length map.
462    ///
463    /// Sets the length map.
464    /// \return \c (*this)
465    DagShortestPath &lengthMap(const LengthMap &m) {
466      length = &m;
467      return *this;
468    }
469
470    /// \brief Sets the map storing the predecessor edges.
471    ///
472    /// Sets the map storing the predecessor edges.
473    /// If you don't use this function before calling \ref run(),
474    /// it will allocate one. The destuctor deallocates this
475    /// automatically allocated map, of course.
476    /// \return \c (*this)
477    DagShortestPath &predMap(PredMap &m) {
478      if(local_pred) {
479        delete _pred;
480        local_pred=false;
481      }
482      _pred = &m;
483      return *this;
484    }
485
486    /// \brief Sets the map storing the distances calculated by the algorithm.
487    ///
488    /// Sets the map storing the distances calculated by the algorithm.
489    /// If you don't use this function before calling \ref run(),
490    /// it will allocate one. The destuctor deallocates this
491    /// automatically allocated map, of course.
492    /// \return \c (*this)
493    DagShortestPath &distMap(DistMap &m) {
494      if(local_dist) {
495        delete _dist;
496        local_dist=false;
497      }
498      _dist = &m;
499      return *this;
500    }
501
502    /// \name Execution control
503    /// The simplest way to execute the algorithm is to use
504    /// one of the member functions called \c run(...)
505    /// \n
506    /// If you need more control on the execution,
507    /// first you must call \ref init(...), then you can add several source
508    /// nodes with \ref addSource().
509    /// Finally \ref start() will perform the actual path computation.
510    /// Some functions have an alternative form (\ref checkedInit(...),
511    /// \ref checkedRun(...)) which also verifies if the graph given in the
512    /// constructor is a dag.
513
514    ///@{
515
516    /// \brief Initializes the internal data structures.
517    ///
518    /// Initializes the internal data structures.
519    void init(const Value value = OperationTraits::infinity()) {
520      typedef typename Graph::template NodeMap<int> NodeOrderMap;
521      _process_step=0;
522      NodeOrderMap node_order(*graph);
523      topologicalSort(*graph,node_order);
524      _node_order.resize(countNodes(*graph),INVALID);
525      create_maps();
526      for (NodeIt it(*graph); it != INVALID; ++it) {
527        _node_order[node_order[it]]=it;
528        _pred->set(it, INVALID);
529        _dist->set(it, value);
530      }
531    }
532
533    /// \brief Initializes the internal data structures
534    /// with a given topological sort (NodeMap).
535    ///
536    /// Initializes the internal data structures
537    /// with a given topological sort (NodeMap).
538    void init(const typename Graph::template NodeMap<int>& node_order,
539         const Value value = OperationTraits::infinity()) {
540      _process_step=0;
541      _node_order.resize(countNodes(*graph),INVALID);
542      create_maps();
543      for (NodeIt it(*graph); it != INVALID; ++it) {
544        _node_order[node_order[it]]=it;
545        _pred->set(it, INVALID);
546        _dist->set(it, value);
547      }
548    }
549
550    /// \brief Initializes the internal data structures
551    /// with a given topological sort (std::vector).
552    ///
553    /// Initializes the internal data structures
554    /// with a given topological sort (std::vector).
555    void init(const std::vector<Node>& node_order,
556        const Value value = OperationTraits::infinity()) {
557      _process_step=0;
558      _node_order=node_order;
559      create_maps();
560      for (NodeIt it(*graph); it != INVALID; ++it) {
561        _pred->set(it, INVALID);
562        _dist->set(it, value);
563      }
564    }
565
566    /// \brief Initializes the internal data structures. It also checks if the graph is dag.
567    ///
568    /// Initializes the internal data structures. It also checks if the graph is dag.
569    /// \return true if the graph (given in the constructor) is dag, false otherwise.
570    bool checkedInit(const Value value = OperationTraits::infinity()) {
571      typedef typename Graph::template NodeMap<int> NodeOrderMap;
572      NodeOrderMap node_order(*graph);
573      if(!checkedTopologicalSort(*graph,node_order))return false;
574      init(node_order,value);
575      return true;
576    }
577
578    /// \brief Initializes the internal data structures with a given
579    /// topological sort (NodeMap). It also checks if the graph is dag.
580    ///
581    /// Initializes the internal data structures with a given
582    /// topological sort (NodeMap). It also checks if the graph is dag.
583    /// \return true if the graph (given in the constructor) is dag, false otherwise.
584    bool checkedInit(const typename Graph::template NodeMap<int>& node_order,
585                     const Value value = OperationTraits::infinity()) {
586      for(NodeIt it(*graph);it!=INVALID;++it){
587        for(OutEdgeIt oeit(*graph,it);oeit!=INVALID;++oeit){
588          if(node_order[graph->target(oeit)]<node_order[it])return false;
589        }
590      }
591      init(node_order,value);
592      return true;
593    }
594
595    /// \brief Initializes the internal data structures with a given
596    /// topological sort (std::vector). It also checks if the graph is dag.
597    ///
598    /// Initializes the internal data structures with a given
599    /// topological sort (std::vector). It also checks if the graph is dag.
600    /// \return true if the graph (given in the constructor) is dag, false otherwise.
601    bool checkedInit(const std::vector<Node>& node_order,
602                     const Value value = OperationTraits::infinity()) {
603      typedef typename Graph::template NodeMap<bool> BoolNodeMap;
604      BoolNodeMap _processed(*graph,false);
605      for(unsigned int i=0;i<_node_order.size();++i){
606        _processed[node_order[i]]=true;
607        for(OutEdgeIt oeit(*graph,node_order[i]);oeit!=INVALID;++oeit){
608          if(_processed[graph->target(oeit)])return false;
609        }
610      }
611      init(node_order,value);
612      return true;
613    }
614
615    /// \brief Adds a new source node.
616    ///
617    /// The optional second parameter is the initial distance of the node.
618    /// It just sets the distance of the node to the given value.
619    void addSource(Node source, Value dst = OperationTraits::zero()) {
620      if((*_dist)[source] != dst){
621        _dist->set(source, dst);
622      }
623    }
624
625    /// \brief Executes one step from the dag shortest path algorithm.
626    ///
627    /// If the algoritm calculated the distances in the previous step
628    /// strictly for all at most k length paths then it will calculate the
629    /// distances strictly for all at most k + 1 length paths. With k
630    /// iteration this function calculates the at most k length paths.
631    ///\pre the queue is not empty
632    ///\return the currently processed node
633    Node processNextNode() {
634      if(reached(_node_order[_process_step])){
635        for (OutEdgeIt it(*graph, _node_order[_process_step]); it != INVALID; ++it) {
636          Node target = graph->target(it);
637          Value relaxed =
638            OperationTraits::plus((*_dist)[_node_order[_process_step]], (*length)[it]);
639          if (OperationTraits::less(relaxed, (*_dist)[target])) {
640            _pred->set(target, it);
641            _dist->set(target, relaxed);
642          }
643        }
644      }
645      ++_process_step;
646      return _node_order[_process_step-1];
647    }
648
649    ///\brief Returns \c false if there are nodes
650    ///to be processed in the queue
651    ///
652    ///Returns \c false if there are nodes
653    ///to be processed in the queue
654    bool emptyQueue() { return _node_order.size()-1==_process_step; }
655
656    ///\brief Returns the number of the nodes to be processed.
657    ///
658    ///Returns the number of the nodes to be processed in the queue.
659    int queueSize() { return _node_order.size()-1-_process_step; }
660
661    /// \brief Executes the algorithm.
662    ///
663    /// \pre init() must be called and at least one node should be added
664    /// with addSource() before using this function.
665    ///
666    /// This method runs the %DagShortestPath algorithm from the root node(s)
667    /// in order to compute the shortest path to each node. The algorithm
668    /// computes
669    /// - The shortest path tree.
670    /// - The distance of each node from the root(s).
671    void start() {
672      while(!emptyQueue()) {
673        processNextNode();
674      }
675    }
676
677    /// \brief Runs %DagShortestPath algorithm from node \c s.
678    ///   
679    /// This method runs the %DagShortestPath algorithm from a root node \c s
680    /// in order to compute the shortest path to each node. The algorithm
681    /// computes
682    /// - The shortest path tree.
683    /// - The distance of each node from the root.
684    ///
685    /// \note d.run(s) is just a shortcut of the following code.
686    ///\code
687    ///  d.init();
688    ///  d.addSource(s);
689    ///  d.start();
690    ///\endcode
691    void run(Node s) {
692      init();
693      addSource(s);
694      start();
695    }
696   
697    /// \brief Runs %DagShortestPath algorithm from node \c s.
698    /// It also checks if the graph is a dag.
699    ///   
700    /// This method runs the %DagShortestPath algorithm from a root node \c s
701    /// in order to compute the shortest path to each node. The algorithm
702    /// computes
703    /// - The shortest path tree.
704    /// - The distance of each node from the root.
705    /// The algorithm checks if the graph given int the constructor is a dag.
706    bool checkedRun(Node s) {
707      if(!checkedInit())return false;
708      addSource(s);
709      start();
710      return true;
711    }
712   
713    ///@}
714
715    /// \name Query Functions
716    /// The result of the %DagShortestPath algorithm can be obtained using these
717    /// functions.\n
718    /// Before the use of these functions,
719    /// either run() or start() must be called.
720   
721    ///@{
722
723    /// \brief Copies the shortest path to \c t into \c p
724    ///   
725    /// This function copies the shortest path to \c t into \c p.
726    /// If it \c t is a source itself or unreachable, then it does not
727    /// alter \c p.
728    ///
729    /// \return Returns \c true if a path to \c t was actually copied to \c p,
730    /// \c false otherwise.
731    /// \sa DirPath
732    template <typename Path>
733    bool getPath(Path &p, Node t) {
734      if(reached(t)) {
735        p.clear();
736        typename Path::Builder b(p);
737        for(b.setStartNode(t);predEdge(t)!=INVALID;t=predNode(t))
738          b.pushFront(predEdge(t));
739        b.commit();
740        return true;
741      }
742      return false;
743    }
744         
745    /// \brief The distance of a node from the root.
746    ///
747    /// Returns the distance of a node from the root.
748    /// \pre \ref run() must be called before using this function.
749    /// \warning If node \c v in unreachable from the root the return value
750    /// of this funcion is undefined.
751    Value dist(Node v) const { return (*_dist)[v]; }
752
753    /// \brief Returns the 'previous edge' of the shortest path tree.
754    ///
755    /// For a node \c v it returns the 'previous edge' of the shortest path
756    /// tree, i.e. it returns the last edge of a shortest path from the root
757    /// to \c v. It is \ref INVALID if \c v is unreachable from the root or
758    /// if \c v=s. The shortest path tree used here is equal to the shortest
759    /// path tree used in \ref predNode().
760    /// \pre \ref run() must be called before using
761    /// this function.
762    Edge predEdge(Node v) const { return (*_pred)[v]; }
763
764    /// \brief Returns the 'previous node' of the shortest path tree.
765    ///
766    /// For a node \c v it returns the 'previous node' of the shortest path
767    /// tree, i.e. it returns the last but one node from a shortest path from
768    /// the root to \c /v. It is INVALID if \c v is unreachable from the root
769    /// or if \c v=s. The shortest path tree used here is equal to the
770    /// shortest path tree used in \ref predEdge().  \pre \ref run() must be
771    /// called before using this function.
772    Node predNode(Node v) const {
773      return (*_pred)[v] == INVALID ? INVALID : graph->source((*_pred)[v]);
774    }
775   
776    /// \brief Returns a reference to the NodeMap of distances.
777    ///
778    /// Returns a reference to the NodeMap of distances. \pre \ref run() must
779    /// be called before using this function.
780    const DistMap &distMap() const { return *_dist;}
781 
782    /// \brief Returns a reference to the shortest path tree map.
783    ///
784    /// Returns a reference to the NodeMap of the edges of the
785    /// shortest path tree.
786    /// \pre \ref run() must be called before using this function.
787    const PredMap &predMap() const { return *_pred; }
788 
789    /// \brief Checks if a node is reachable from the root.
790    ///
791    /// Returns \c true if \c v is reachable from the root.
792    /// \pre \ref run() must be called before using this function.
793    ///
794    bool reached(Node v) { return (*_dist)[v] != OperationTraits::infinity(); }
795   
796    ///@}
797  };
798 
799  /// \brief Default traits class of DagShortestPath function.
800  ///
801  /// Default traits class of DagShortestPath function.
802  /// \param _Graph Graph type.
803  /// \param _LengthMap Type of length map.
804  template <typename _Graph, typename _LengthMap>
805  struct DagShortestPathWizardDefaultTraits {
806    /// \brief The graph type the algorithm runs on.
807    typedef _Graph Graph;
808
809    /// \brief The type of the map that stores the edge lengths.
810    ///
811    /// The type of the map that stores the edge lengths.
812    /// It must meet the \ref concept::ReadMap "ReadMap" concept.
813    typedef _LengthMap LengthMap;
814
815    /// \brief The value type of the length map.
816    typedef typename _LengthMap::Value Value;
817
818    /// \brief Operation traits for dag shortest path algorithm.
819    ///
820    /// It defines the infinity type on the given Value type
821    /// and the used operation.
822    /// \see DagShortestPathDefaultOperationTraits
823    typedef DagShortestPathDefaultOperationTraits<Value> OperationTraits;
824
825    /// \brief The type of the map that stores the last
826    /// edges of the shortest paths.
827    ///
828    /// The type of the map that stores the last
829    /// edges of the shortest paths.
830    /// It must meet the \ref concept::WriteMap "WriteMap" concept.
831    typedef NullMap <typename _Graph::Node,typename _Graph::Edge> PredMap;
832
833    /// \brief Instantiates a PredMap.
834    ///
835    /// This function instantiates a \ref PredMap.
836    static PredMap *createPredMap(const _Graph &) {
837      return new PredMap();
838    }
839    /// \brief The type of the map that stores the dists of the nodes.
840    ///
841    /// The type of the map that stores the dists of the nodes.
842    /// It must meet the \ref concept::WriteMap "WriteMap" concept.
843    typedef NullMap<typename Graph::Node, Value> DistMap;
844    /// \brief Instantiates a DistMap.
845    ///
846    /// This function instantiates a \ref DistMap.
847    static DistMap *createDistMap(const _Graph &) {
848      return new DistMap();
849    }
850  };
851 
852  /// \brief Default traits used by \ref DagShortestPathWizard
853  ///
854  /// To make it easier to use DagShortestPath algorithm
855  /// we have created a wizard class.
856  /// This \ref DagShortestPathWizard class needs default traits,
857  /// as well as the \ref DagShortestPath class.
858  /// The \ref DagShortestPathWizardBase is a class to be the default traits of the
859  /// \ref DagShortestPathWizard class.
860  /// \todo More named parameters are required...
861  template<class _Graph,class _LengthMap>
862  class DagShortestPathWizardBase
863    : public DagShortestPathWizardDefaultTraits<_Graph,_LengthMap> {
864
865    typedef DagShortestPathWizardDefaultTraits<_Graph,_LengthMap> Base;
866  protected:
867    /// Type of the nodes in the graph.
868    typedef typename Base::Graph::Node Node;
869
870    /// Pointer to the underlying graph.
871    void *_graph;
872    /// Pointer to the length map
873    void *_length;
874    ///Pointer to the map of predecessors edges.
875    void *_pred;
876    ///Pointer to the map of distances.
877    void *_dist;
878    ///Pointer to the source node.
879    Node _source;
880
881    public:
882    /// Constructor.
883   
884    /// This constructor does not require parameters, therefore it initiates
885    /// all of the attributes to default values (0, INVALID).
886    DagShortestPathWizardBase() : _graph(0), _length(0), _pred(0),
887                           _dist(0), _source(INVALID) {}
888
889    /// Constructor.
890   
891    /// This constructor requires some parameters,
892    /// listed in the parameters list.
893    /// Others are initiated to 0.
894    /// \param graph is the initial value of  \ref _graph
895    /// \param length is the initial value of  \ref _length
896    /// \param source is the initial value of  \ref _source
897    DagShortestPathWizardBase(const _Graph& graph,
898                          const _LengthMap& length,
899                          Node source = INVALID) :
900      _graph((void *)&graph), _length((void *)&length), _pred(0),
901      _dist(0), _source(source) {}
902
903  };
904 
905  /// A class to make the usage of DagShortestPath algorithm easier
906
907  /// This class is created to make it easier to use DagShortestPath algorithm.
908  /// It uses the functions and features of the plain \ref DagShortestPath,
909  /// but it is much simpler to use it.
910  ///
911  /// Simplicity means that the way to change the types defined
912  /// in the traits class is based on functions that returns the new class
913  /// and not on templatable built-in classes.
914  /// When using the plain \ref DagShortestPath
915  /// the new class with the modified type comes from
916  /// the original class by using the ::
917  /// operator. In the case of \ref DagShortestPathWizard only
918  /// a function have to be called and it will
919  /// return the needed class.
920  ///
921  /// It does not have own \ref run method. When its \ref run method is called
922  /// it initiates a plain \ref DagShortestPath class, and calls the \ref
923  /// DagShortestPath::run() method of it.
924  template<class _Traits>
925  class DagShortestPathWizard : public _Traits {
926    typedef _Traits Base;
927
928    ///The type of the underlying graph.
929    typedef typename _Traits::Graph Graph;
930
931    typedef typename Graph::Node Node;
932    typedef typename Graph::NodeIt NodeIt;
933    typedef typename Graph::Edge Edge;
934    typedef typename Graph::OutEdgeIt EdgeIt;
935   
936    ///The type of the map that stores the edge lengths.
937    typedef typename _Traits::LengthMap LengthMap;
938
939    ///The type of the length of the edges.
940    typedef typename LengthMap::Value Value;
941
942    ///\brief The type of the map that stores the last
943    ///edges of the shortest paths.
944    typedef typename _Traits::PredMap PredMap;
945
946    ///The type of the map that stores the dists of the nodes.
947    typedef typename _Traits::DistMap DistMap;
948
949  public:
950    /// Constructor.
951    DagShortestPathWizard() : _Traits() {}
952
953    /// \brief Constructor that requires parameters.
954    ///
955    /// Constructor that requires parameters.
956    /// These parameters will be the default values for the traits class.
957    DagShortestPathWizard(const Graph& graph, const LengthMap& length,
958                      Node source = INVALID)
959      : _Traits(graph, length, source) {}
960
961    /// \brief Copy constructor
962    DagShortestPathWizard(const _Traits &b) : _Traits(b) {}
963
964    ~DagShortestPathWizard() {}
965
966    /// \brief Runs DagShortestPath algorithm from a given node.
967    ///   
968    /// Runs DagShortestPath algorithm from a given node.
969    /// The node can be given by the \ref source function.
970    void run() {
971      if(Base::_source == INVALID) throw UninitializedParameter();
972      DagShortestPath<Graph,LengthMap,_Traits>
973        bf(*(Graph*)Base::_graph, *(LengthMap*)Base::_length);
974      if (Base::_pred) bf.predMap(*(PredMap*)Base::_pred);
975      if (Base::_dist) bf.distMap(*(DistMap*)Base::_dist);
976      bf.run(Base::_source);
977    }
978
979    /// \brief Runs DagShortestPath algorithm from the given node.
980    ///
981    /// Runs DagShortestPath algorithm from the given node.
982    /// \param source is the given source.
983    void run(Node source) {
984      Base::_source = source;
985      run();
986    }
987
988    template<class T>
989    struct DefPredMapBase : public Base {
990      typedef T PredMap;
991      static PredMap *createPredMap(const Graph &) { return 0; };
992      DefPredMapBase(const _Traits &b) : _Traits(b) {}
993    };
994   
995    ///\brief \ref named-templ-param "Named parameter"
996    ///function for setting PredMap type
997    ///
998    /// \ref named-templ-param "Named parameter"
999    ///function for setting PredMap type
1000    ///
1001    template<class T>
1002    DagShortestPathWizard<DefPredMapBase<T> > predMap(const T &t)
1003    {
1004      Base::_pred=(void *)&t;
1005      return DagShortestPathWizard<DefPredMapBase<T> >(*this);
1006    }
1007   
1008    template<class T>
1009    struct DefDistMapBase : public Base {
1010      typedef T DistMap;
1011      static DistMap *createDistMap(const Graph &) { return 0; };
1012      DefDistMapBase(const _Traits &b) : _Traits(b) {}
1013    };
1014   
1015    ///\brief \ref named-templ-param "Named parameter"
1016    ///function for setting DistMap type
1017    ///
1018    /// \ref named-templ-param "Named parameter"
1019    ///function for setting DistMap type
1020    ///
1021    template<class T>
1022    DagShortestPathWizard<DefDistMapBase<T> > distMap(const T &t) {
1023      Base::_dist=(void *)&t;
1024      return DagShortestPathWizard<DefDistMapBase<T> >(*this);
1025    }
1026
1027    template<class T>
1028    struct DefOperationTraitsBase : public Base {
1029      typedef T OperationTraits;
1030      DefOperationTraitsBase(const _Traits &b) : _Traits(b) {}
1031    };
1032   
1033    ///\brief \ref named-templ-param "Named parameter"
1034    ///function for setting OperationTraits type
1035    ///
1036    /// \ref named-templ-param "Named parameter"
1037    ///function for setting OperationTraits type
1038    ///
1039    template<class T>
1040    DagShortestPathWizard<DefOperationTraitsBase<T> > distMap() {
1041      return DagShortestPathWizard<DefDistMapBase<T> >(*this);
1042    }
1043   
1044    /// \brief Sets the source node, from which the DagShortestPath algorithm runs.
1045    ///
1046    /// Sets the source node, from which the DagShortestPath algorithm runs.
1047    /// \param source is the source node.
1048    DagShortestPathWizard<_Traits>& source(Node source) {
1049      Base::_source = source;
1050      return *this;
1051    }
1052   
1053  };
1054 
1055  /// \brief Function type interface for DagShortestPath algorithm.
1056  ///
1057  /// \ingroup flowalgs
1058  /// Function type interface for DagShortestPath algorithm.
1059  ///
1060  /// This function also has several \ref named-templ-func-param
1061  /// "named parameters", they are declared as the members of class
1062  /// \ref DagShortestPathWizard.
1063  /// The following
1064  /// example shows how to use these parameters.
1065  ///\code
1066  /// dagShortestPath(g,length,source).predMap(preds).run();
1067  ///\endcode
1068  /// \warning Don't forget to put the \ref DagShortestPathWizard::run() "run()"
1069  /// to the end of the parameter list.
1070  /// \sa DagShortestPathWizard
1071  /// \sa DagShortestPath
1072  template<class _Graph, class _LengthMap>
1073  DagShortestPathWizard<DagShortestPathWizardBase<_Graph,_LengthMap> >
1074  dagShortestPath(const _Graph& graph,
1075              const _LengthMap& length,
1076              typename _Graph::Node source = INVALID) {
1077    return DagShortestPathWizard<DagShortestPathWizardBase<_Graph,_LengthMap> >
1078      (graph, length, source);
1079  }
1080
1081} //END OF NAMESPACE LEMON
1082
1083#endif
1084
Note: See TracBrowser for help on using the repository browser.