COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/dijkstra.h @ 1709:a323456bf7c8

Last change on this file since 1709:a323456bf7c8 was 1709:a323456bf7c8, checked in by Balazs Dezso, 14 years ago

Template Named Parameter bugfix

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