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