COIN-OR::LEMON - Graph Library

source: lemon/lemon/dijkstra.h @ 237:9c8efad5f587

Last change on this file since 237:9c8efad5f587 was 220:a5d8c039f218, checked in by Balazs Dezso <deba@…>, 12 years ago

Reorganize header files (Ticket #97)

In addition on some places the DefaultMap?<G, K, V> is replaced with
ItemSetTraits?<G, K>::template Map<V>::Type, to decrease the dependencies
of different tools. It is obviously better solution.

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