src/lemon/dijkstra.h
author alpar
Mon, 01 Nov 2004 07:04:52 +0000
changeset 952 fa65d57f1930
parent 911 89a4fbb99cad
child 959 c80ef5912903
permissions -rw-r--r--
Traits + Named Parameters version
     1 /* -*- C++ -*-
     2  * src/lemon/dijkstra.h - Part of LEMON, a generic C++ optimization library
     3  *
     4  * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     5  * (Egervary Combinatorial Optimization Research Group, 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_DIJKSTRA_H
    18 #define LEMON_DIJKSTRA_H
    19 
    20 ///\ingroup flowalgs
    21 ///\file
    22 ///\brief Dijkstra algorithm.
    23 
    24 #include <lemon/bin_heap.h>
    25 #include <lemon/invalid.h>
    26 
    27 namespace lemon {
    28 
    29 /// \addtogroup flowalgs
    30 /// @{
    31 
    32   ///%Dijkstra algorithm class.
    33 
    34   ///This class provides an efficient implementation of %Dijkstra algorithm.
    35   ///The edge lengths are passed to the algorithm using a
    36   ///\ref skeleton::ReadMap "ReadMap",
    37   ///so it is easy to change it to any kind of length.
    38   ///
    39   ///The type of the length is determined by the
    40   ///\ref skeleton::ReadMap::ValueType "ValueType" of the length map.
    41   ///
    42   ///It is also possible to change the underlying priority heap.
    43   ///
    44   ///\param GR The graph type the algorithm runs on.
    45   ///\param LM This read-only
    46   ///EdgeMap
    47   ///determines the
    48   ///lengths of the edges. It is read once for each edge, so the map
    49   ///may involve in relatively time consuming process to compute the edge
    50   ///length if it is necessary. The default map type is
    51   ///\ref skeleton::StaticGraph::EdgeMap "Graph::EdgeMap<int>"
    52   ///\param Heap The heap type used by the %Dijkstra
    53   ///algorithm. The default
    54   ///is using \ref BinHeap "binary heap".
    55   ///
    56   ///\author Jacint Szabo and Alpar Juttner
    57   ///\todo We need a typedef-names should be standardized. (-:
    58   ///\todo Type of \c PredMap, \c PredNodeMap and \c DistMap
    59   ///should not be fixed. (Problematic to solve).
    60 
    61 #ifdef DOXYGEN
    62   template <typename GR,
    63 	    typename LM,
    64 	    typename Heap>
    65 #else
    66   template <typename GR,
    67 	    typename LM=typename GR::template EdgeMap<int>,
    68 	    template <class,class,class,class> class Heap = BinHeap >
    69 #endif
    70   class Dijkstra{
    71   public:
    72     ///The type of the underlying graph.
    73     typedef GR Graph;
    74     ///\e
    75     typedef typename Graph::Node Node;
    76     ///\e
    77     typedef typename Graph::NodeIt NodeIt;
    78     ///\e
    79     typedef typename Graph::Edge Edge;
    80     ///\e
    81     typedef typename Graph::OutEdgeIt OutEdgeIt;
    82     
    83     ///The type of the length of the edges.
    84     typedef typename LM::ValueType ValueType;
    85     ///The type of the map that stores the edge lengths.
    86     typedef LM LengthMap;
    87     ///\brief The type of the map that stores the last
    88     ///edges of the shortest paths.
    89     typedef typename Graph::template NodeMap<Edge> PredMap;
    90     ///\brief The type of the map that stores the last but one
    91     ///nodes of the shortest paths.
    92     typedef typename Graph::template NodeMap<Node> PredNodeMap;
    93     ///The type of the map that stores the dists of the nodes.
    94     typedef typename Graph::template NodeMap<ValueType> DistMap;
    95 
    96   private:
    97     /// Pointer to the underlying graph.
    98     const Graph *G;
    99     /// Pointer to the length map
   100     const LM *length;
   101     ///Pointer to the map of predecessors edges.
   102     PredMap *predecessor;
   103     ///Indicates if \ref predecessor is locally allocated (\c true) or not.
   104     bool local_predecessor;
   105     ///Pointer to the map of predecessors nodes.
   106     PredNodeMap *pred_node;
   107     ///Indicates if \ref pred_node is locally allocated (\c true) or not.
   108     bool local_pred_node;
   109     ///Pointer to the map of distances.
   110     DistMap *distance;
   111     ///Indicates if \ref distance is locally allocated (\c true) or not.
   112     bool local_distance;
   113 
   114     ///The source node of the last execution.
   115     Node source;
   116 
   117     ///Initializes the maps.
   118     
   119     ///\todo Error if \c G or are \c NULL. What about \c length?
   120     ///\todo Better memory allocation (instead of new).
   121     void init_maps() 
   122     {
   123       if(!predecessor) {
   124 	local_predecessor = true;
   125 	predecessor = new PredMap(*G);
   126       }
   127       if(!pred_node) {
   128 	local_pred_node = true;
   129 	pred_node = new PredNodeMap(*G);
   130       }
   131       if(!distance) {
   132 	local_distance = true;
   133 	distance = new DistMap(*G);
   134       }
   135     }
   136     
   137   public :
   138     ///Constructor.
   139     
   140     ///\param _G the graph the algorithm will run on.
   141     ///\param _length the length map used by the algorithm.
   142     Dijkstra(const Graph& _G, const LM& _length) :
   143       G(&_G), length(&_length),
   144       predecessor(NULL), local_predecessor(false),
   145       pred_node(NULL), local_pred_node(false),
   146       distance(NULL), local_distance(false)
   147     { }
   148     
   149     ///Destructor.
   150     ~Dijkstra() 
   151     {
   152       if(local_predecessor) delete predecessor;
   153       if(local_pred_node) delete pred_node;
   154       if(local_distance) delete distance;
   155     }
   156 
   157     ///Sets the length map.
   158 
   159     ///Sets the length map.
   160     ///\return <tt> (*this) </tt>
   161     Dijkstra &setLengthMap(const LM &m) 
   162     {
   163       length = &m;
   164       return *this;
   165     }
   166 
   167     ///Sets the map storing the predecessor edges.
   168 
   169     ///Sets the map storing the predecessor edges.
   170     ///If you don't use this function before calling \ref run(),
   171     ///it will allocate one. The destuctor deallocates this
   172     ///automatically allocated map, of course.
   173     ///\return <tt> (*this) </tt>
   174     Dijkstra &setPredMap(PredMap &m) 
   175     {
   176       if(local_predecessor) {
   177 	delete predecessor;
   178 	local_predecessor=false;
   179       }
   180       predecessor = &m;
   181       return *this;
   182     }
   183 
   184     ///Sets the map storing the predecessor nodes.
   185 
   186     ///Sets the map storing the predecessor nodes.
   187     ///If you don't use this function before calling \ref run(),
   188     ///it will allocate one. The destuctor deallocates this
   189     ///automatically allocated map, of course.
   190     ///\return <tt> (*this) </tt>
   191     Dijkstra &setPredNodeMap(PredNodeMap &m) 
   192     {
   193       if(local_pred_node) {
   194 	delete pred_node;
   195 	local_pred_node=false;
   196       }
   197       pred_node = &m;
   198       return *this;
   199     }
   200 
   201     ///Sets the map storing the distances calculated by the algorithm.
   202 
   203     ///Sets the map storing the distances calculated by the algorithm.
   204     ///If you don't use this function before calling \ref run(),
   205     ///it will allocate one. The destuctor deallocates this
   206     ///automatically allocated map, of course.
   207     ///\return <tt> (*this) </tt>
   208     Dijkstra &setDistMap(DistMap &m) 
   209     {
   210       if(local_distance) {
   211 	delete distance;
   212 	local_distance=false;
   213       }
   214       distance = &m;
   215       return *this;
   216     }
   217     
   218   ///Runs %Dijkstra algorithm from node \c s.
   219 
   220   ///This method runs the %Dijkstra algorithm from a root node \c s
   221   ///in order to
   222   ///compute the
   223   ///shortest path to each node. The algorithm computes
   224   ///- The shortest path tree.
   225   ///- The distance of each node from the root.
   226     
   227     void run(Node s) {
   228       
   229       init_maps();
   230       
   231       source = s;
   232       
   233       for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
   234 	predecessor->set(u,INVALID);
   235 	pred_node->set(u,INVALID);
   236       }
   237       
   238       typename GR::template NodeMap<int> heap_map(*G,-1);
   239       
   240       typedef Heap<Node, ValueType, typename GR::template NodeMap<int>,
   241       std::less<ValueType> > 
   242       HeapType;
   243       
   244       HeapType heap(heap_map);
   245       
   246       heap.push(s,0); 
   247       
   248       while ( !heap.empty() ) {
   249 	
   250 	Node v=heap.top(); 
   251 	ValueType oldvalue=heap[v];
   252 	heap.pop();
   253 	distance->set(v, oldvalue);
   254 	
   255 	
   256 	for(OutEdgeIt e(*G,v); e!=INVALID; ++e) {
   257 	  Node w=G->head(e); 
   258 	  switch(heap.state(w)) {
   259 	  case HeapType::PRE_HEAP:
   260 	    heap.push(w,oldvalue+(*length)[e]); 
   261 	    predecessor->set(w,e);
   262 	    pred_node->set(w,v);
   263 	    break;
   264 	  case HeapType::IN_HEAP:
   265 	    if ( oldvalue+(*length)[e] < heap[w] ) {
   266 	      heap.decrease(w, oldvalue+(*length)[e]); 
   267 	      predecessor->set(w,e);
   268 	      pred_node->set(w,v);
   269 	    }
   270 	    break;
   271 	  case HeapType::POST_HEAP:
   272 	    break;
   273 	  }
   274 	}
   275       }
   276     }
   277     
   278     ///The distance of a node from the root.
   279 
   280     ///Returns the distance of a node from the root.
   281     ///\pre \ref run() must be called before using this function.
   282     ///\warning If node \c v in unreachable from the root the return value
   283     ///of this funcion is undefined.
   284     ValueType dist(Node v) const { return (*distance)[v]; }
   285 
   286     ///Returns the 'previous edge' of the shortest path tree.
   287 
   288     ///For a node \c v it returns the 'previous edge' of the shortest path tree,
   289     ///i.e. it returns the last edge of a shortest path from the root to \c
   290     ///v. It is \ref INVALID
   291     ///if \c v is unreachable from the root or if \c v=s. The
   292     ///shortest path tree used here is equal to the shortest path tree used in
   293     ///\ref predNode(Node v).  \pre \ref run() must be called before using
   294     ///this function.
   295     ///\todo predEdge could be a better name.
   296     Edge pred(Node v) const { return (*predecessor)[v]; }
   297 
   298     ///Returns the 'previous node' of the shortest path tree.
   299 
   300     ///For a node \c v it returns the 'previous node' of the shortest path tree,
   301     ///i.e. it returns the last but one node from a shortest path from the
   302     ///root to \c /v. It is INVALID if \c v is unreachable from the root or if
   303     ///\c v=s. The shortest path tree used here is equal to the shortest path
   304     ///tree used in \ref pred(Node v).  \pre \ref run() must be called before
   305     ///using this function.
   306     Node predNode(Node v) const { return (*pred_node)[v]; }
   307     
   308     ///Returns a reference to the NodeMap of distances.
   309 
   310     ///Returns a reference to the NodeMap of distances. \pre \ref run() must
   311     ///be called before using this function.
   312     const DistMap &distMap() const { return *distance;}
   313  
   314     ///Returns a reference to the shortest path tree map.
   315 
   316     ///Returns a reference to the NodeMap of the edges of the
   317     ///shortest path tree.
   318     ///\pre \ref run() must be called before using this function.
   319     const PredMap &predMap() const { return *predecessor;}
   320  
   321     ///Returns a reference to the map of nodes of shortest paths.
   322 
   323     ///Returns a reference to the NodeMap of the last but one nodes of the
   324     ///shortest path tree.
   325     ///\pre \ref run() must be called before using this function.
   326     const PredNodeMap &predNodeMap() const { return *pred_node;}
   327 
   328     ///Checks if a node is reachable from the root.
   329 
   330     ///Returns \c true if \c v is reachable from the root.
   331     ///\note The root node is reported to be reached!
   332     ///\pre \ref run() must be called before using this function.
   333     ///
   334     bool reached(Node v) { return v==source || (*predecessor)[v]!=INVALID; }
   335     
   336   };
   337   
   338 /// @}
   339   
   340 } //END OF NAMESPACE LEMON
   341 
   342 #endif
   343 
   344