COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/dijkstra.h @ 882:ece1f8a3052d

Last change on this file since 882:ece1f8a3052d was 584:33c6b6e755cd, checked in by Peter Kovacs <kpeter@…>, 16 years ago

Small doc improvements (#263)

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