COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dijkstra.h @ 1734:2fb5ceac10e7

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