COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dijkstra.h @ 1874:396831fa7012

Last change on this file since 1874:396831fa7012 was 1765:f15b3c09481c, checked in by Balazs Dezso, 14 years ago

Removing todos

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