COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dijkstra.h @ 2580:fa71d9612c42

Last change on this file since 2580:fa71d9612c42 was 2553:bfced05fa852, checked in by Alpar Juttner, 16 years ago

Happy New Year to LEMON (+ better update-copyright-header script)

File size: 38.2 KB
RevLine 
[906]1/* -*- C++ -*-
2 *
[1956]3 * This file is a part of LEMON, a generic C++ optimization library
4 *
[2553]5 * Copyright (C) 2003-2008
[1956]6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
[1359]7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
[906]8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
[921]19#ifndef LEMON_DIJKSTRA_H
20#define LEMON_DIJKSTRA_H
[255]21
[2376]22///\ingroup shortest_path
[255]23///\file
24///\brief Dijkstra algorithm.
[1283]25///
[255]26
[953]27#include <lemon/list_graph.h>
[921]28#include <lemon/bin_heap.h>
[2335]29#include <lemon/bits/path_dump.h>
[1993]30#include <lemon/bits/invalid.h>
[1119]31#include <lemon/error.h>
32#include <lemon/maps.h>
[255]33
[2335]34
[921]35namespace lemon {
[385]36
[2537]37  /// \brief Default OperationTraits for the Dijkstra algorithm class.
38  /// 
39  /// It defines all computational operations and constants which are
40  /// used in the Dijkstra algorithm.
41  template <typename Value>
42  struct DijkstraDefaultOperationTraits {
43    /// \brief Gives back the zero value of the type.
44    static Value zero() {
45      return static_cast<Value>(0);
46    }
47    /// \brief Gives back the sum of the given two elements.
48    static Value plus(const Value& left, const Value& right) {
49      return left + right;
50    }
51    /// \brief Gives back true only if the first value less than the second.
52    static bool less(const Value& left, const Value& right) {
53      return left < right;
54    }
55  };
56
57  /// \brief Widest path OperationTraits for the Dijkstra algorithm class.
58  /// 
59  /// It defines all computational operations and constants which are
60  /// used in the Dijkstra algorithm for widest path computation.
61  template <typename Value>
62  struct DijkstraWidestPathOperationTraits {
63    /// \brief Gives back the maximum value of the type.
64    static Value zero() {
65      return std::numeric_limits<Value>::max();
66    }
[2538]67    /// \brief Gives back the minimum of the given two elements.
[2537]68    static Value plus(const Value& left, const Value& right) {
69      return std::min(left, right);
70    }
71    /// \brief Gives back true only if the first value less than the second.
72    static bool less(const Value& left, const Value& right) {
73      return left < right;
74    }
75  };
[1151]76 
[954]77  ///Default traits class of Dijkstra class.
78
79  ///Default traits class of Dijkstra class.
80  ///\param GR Graph type.
81  ///\param LM Type of length map.
[953]82  template<class GR, class LM>
83  struct DijkstraDefaultTraits
84  {
[954]85    ///The graph type the algorithm runs on.
[953]86    typedef GR Graph;
87    ///The type of the map that stores the edge lengths.
88
[1124]89    ///The type of the map that stores the edge lengths.
[2260]90    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
[953]91    typedef LM LengthMap;
[954]92    //The type of the length of the edges.
[987]93    typedef typename LM::Value Value;
[2537]94    /// Operation traits for Dijkstra algorithm.
95
96    /// It defines the used operation by the algorithm.
97    /// \see DijkstraDefaultOperationTraits
98    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
[1721]99    /// The cross reference type used by heap.
100
[2537]101
[1721]102    /// The cross reference type used by heap.
103    /// Usually it is \c Graph::NodeMap<int>.
104    typedef typename Graph::template NodeMap<int> HeapCrossRef;
105    ///Instantiates a HeapCrossRef.
106
[2537]107    ///This function instantiates a \c HeapCrossRef.
[1721]108    /// \param G is the graph, to which we would like to define the
109    /// HeapCrossRef.
110    static HeapCrossRef *createHeapCrossRef(const GR &G)
111    {
112      return new HeapCrossRef(G);
113    }
114   
[954]115    ///The heap type used by Dijkstra algorithm.
[967]116
117    ///The heap type used by Dijkstra algorithm.
118    ///
119    ///\sa BinHeap
120    ///\sa Dijkstra
[2263]121    typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
[953]122
[1721]123    static Heap *createHeap(HeapCrossRef& R)
124    {
125      return new Heap(R);
126    }
127
[953]128    ///\brief The type of the map that stores the last
129    ///edges of the shortest paths.
130    ///
[1124]131    ///The type of the map that stores the last
132    ///edges of the shortest paths.
[2260]133    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[953]134    ///
[954]135    typedef typename Graph::template NodeMap<typename GR::Edge> PredMap;
136    ///Instantiates a PredMap.
[953]137 
[2537]138    ///This function instantiates a \c PredMap.
[1123]139    ///\param G is the graph, to which we would like to define the PredMap.
[1119]140    ///\todo The graph alone may be insufficient for the initialization
[954]141    static PredMap *createPredMap(const GR &G)
[953]142    {
143      return new PredMap(G);
144    }
[1119]145
[1218]146    ///The type of the map that stores whether a nodes is processed.
[1119]147 
[1218]148    ///The type of the map that stores whether a nodes is processed.
[2260]149    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[1119]150    ///By default it is a NullMap.
[1218]151    ///\todo If it is set to a real map,
152    ///Dijkstra::processed() should read this.
[1119]153    ///\todo named parameter to set this type, function to read and write.
[1218]154    typedef NullMap<typename Graph::Node,bool> ProcessedMap;
155    ///Instantiates a ProcessedMap.
[1119]156 
[2537]157    ///This function instantiates a \c ProcessedMap.
[1536]158    ///\param g is the graph, to which
[2537]159    ///we would like to define the \c ProcessedMap
[1536]160#ifdef DOXYGEN
161    static ProcessedMap *createProcessedMap(const GR &g)
162#else
[1366]163    static ProcessedMap *createProcessedMap(const GR &)
[1536]164#endif
[1119]165    {
[1218]166      return new ProcessedMap();
[1119]167    }
[953]168    ///The type of the map that stores the dists of the nodes.
169 
[1124]170    ///The type of the map that stores the dists of the nodes.
[2260]171    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[953]172    ///
[987]173    typedef typename Graph::template NodeMap<typename LM::Value> DistMap;
[954]174    ///Instantiates a DistMap.
[953]175 
[1123]176    ///This function instantiates a \ref DistMap.
177    ///\param G is the graph, to which we would like to define the \ref DistMap
[954]178    static DistMap *createDistMap(const GR &G)
[953]179    {
180      return new DistMap(G);
181    }
182  };
183 
[255]184  ///%Dijkstra algorithm class.
[1125]185 
[2376]186  /// \ingroup shortest_path
[255]187  ///This class provides an efficient implementation of %Dijkstra algorithm.
188  ///The edge lengths are passed to the algorithm using a
[2260]189  ///\ref concepts::ReadMap "ReadMap",
[255]190  ///so it is easy to change it to any kind of length.
191  ///
[880]192  ///The type of the length is determined by the
[2260]193  ///\ref concepts::ReadMap::Value "Value" of the length map.
[255]194  ///
195  ///It is also possible to change the underlying priority heap.
196  ///
[1218]197  ///\param GR The graph type the algorithm runs on. The default value
198  ///is \ref ListGraph. The value of GR is not used directly by
199  ///Dijkstra, it is only passed to \ref DijkstraDefaultTraits.
200  ///\param LM This read-only EdgeMap determines the lengths of the
201  ///edges. It is read once for each edge, so the map may involve in
202  ///relatively time consuming process to compute the edge length if
203  ///it is necessary. The default map type is \ref
[2260]204  ///concepts::Graph::EdgeMap "Graph::EdgeMap<int>".  The value
[1218]205  ///of LM is not used directly by Dijkstra, it is only passed to \ref
206  ///DijkstraDefaultTraits.  \param TR Traits class to set
207  ///various data types used by the algorithm.  The default traits
208  ///class is \ref DijkstraDefaultTraits
209  ///"DijkstraDefaultTraits<GR,LM>".  See \ref
210  ///DijkstraDefaultTraits for the documentation of a Dijkstra traits
211  ///class.
[456]212  ///
[689]213  ///\author Jacint Szabo and Alpar Juttner
[584]214
[255]215#ifdef DOXYGEN
[2537]216  template <typename GR, typename LM, typename TR>
[255]217#else
[953]218  template <typename GR=ListGraph,
[584]219            typename LM=typename GR::template EdgeMap<int>,
[953]220            typename TR=DijkstraDefaultTraits<GR,LM> >
[255]221#endif
[1116]222  class Dijkstra {
[255]223  public:
[1125]224    /**
225     * \brief \ref Exception for uninitialized parameters.
226     *
227     * This error represents problems in the initialization
228     * of the parameters of the algorithms.
229     */
230    class UninitializedParameter : public lemon::UninitializedParameter {
231    public:
[2151]232      virtual const char* what() const throw() {
[1218]233        return "lemon::Dijkstra::UninitializedParameter";
[1125]234      }
235    };
[1119]236
[953]237    typedef TR Traits;
[584]238    ///The type of the underlying graph.
[954]239    typedef typename TR::Graph Graph;
[911]240    ///\e
[255]241    typedef typename Graph::Node Node;
[911]242    ///\e
[255]243    typedef typename Graph::NodeIt NodeIt;
[911]244    ///\e
[255]245    typedef typename Graph::Edge Edge;
[911]246    ///\e
[255]247    typedef typename Graph::OutEdgeIt OutEdgeIt;
248   
[584]249    ///The type of the length of the edges.
[987]250    typedef typename TR::LengthMap::Value Value;
[693]251    ///The type of the map that stores the edge lengths.
[954]252    typedef typename TR::LengthMap LengthMap;
[693]253    ///\brief The type of the map that stores the last
[584]254    ///edges of the shortest paths.
[953]255    typedef typename TR::PredMap PredMap;
[1218]256    ///The type of the map indicating if a node is processed.
257    typedef typename TR::ProcessedMap ProcessedMap;
[693]258    ///The type of the map that stores the dists of the nodes.
[953]259    typedef typename TR::DistMap DistMap;
[1721]260    ///The cross reference type used for the current heap.
261    typedef typename TR::HeapCrossRef HeapCrossRef;
[953]262    ///The heap type used by the dijkstra algorithm.
263    typedef typename TR::Heap Heap;
[2537]264    ///The operation traits.
265    typedef typename TR::OperationTraits OperationTraits;
[255]266  private:
[802]267    /// Pointer to the underlying graph.
[688]268    const Graph *G;
[802]269    /// Pointer to the length map
[954]270    const LengthMap *length;
[802]271    ///Pointer to the map of predecessors edges.
[1119]272    PredMap *_pred;
273    ///Indicates if \ref _pred is locally allocated (\c true) or not.
274    bool local_pred;
[802]275    ///Pointer to the map of distances.
[1130]276    DistMap *_dist;
277    ///Indicates if \ref _dist is locally allocated (\c true) or not.
278    bool local_dist;
[1218]279    ///Pointer to the map of processed status of the nodes.
280    ProcessedMap *_processed;
281    ///Indicates if \ref _processed is locally allocated (\c true) or not.
282    bool local_processed;
[1721]283    ///Pointer to the heap cross references.
284    HeapCrossRef *_heap_cross_ref;
285    ///Indicates if \ref _heap_cross_ref is locally allocated (\c true) or not.
286    bool local_heap_cross_ref;
287    ///Pointer to the heap.
288    Heap *_heap;
289    ///Indicates if \ref _heap is locally allocated (\c true) or not.
290    bool local_heap;
[688]291
[1128]292    ///Creates the maps if necessary.
[688]293   
294    ///\todo Better memory allocation (instead of new).
[1128]295    void create_maps()
[688]296    {
[1119]297      if(!_pred) {
298        local_pred = true;
299        _pred = Traits::createPredMap(*G);
[688]300      }
[1130]301      if(!_dist) {
302        local_dist = true;
303        _dist = Traits::createDistMap(*G);
[688]304      }
[1218]305      if(!_processed) {
306        local_processed = true;
307        _processed = Traits::createProcessedMap(*G);
[1119]308      }
[1721]309      if (!_heap_cross_ref) {
310        local_heap_cross_ref = true;
311        _heap_cross_ref = Traits::createHeapCrossRef(*G);
312      }
313      if (!_heap) {
314        local_heap = true;
315        _heap = Traits::createHeap(*_heap_cross_ref);
316      }
[688]317    }
[255]318   
319  public :
[1710]320
321    typedef Dijkstra Create;
[1116]322 
[1128]323    ///\name Named template parameters
324
325    ///@{
326
[953]327    template <class T>
[1116]328    struct DefPredMapTraits : public Traits {
[953]329      typedef T PredMap;
[2010]330      static PredMap *createPredMap(const Graph &)
[953]331      {
[1126]332        throw UninitializedParameter();
[953]333      }
334    };
[954]335    ///\ref named-templ-param "Named parameter" for setting PredMap type
336
337    ///\ref named-templ-param "Named parameter" for setting PredMap type
[1043]338    ///
[953]339    template <class T>
[1709]340    struct DefPredMap
341      : public Dijkstra< Graph, LengthMap, DefPredMapTraits<T> > {
342      typedef Dijkstra< Graph,  LengthMap, DefPredMapTraits<T> > Create;
343    };
[953]344   
345    template <class T>
[1116]346    struct DefDistMapTraits : public Traits {
[953]347      typedef T DistMap;
[2010]348      static DistMap *createDistMap(const Graph &)
[953]349      {
[1126]350        throw UninitializedParameter();
[953]351      }
352    };
[954]353    ///\ref named-templ-param "Named parameter" for setting DistMap type
354
355    ///\ref named-templ-param "Named parameter" for setting DistMap type
[1043]356    ///
[953]357    template <class T>
[1709]358    struct DefDistMap
359      : public Dijkstra< Graph, LengthMap, DefDistMapTraits<T> > {
360      typedef Dijkstra< Graph, LengthMap, DefDistMapTraits<T> > Create;
361    };
[953]362   
[1128]363    template <class T>
[1218]364    struct DefProcessedMapTraits : public Traits {
365      typedef T ProcessedMap;
366      static ProcessedMap *createProcessedMap(const Graph &G)
[1128]367      {
368        throw UninitializedParameter();
369      }
370    };
[1218]371    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
[1128]372
[1218]373    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
[1128]374    ///
375    template <class T>
[1709]376    struct DefProcessedMap
377      : public Dijkstra< Graph, LengthMap, DefProcessedMapTraits<T> > {
378      typedef Dijkstra< Graph,  LengthMap, DefProcessedMapTraits<T> > Create;
379    };
[1128]380   
[1218]381    struct DefGraphProcessedMapTraits : public Traits {
382      typedef typename Graph::template NodeMap<bool> ProcessedMap;
383      static ProcessedMap *createProcessedMap(const Graph &G)
[1128]384      {
[1218]385        return new ProcessedMap(G);
[1128]386      }
387    };
388    ///\brief \ref named-templ-param "Named parameter"
[1218]389    ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
[1128]390    ///
391    ///\ref named-templ-param "Named parameter"
[1218]392    ///for setting the ProcessedMap type to be Graph::NodeMap<bool>.
[1128]393    ///If you don't set it explicitely, it will be automatically allocated.
394    template <class T>
[1709]395    struct DefProcessedMapToBeDefaultMap
396      : public Dijkstra< Graph, LengthMap, DefGraphProcessedMapTraits> {
397      typedef Dijkstra< Graph, LengthMap, DefGraphProcessedMapTraits> Create;
398    };
[1721]399
400    template <class H, class CR>
401    struct DefHeapTraits : public Traits {
402      typedef CR HeapCrossRef;
403      typedef H Heap;
[1741]404      static HeapCrossRef *createHeapCrossRef(const Graph &) {
405        throw UninitializedParameter();
[1721]406      }
[1741]407      static Heap *createHeap(HeapCrossRef &)
[1721]408      {
[1741]409        throw UninitializedParameter();
[1721]410      }
411    };
[2230]412    ///\brief \ref named-templ-param "Named parameter" for setting
413    ///heap and cross reference type
414    ///
[1721]415    ///\ref named-templ-param "Named parameter" for setting heap and cross
416    ///reference type
417    ///
418    template <class H, class CR = typename Graph::template NodeMap<int> >
419    struct DefHeap
420      : public Dijkstra< Graph, LengthMap, DefHeapTraits<H, CR> > {
421      typedef Dijkstra< Graph,  LengthMap, DefHeapTraits<H, CR> > Create;
422    };
[1741]423
424    template <class H, class CR>
425    struct DefStandardHeapTraits : public Traits {
426      typedef CR HeapCrossRef;
427      typedef H Heap;
428      static HeapCrossRef *createHeapCrossRef(const Graph &G) {
429        return new HeapCrossRef(G);
430      }
431      static Heap *createHeap(HeapCrossRef &R)
432      {
433        return new Heap(R);
434      }
435    };
[2230]436    ///\brief \ref named-templ-param "Named parameter" for setting
437    ///heap and cross reference type with automatic allocation
438    ///
[1741]439    ///\ref named-templ-param "Named parameter" for setting heap and cross
440    ///reference type. It can allocate the heap and the cross reference
441    ///object if the cross reference's constructor waits for the graph as
442    ///parameter and the heap's constructor waits for the cross reference.
443    template <class H, class CR = typename Graph::template NodeMap<int> >
444    struct DefStandardHeap
445      : public Dijkstra< Graph, LengthMap, DefStandardHeapTraits<H, CR> > {
446      typedef Dijkstra< Graph,  LengthMap, DefStandardHeapTraits<H, CR> >
447      Create;
448    };
[2537]449
450    template <class T>
451    struct DefOperationTraitsTraits : public Traits {
452      typedef T OperationTraits;
453    };
454   
455    /// \brief \ref named-templ-param "Named parameter" for setting
456    /// OperationTraits type
457    ///
458    /// \ref named-templ-param "Named parameter" for setting OperationTraits
459    /// type
460    template <class T>
461    struct DefOperationTraits
462      : public Dijkstra<Graph, LengthMap, DefOperationTraitsTraits<T> > {
463      typedef Dijkstra<Graph, LengthMap, DefOperationTraitsTraits<T> >
464      Create;
465    };
[1128]466   
467    ///@}
468
469
[1710]470  protected:
471
472    Dijkstra() {}
473
[1128]474  public:     
475   
[802]476    ///Constructor.
[255]477   
[802]478    ///\param _G the graph the algorithm will run on.
479    ///\param _length the length map used by the algorithm.
[954]480    Dijkstra(const Graph& _G, const LengthMap& _length) :
[688]481      G(&_G), length(&_length),
[1119]482      _pred(NULL), local_pred(false),
[1130]483      _dist(NULL), local_dist(false),
[1218]484      _processed(NULL), local_processed(false),
[1721]485      _heap_cross_ref(NULL), local_heap_cross_ref(false),
486      _heap(NULL), local_heap(false)
[688]487    { }
488   
[802]489    ///Destructor.
[688]490    ~Dijkstra()
491    {
[1119]492      if(local_pred) delete _pred;
[1130]493      if(local_dist) delete _dist;
[1218]494      if(local_processed) delete _processed;
[1721]495      if(local_heap_cross_ref) delete _heap_cross_ref;
496      if(local_heap) delete _heap;
[688]497    }
498
499    ///Sets the length map.
500
501    ///Sets the length map.
502    ///\return <tt> (*this) </tt>
[1116]503    Dijkstra &lengthMap(const LengthMap &m)
[688]504    {
505      length = &m;
506      return *this;
507    }
508
509    ///Sets the map storing the predecessor edges.
510
511    ///Sets the map storing the predecessor edges.
512    ///If you don't use this function before calling \ref run(),
513    ///it will allocate one. The destuctor deallocates this
514    ///automatically allocated map, of course.
515    ///\return <tt> (*this) </tt>
[1116]516    Dijkstra &predMap(PredMap &m)
[688]517    {
[1119]518      if(local_pred) {
519        delete _pred;
520        local_pred=false;
[688]521      }
[1119]522      _pred = &m;
[688]523      return *this;
524    }
525
526    ///Sets the map storing the distances calculated by the algorithm.
527
528    ///Sets the map storing the distances calculated by the algorithm.
529    ///If you don't use this function before calling \ref run(),
530    ///it will allocate one. The destuctor deallocates this
531    ///automatically allocated map, of course.
532    ///\return <tt> (*this) </tt>
[1116]533    Dijkstra &distMap(DistMap &m)
[688]534    {
[1130]535      if(local_dist) {
536        delete _dist;
537        local_dist=false;
[688]538      }
[1130]539      _dist = &m;
[688]540      return *this;
541    }
[694]542
[1741]543    ///Sets the heap and the cross reference used by algorithm.
544
545    ///Sets the heap and the cross reference used by algorithm.
546    ///If you don't use this function before calling \ref run(),
547    ///it will allocate one. The destuctor deallocates this
[1981]548    ///automatically allocated heap and cross reference, of course.
[1741]549    ///\return <tt> (*this) </tt>
[2386]550    Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
[1741]551    {
552      if(local_heap_cross_ref) {
553        delete _heap_cross_ref;
554        local_heap_cross_ref=false;
555      }
[2386]556      _heap_cross_ref = &cr;
[1741]557      if(local_heap) {
558        delete _heap;
559        local_heap=false;
560      }
[2386]561      _heap = &hp;
[1741]562      return *this;
563    }
564
[1130]565  private:
566    void finalizeNodeData(Node v,Value dst)
567    {
[1218]568      _processed->set(v,true);
[1130]569      _dist->set(v, dst);
570    }
571
572  public:
[2354]573
574    typedef PredMapPath<Graph, PredMap> Path;
575
[1218]576    ///\name Execution control
[1128]577    ///The simplest way to execute the algorithm is to use
[1156]578    ///one of the member functions called \c run(...).
[1128]579    ///\n
[1218]580    ///If you need more control on the execution,
[1128]581    ///first you must call \ref init(), then you can add several source nodes
[1218]582    ///with \ref addSource().
583    ///Finally \ref start() will perform the actual path
[1128]584    ///computation.
585
586    ///@{
587
588    ///Initializes the internal data structures.
589
590    ///Initializes the internal data structures.
591    ///
592    void init()
593    {
594      create_maps();
[1721]595      _heap->clear();
[774]596      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
[1119]597        _pred->set(u,INVALID);
[1218]598        _processed->set(u,false);
[1721]599        _heap_cross_ref->set(u,Heap::PRE_HEAP);
[694]600      }
[1128]601    }
602   
603    ///Adds a new source node.
604
[1155]605    ///Adds a new source node to the priority heap.
[1128]606    ///
607    ///The optional second parameter is the initial distance of the node.
608    ///
[1155]609    ///It checks if the node has already been added to the heap and
[1988]610    ///it is pushed to the heap only if either it was not in the heap
611    ///or the shortest path found till then is shorter than \c dst.
[2537]612    void addSource(Node s,Value dst=OperationTraits::zero())
[1128]613    {
[1721]614      if(_heap->state(s) != Heap::IN_HEAP) {
615        _heap->push(s,dst);
[2537]616      } else if(OperationTraits::less((*_heap)[s], dst)) {
[1988]617        _heap->set(s,dst);
[1155]618        _pred->set(s,INVALID);
619      }
[1128]620    }
621   
[1155]622    ///Processes the next node in the priority heap
623
624    ///Processes the next node in the priority heap.
625    ///
[1516]626    ///\return The processed node.
627    ///
[1155]628    ///\warning The priority heap must not be empty!
[1516]629    Node processNextNode()
[1128]630    {
[1721]631      Node v=_heap->top();
632      Value oldvalue=_heap->prio();
633      _heap->pop();
[1130]634      finalizeNodeData(v,oldvalue);
[694]635     
[1128]636      for(OutEdgeIt e(*G,v); e!=INVALID; ++e) {
637        Node w=G->target(e);
[1721]638        switch(_heap->state(w)) {
[1128]639        case Heap::PRE_HEAP:
[2537]640          _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
[1128]641          _pred->set(w,e);
642          break;
643        case Heap::IN_HEAP:
[2537]644          {
645            Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
646            if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
647              _heap->decrease(w, newvalue);
648              _pred->set(w,e);
649            }
[694]650          }
[1128]651          break;
652        case Heap::POST_HEAP:
653          break;
[694]654        }
655      }
[1516]656      return v;
[694]657    }
[1128]658
[1665]659    ///Next node to be processed.
660   
661    ///Next node to be processed.
662    ///
663    ///\return The next node to be processed or INVALID if the priority heap
664    /// is empty.
[1694]665    Node nextNode()
[1665]666    {
[2439]667      return !_heap->empty()?_heap->top():INVALID;
[1665]668    }
669 
[1218]670    ///\brief Returns \c false if there are nodes
671    ///to be processed in the priority heap
[1155]672    ///
[1218]673    ///Returns \c false if there are nodes
674    ///to be processed in the priority heap
[1721]675    bool emptyQueue() { return _heap->empty(); }
[1155]676    ///Returns the number of the nodes to be processed in the priority heap
677
678    ///Returns the number of the nodes to be processed in the priority heap
679    ///
[1721]680    int queueSize() { return _heap->size(); }
[1155]681   
[1130]682    ///Executes the algorithm.
[1128]683
[1130]684    ///Executes the algorithm.
[1128]685    ///
[1130]686    ///\pre init() must be called and at least one node should be added
687    ///with addSource() before using this function.
[1128]688    ///
689    ///This method runs the %Dijkstra algorithm from the root node(s)
690    ///in order to
691    ///compute the
692    ///shortest path to each node. The algorithm computes
693    ///- The shortest path tree.
694    ///- The distance of each node from the root(s).
695    ///
696    void start()
697    {
[1721]698      while ( !_heap->empty() ) processNextNode();
[1128]699    }
[255]700   
[1130]701    ///Executes the algorithm until \c dest is reached.
[1128]702
[1130]703    ///Executes the algorithm until \c dest is reached.
[1128]704    ///
[1130]705    ///\pre init() must be called and at least one node should be added
706    ///with addSource() before using this function.
[1128]707    ///
708    ///This method runs the %Dijkstra algorithm from the root node(s)
709    ///in order to
710    ///compute the
711    ///shortest path to \c dest. The algorithm computes
712    ///- The shortest path to \c  dest.
713    ///- The distance of \c dest from the root(s).
714    ///
715    void start(Node dest)
716    {
[1721]717      while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
718      if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
[1130]719    }
720   
721    ///Executes the algorithm until a condition is met.
722
723    ///Executes the algorithm until a condition is met.
724    ///
725    ///\pre init() must be called and at least one node should be added
726    ///with addSource() before using this function.
727    ///
728    ///\param nm must be a bool (or convertible) node map. The algorithm
[2443]729    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
[2439]730    ///
[2476]731    ///\return The reached node \c v with <tt>nm[v]</tt> true or
[2439]732    ///\c INVALID if no such node was found.
[1345]733    template<class NodeBoolMap>
[2439]734    Node start(const NodeBoolMap &nm)
[1130]735    {
[1721]736      while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
[2439]737      if ( _heap->empty() ) return INVALID;
738      finalizeNodeData(_heap->top(),_heap->prio());
739      return _heap->top();
[1128]740    }
741   
742    ///Runs %Dijkstra algorithm from node \c s.
743   
744    ///This method runs the %Dijkstra algorithm from a root node \c s
745    ///in order to
746    ///compute the
747    ///shortest path to each node. The algorithm computes
748    ///- The shortest path tree.
749    ///- The distance of each node from the root.
750    ///
751    ///\note d.run(s) is just a shortcut of the following code.
752    ///\code
753    ///  d.init();
754    ///  d.addSource(s);
755    ///  d.start();
756    ///\endcode
757    void run(Node s) {
758      init();
759      addSource(s);
760      start();
761    }
762   
[1130]763    ///Finds the shortest path between \c s and \c t.
764   
765    ///Finds the shortest path between \c s and \c t.
766    ///
767    ///\return The length of the shortest s---t path if there exists one,
768    ///0 otherwise.
769    ///\note Apart from the return value, d.run(s) is
770    ///just a shortcut of the following code.
771    ///\code
772    ///  d.init();
773    ///  d.addSource(s);
774    ///  d.start(t);
775    ///\endcode
776    Value run(Node s,Node t) {
777      init();
778      addSource(s);
779      start(t);
[2537]780      return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t];
[1130]781    }
782   
[1128]783    ///@}
784
785    ///\name Query Functions
786    ///The result of the %Dijkstra algorithm can be obtained using these
787    ///functions.\n
788    ///Before the use of these functions,
789    ///either run() or start() must be called.
790   
791    ///@{
792
[2335]793    ///Gives back the shortest path.
[1283]794   
[2335]795    ///Gives back the shortest path.
796    ///\pre The \c t should be reachable from the source.
797    Path path(Node t)
[1283]798    {
[2335]799      return Path(*G, *_pred, t);
[1283]800    }
[2335]801
[385]802    ///The distance of a node from the root.
[255]803
[385]804    ///Returns the distance of a node from the root.
[255]805    ///\pre \ref run() must be called before using this function.
[385]806    ///\warning If node \c v in unreachable from the root the return value
[255]807    ///of this funcion is undefined.
[1130]808    Value dist(Node v) const { return (*_dist)[v]; }
[373]809
[2358]810    ///The current distance of a node from the root.
811
812    ///Returns the current distance of a node from the root.
813    ///It may be decreased in the following processes.
814    ///\pre \c node should be reached but not processed
815    Value currentDist(Node v) const { return (*_heap)[v]; }
816
[584]817    ///Returns the 'previous edge' of the shortest path tree.
[255]818
[584]819    ///For a node \c v it returns the 'previous edge' of the shortest path tree,
[785]820    ///i.e. it returns the last edge of a shortest path from the root to \c
[688]821    ///v. It is \ref INVALID
822    ///if \c v is unreachable from the root or if \c v=s. The
[385]823    ///shortest path tree used here is equal to the shortest path tree used in
[1631]824    ///\ref predNode().  \pre \ref run() must be called before using
[385]825    ///this function.
[1763]826    Edge predEdge(Node v) const { return (*_pred)[v]; }
[373]827
[584]828    ///Returns the 'previous node' of the shortest path tree.
[255]829
[584]830    ///For a node \c v it returns the 'previous node' of the shortest path tree,
[385]831    ///i.e. it returns the last but one node from a shortest path from the
832    ///root to \c /v. It is INVALID if \c v is unreachable from the root or if
833    ///\c v=s. The shortest path tree used here is equal to the shortest path
[1763]834    ///tree used in \ref predEdge().  \pre \ref run() must be called before
[385]835    ///using this function.
[1130]836    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
837                                  G->source((*_pred)[v]); }
[255]838   
839    ///Returns a reference to the NodeMap of distances.
840
[385]841    ///Returns a reference to the NodeMap of distances. \pre \ref run() must
842    ///be called before using this function.
[1130]843    const DistMap &distMap() const { return *_dist;}
[385]844 
[255]845    ///Returns a reference to the shortest path tree map.
846
847    ///Returns a reference to the NodeMap of the edges of the
848    ///shortest path tree.
849    ///\pre \ref run() must be called before using this function.
[1119]850    const PredMap &predMap() const { return *_pred;}
[385]851 
852    ///Checks if a node is reachable from the root.
[255]853
[385]854    ///Returns \c true if \c v is reachable from the root.
[1218]855    ///\warning The source nodes are inditated as unreached.
[255]856    ///\pre \ref run() must be called before using this function.
[385]857    ///
[1721]858    bool reached(Node v) { return (*_heap_cross_ref)[v] != Heap::PRE_HEAP; }
[1734]859
860    ///Checks if a node is processed.
861
862    ///Returns \c true if \c v is processed, i.e. the shortest
863    ///path to \c v has already found.
864    ///\pre \ref run() must be called before using this function.
865    ///
866    bool processed(Node v) { return (*_heap_cross_ref)[v] == Heap::POST_HEAP; }
[255]867   
[1128]868    ///@}
[255]869  };
[953]870
[1218]871
872
873
874 
875  ///Default traits class of Dijkstra function.
876
877  ///Default traits class of Dijkstra function.
878  ///\param GR Graph type.
879  ///\param LM Type of length map.
880  template<class GR, class LM>
881  struct DijkstraWizardDefaultTraits
882  {
883    ///The graph type the algorithm runs on.
884    typedef GR Graph;
885    ///The type of the map that stores the edge lengths.
886
887    ///The type of the map that stores the edge lengths.
[2260]888    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
[1218]889    typedef LM LengthMap;
890    //The type of the length of the edges.
891    typedef typename LM::Value Value;
[2537]892    /// Operation traits for Dijkstra algorithm.
893
894    /// It defines the used operation by the algorithm.
895    /// \see DijkstraDefaultOperationTraits
896    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
[1218]897    ///The heap type used by Dijkstra algorithm.
898
[1721]899    /// The cross reference type used by heap.
900
901    /// The cross reference type used by heap.
902    /// Usually it is \c Graph::NodeMap<int>.
903    typedef typename Graph::template NodeMap<int> HeapCrossRef;
904    ///Instantiates a HeapCrossRef.
905
906    ///This function instantiates a \ref HeapCrossRef.
907    /// \param G is the graph, to which we would like to define the
908    /// HeapCrossRef.
909    /// \todo The graph alone may be insufficient for the initialization
910    static HeapCrossRef *createHeapCrossRef(const GR &G)
911    {
912      return new HeapCrossRef(G);
913    }
914   
915    ///The heap type used by Dijkstra algorithm.
916
[1218]917    ///The heap type used by Dijkstra algorithm.
918    ///
919    ///\sa BinHeap
920    ///\sa Dijkstra
[2263]921    typedef BinHeap<typename LM::Value, typename GR::template NodeMap<int>,
[1218]922                    std::less<Value> > Heap;
923
[1721]924    static Heap *createHeap(HeapCrossRef& R)
925    {
926      return new Heap(R);
927    }
928
[1218]929    ///\brief The type of the map that stores the last
930    ///edges of the shortest paths.
931    ///
932    ///The type of the map that stores the last
933    ///edges of the shortest paths.
[2260]934    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[1218]935    ///
936    typedef NullMap <typename GR::Node,typename GR::Edge> PredMap;
937    ///Instantiates a PredMap.
938 
939    ///This function instantiates a \ref PredMap.
[1536]940    ///\param g is the graph, to which we would like to define the PredMap.
[1218]941    ///\todo The graph alone may be insufficient for the initialization
[1536]942#ifdef DOXYGEN
943    static PredMap *createPredMap(const GR &g)
944#else
[1367]945    static PredMap *createPredMap(const GR &)
[1536]946#endif
[1218]947    {
948      return new PredMap();
949    }
950    ///The type of the map that stores whether a nodes is processed.
951 
952    ///The type of the map that stores whether a nodes is processed.
[2260]953    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[1218]954    ///By default it is a NullMap.
955    ///\todo If it is set to a real map,
956    ///Dijkstra::processed() should read this.
957    ///\todo named parameter to set this type, function to read and write.
958    typedef NullMap<typename Graph::Node,bool> ProcessedMap;
959    ///Instantiates a ProcessedMap.
960 
961    ///This function instantiates a \ref ProcessedMap.
[1536]962    ///\param g is the graph, to which
[1218]963    ///we would like to define the \ref ProcessedMap
[1536]964#ifdef DOXYGEN
965    static ProcessedMap *createProcessedMap(const GR &g)
966#else
[1367]967    static ProcessedMap *createProcessedMap(const GR &)
[1536]968#endif
[1218]969    {
970      return new ProcessedMap();
971    }
972    ///The type of the map that stores the dists of the nodes.
973 
974    ///The type of the map that stores the dists of the nodes.
[2260]975    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
[1218]976    ///
977    typedef NullMap<typename Graph::Node,typename LM::Value> DistMap;
978    ///Instantiates a DistMap.
979 
980    ///This function instantiates a \ref DistMap.
[1536]981    ///\param g is the graph, to which we would like to define the \ref DistMap
982#ifdef DOXYGEN
983    static DistMap *createDistMap(const GR &g)
984#else
[1367]985    static DistMap *createDistMap(const GR &)
[1536]986#endif
[1218]987    {
988      return new DistMap();
989    }
990  };
991 
[1123]992  /// Default traits used by \ref DijkstraWizard
993
[1151]994  /// To make it easier to use Dijkstra algorithm
995  ///we have created a wizard class.
996  /// This \ref DijkstraWizard class needs default traits,
997  ///as well as the \ref Dijkstra class.
[1123]998  /// The \ref DijkstraWizardBase is a class to be the default traits of the
999  /// \ref DijkstraWizard class.
[1220]1000  /// \todo More named parameters are required...
[1116]1001  template<class GR,class LM>
[1218]1002  class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
[1116]1003  {
1004
[1218]1005    typedef DijkstraWizardDefaultTraits<GR,LM> Base;
[1116]1006  protected:
[1201]1007    /// Type of the nodes in the graph.
1008    typedef typename Base::Graph::Node Node;
1009
[1116]1010    /// Pointer to the underlying graph.
1011    void *_g;
1012    /// Pointer to the length map
1013    void *_length;
1014    ///Pointer to the map of predecessors edges.
1015    void *_pred;
1016    ///Pointer to the map of distances.
1017    void *_dist;
1018    ///Pointer to the source node.
[1201]1019    Node _source;
[1116]1020
1021    public:
[1123]1022    /// Constructor.
1023   
1024    /// This constructor does not require parameters, therefore it initiates
1025    /// all of the attributes to default values (0, INVALID).
[1218]1026    DijkstraWizardBase() : _g(0), _length(0), _pred(0),
1027                           _dist(0), _source(INVALID) {}
[1116]1028
[1123]1029    /// Constructor.
1030   
[1156]1031    /// This constructor requires some parameters,
1032    /// listed in the parameters list.
[1123]1033    /// Others are initiated to 0.
1034    /// \param g is the initial value of  \ref _g
1035    /// \param l is the initial value of  \ref _length
1036    /// \param s is the initial value of  \ref _source
[1116]1037    DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
[2386]1038      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1039      _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1040      _pred(0), _dist(0), _source(s) {}
[1116]1041
1042  };
1043 
[1229]1044  /// A class to make the usage of Dijkstra algorithm easier
[953]1045
[1123]1046  /// This class is created to make it easier to use Dijkstra algorithm.
1047  /// It uses the functions and features of the plain \ref Dijkstra,
[1151]1048  /// but it is much simpler to use it.
[953]1049  ///
[1123]1050  /// Simplicity means that the way to change the types defined
1051  /// in the traits class is based on functions that returns the new class
[1151]1052  /// and not on templatable built-in classes.
1053  /// When using the plain \ref Dijkstra
1054  /// the new class with the modified type comes from
1055  /// the original class by using the ::
1056  /// operator. In the case of \ref DijkstraWizard only
1057  /// a function have to be called and it will
[1123]1058  /// return the needed class.
1059  ///
1060  /// It does not have own \ref run method. When its \ref run method is called
[1721]1061  /// it initiates a plain \ref Dijkstra class, and calls the \ref
1062  /// Dijkstra::run method of it.
[953]1063  template<class TR>
[1116]1064  class DijkstraWizard : public TR
[953]1065  {
[1116]1066    typedef TR Base;
[953]1067
[1123]1068    ///The type of the underlying graph.
[953]1069    typedef typename TR::Graph Graph;
[1119]1070    //\e
[953]1071    typedef typename Graph::Node Node;
[1119]1072    //\e
[953]1073    typedef typename Graph::NodeIt NodeIt;
[1119]1074    //\e
[953]1075    typedef typename Graph::Edge Edge;
[1119]1076    //\e
[953]1077    typedef typename Graph::OutEdgeIt OutEdgeIt;
1078   
[1123]1079    ///The type of the map that stores the edge lengths.
[953]1080    typedef typename TR::LengthMap LengthMap;
[1123]1081    ///The type of the length of the edges.
[987]1082    typedef typename LengthMap::Value Value;
[1123]1083    ///\brief The type of the map that stores the last
1084    ///edges of the shortest paths.
[953]1085    typedef typename TR::PredMap PredMap;
[1123]1086    ///The type of the map that stores the dists of the nodes.
[953]1087    typedef typename TR::DistMap DistMap;
[1123]1088    ///The heap type used by the dijkstra algorithm.
[953]1089    typedef typename TR::Heap Heap;
[2269]1090  public:
[1123]1091    /// Constructor.
[1116]1092    DijkstraWizard() : TR() {}
[953]1093
[1123]1094    /// Constructor that requires parameters.
[1124]1095
1096    /// Constructor that requires parameters.
[1123]1097    /// These parameters will be the default values for the traits class.
[1116]1098    DijkstraWizard(const Graph &g,const LengthMap &l, Node s=INVALID) :
1099      TR(g,l,s) {}
[953]1100
[1123]1101    ///Copy constructor
[1116]1102    DijkstraWizard(const TR &b) : TR(b) {}
[953]1103
[1116]1104    ~DijkstraWizard() {}
1105
[1123]1106    ///Runs Dijkstra algorithm from a given node.
1107   
1108    ///Runs Dijkstra algorithm from a given node.
1109    ///The node can be given by the \ref source function.
[1116]1110    void run()
[953]1111    {
[1201]1112      if(Base::_source==INVALID) throw UninitializedParameter();
[1193]1113      Dijkstra<Graph,LengthMap,TR>
[2386]1114        dij(*reinterpret_cast<const Graph*>(Base::_g),
1115            *reinterpret_cast<const LengthMap*>(Base::_length));
1116      if(Base::_pred) dij.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1117      if(Base::_dist) dij.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
[1345]1118      dij.run(Base::_source);
[1116]1119    }
1120
[1124]1121    ///Runs Dijkstra algorithm from the given node.
[1123]1122
[1124]1123    ///Runs Dijkstra algorithm from the given node.
[1123]1124    ///\param s is the given source.
[1116]1125    void run(Node s)
1126    {
[1201]1127      Base::_source=s;
[1116]1128      run();
[953]1129    }
1130
1131    template<class T>
[1116]1132    struct DefPredMapBase : public Base {
1133      typedef T PredMap;
[1367]1134      static PredMap *createPredMap(const Graph &) { return 0; };
[1236]1135      DefPredMapBase(const TR &b) : TR(b) {}
[1116]1136    };
[953]1137   
[1156]1138    ///\brief \ref named-templ-param "Named parameter"
1139    ///function for setting PredMap type
1140    ///
1141    /// \ref named-templ-param "Named parameter"
1142    ///function for setting PredMap type
[1124]1143    ///
[953]1144    template<class T>
[1116]1145    DijkstraWizard<DefPredMapBase<T> > predMap(const T &t)
[953]1146    {
[2386]1147      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
[1116]1148      return DijkstraWizard<DefPredMapBase<T> >(*this);
[953]1149    }
1150   
[1116]1151    template<class T>
1152    struct DefDistMapBase : public Base {
1153      typedef T DistMap;
[1367]1154      static DistMap *createDistMap(const Graph &) { return 0; };
[1236]1155      DefDistMapBase(const TR &b) : TR(b) {}
[1116]1156    };
[953]1157   
[1156]1158    ///\brief \ref named-templ-param "Named parameter"
1159    ///function for setting DistMap type
1160    ///
1161    /// \ref named-templ-param "Named parameter"
1162    ///function for setting DistMap type
[1124]1163    ///
[953]1164    template<class T>
[1116]1165    DijkstraWizard<DefDistMapBase<T> > distMap(const T &t)
[953]1166    {
[2386]1167      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
[1116]1168      return DijkstraWizard<DefDistMapBase<T> >(*this);
[953]1169    }
[1117]1170   
[1123]1171    /// Sets the source node, from which the Dijkstra algorithm runs.
1172
1173    /// Sets the source node, from which the Dijkstra algorithm runs.
1174    /// \param s is the source node.
[1117]1175    DijkstraWizard<TR> &source(Node s)
[953]1176    {
[1201]1177      Base::_source=s;
[953]1178      return *this;
1179    }
1180   
1181  };
[255]1182 
[1218]1183  ///Function type interface for Dijkstra algorithm.
[953]1184
[2376]1185  /// \ingroup shortest_path
[1218]1186  ///Function type interface for Dijkstra algorithm.
[953]1187  ///
[1218]1188  ///This function also has several
1189  ///\ref named-templ-func-param "named parameters",
1190  ///they are declared as the members of class \ref DijkstraWizard.
1191  ///The following
1192  ///example shows how to use these parameters.
1193  ///\code
1194  ///  dijkstra(g,length,source).predMap(preds).run();
1195  ///\endcode
1196  ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1197  ///to the end of the parameter list.
1198  ///\sa DijkstraWizard
1199  ///\sa Dijkstra
[953]1200  template<class GR, class LM>
[1116]1201  DijkstraWizard<DijkstraWizardBase<GR,LM> >
1202  dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
[953]1203  {
[1116]1204    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
[953]1205  }
1206
[921]1207} //END OF NAMESPACE LEMON
[255]1208
1209#endif
Note: See TracBrowser for help on using the repository browser.