Fix wrong iteration in ListGraph snapshot, part II. (#598)
1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_DIJKSTRA_H
20 #define LEMON_DIJKSTRA_H
22 ///\ingroup shortest_path
24 ///\brief Dijkstra algorithm.
27 #include <lemon/list_graph.h>
28 #include <lemon/bin_heap.h>
29 #include <lemon/bits/path_dump.h>
30 #include <lemon/core.h>
31 #include <lemon/error.h>
32 #include <lemon/maps.h>
33 #include <lemon/path.h>
37 /// \brief Default operation traits for the Dijkstra algorithm class.
39 /// This operation traits class defines all computational operations and
40 /// constants which are used in the Dijkstra algorithm.
42 struct DijkstraDefaultOperationTraits {
45 /// \brief Gives back the zero value of the type.
47 return static_cast<Value>(0);
49 /// \brief Gives back the sum of the given two elements.
50 static Value plus(const Value& left, const Value& right) {
53 /// \brief Gives back true only if the first value is less than the second.
54 static bool less(const Value& left, const Value& right) {
59 ///Default traits class of Dijkstra class.
61 ///Default traits class of Dijkstra class.
62 ///\tparam GR The type of the digraph.
63 ///\tparam LEN The type of the length map.
64 template<typename GR, typename LEN>
65 struct DijkstraDefaultTraits
67 ///The type of the digraph the algorithm runs on.
70 ///The type of the map that stores the arc lengths.
72 ///The type of the map that stores the arc lengths.
73 ///It must conform to the \ref concepts::ReadMap "ReadMap" concept.
74 typedef LEN LengthMap;
75 ///The type of the arc lengths.
76 typedef typename LEN::Value Value;
78 /// Operation traits for %Dijkstra algorithm.
80 /// This class defines the operations that are used in the algorithm.
81 /// \see DijkstraDefaultOperationTraits
82 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
84 /// The cross reference type used by the heap.
86 /// The cross reference type used by the heap.
87 /// Usually it is \c Digraph::NodeMap<int>.
88 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
89 ///Instantiates a \c HeapCrossRef.
91 ///This function instantiates a \ref HeapCrossRef.
92 /// \param g is the digraph, to which we would like to define the
93 /// \ref HeapCrossRef.
94 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
96 return new HeapCrossRef(g);
99 ///The heap type used by the %Dijkstra algorithm.
101 ///The heap type used by the Dijkstra algorithm.
105 typedef BinHeap<typename LEN::Value, HeapCrossRef, std::less<Value> > Heap;
106 ///Instantiates a \c Heap.
108 ///This function instantiates a \ref Heap.
109 static Heap *createHeap(HeapCrossRef& r)
114 ///\brief The type of the map that stores the predecessor
115 ///arcs of the shortest paths.
117 ///The type of the map that stores the predecessor
118 ///arcs of the shortest paths.
119 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
120 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
121 ///Instantiates a \c PredMap.
123 ///This function instantiates a \ref PredMap.
124 ///\param g is the digraph, to which we would like to define the
126 static PredMap *createPredMap(const Digraph &g)
128 return new PredMap(g);
131 ///The type of the map that indicates which nodes are processed.
133 ///The type of the map that indicates which nodes are processed.
134 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
135 ///By default, it is a NullMap.
136 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
137 ///Instantiates a \c ProcessedMap.
139 ///This function instantiates a \ref ProcessedMap.
140 ///\param g is the digraph, to which
141 ///we would like to define the \ref ProcessedMap.
143 static ProcessedMap *createProcessedMap(const Digraph &g)
145 static ProcessedMap *createProcessedMap(const Digraph &)
148 return new ProcessedMap();
151 ///The type of the map that stores the distances of the nodes.
153 ///The type of the map that stores the distances of the nodes.
154 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
155 typedef typename Digraph::template NodeMap<typename LEN::Value> DistMap;
156 ///Instantiates a \c DistMap.
158 ///This function instantiates a \ref DistMap.
159 ///\param g is the digraph, to which we would like to define
161 static DistMap *createDistMap(const Digraph &g)
163 return new DistMap(g);
167 ///%Dijkstra algorithm class.
169 /// \ingroup shortest_path
170 ///This class provides an efficient implementation of the %Dijkstra algorithm.
172 ///The %Dijkstra algorithm solves the single-source shortest path problem
173 ///when all arc lengths are non-negative. If there are negative lengths,
174 ///the BellmanFord algorithm should be used instead.
176 ///The arc lengths are passed to the algorithm using a
177 ///\ref concepts::ReadMap "ReadMap",
178 ///so it is easy to change it to any kind of length.
179 ///The type of the length is determined by the
180 ///\ref concepts::ReadMap::Value "Value" of the length map.
181 ///It is also possible to change the underlying priority heap.
183 ///There is also a \ref dijkstra() "function-type interface" for the
184 ///%Dijkstra algorithm, which is convenient in the simplier cases and
185 ///it can be used easier.
187 ///\tparam GR The type of the digraph the algorithm runs on.
188 ///The default type is \ref ListDigraph.
189 ///\tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
190 ///the lengths of the arcs.
191 ///It is read once for each arc, so the map may involve in
192 ///relatively time consuming process to compute the arc lengths if
193 ///it is necessary. The default map type is \ref
194 ///concepts::Digraph::ArcMap "GR::ArcMap<int>".
195 ///\tparam TR The traits class that defines various types used by the
196 ///algorithm. By default, it is \ref DijkstraDefaultTraits
197 ///"DijkstraDefaultTraits<GR, LEN>".
198 ///In most cases, this parameter should not be set directly,
199 ///consider to use the named template parameters instead.
201 template <typename GR, typename LEN, typename TR>
203 template <typename GR=ListDigraph,
204 typename LEN=typename GR::template ArcMap<int>,
205 typename TR=DijkstraDefaultTraits<GR,LEN> >
210 ///The type of the digraph the algorithm runs on.
211 typedef typename TR::Digraph Digraph;
213 ///The type of the arc lengths.
214 typedef typename TR::Value Value;
215 ///The type of the map that stores the arc lengths.
216 typedef typename TR::LengthMap LengthMap;
217 ///\brief The type of the map that stores the predecessor arcs of the
219 typedef typename TR::PredMap PredMap;
220 ///The type of the map that stores the distances of the nodes.
221 typedef typename TR::DistMap DistMap;
222 ///The type of the map that indicates which nodes are processed.
223 typedef typename TR::ProcessedMap ProcessedMap;
224 ///The type of the paths.
225 typedef PredMapPath<Digraph, PredMap> Path;
226 ///The cross reference type used for the current heap.
227 typedef typename TR::HeapCrossRef HeapCrossRef;
228 ///The heap type used by the algorithm.
229 typedef typename TR::Heap Heap;
230 /// \brief The \ref lemon::DijkstraDefaultOperationTraits
231 /// "operation traits class" of the algorithm.
232 typedef typename TR::OperationTraits OperationTraits;
234 ///The \ref lemon::DijkstraDefaultTraits "traits class" of the algorithm.
239 typedef typename Digraph::Node Node;
240 typedef typename Digraph::NodeIt NodeIt;
241 typedef typename Digraph::Arc Arc;
242 typedef typename Digraph::OutArcIt OutArcIt;
244 //Pointer to the underlying digraph.
246 //Pointer to the length map.
247 const LengthMap *_length;
248 //Pointer to the map of predecessors arcs.
250 //Indicates if _pred is locally allocated (true) or not.
252 //Pointer to the map of distances.
254 //Indicates if _dist is locally allocated (true) or not.
256 //Pointer to the map of processed status of the nodes.
257 ProcessedMap *_processed;
258 //Indicates if _processed is locally allocated (true) or not.
259 bool local_processed;
260 //Pointer to the heap cross references.
261 HeapCrossRef *_heap_cross_ref;
262 //Indicates if _heap_cross_ref is locally allocated (true) or not.
263 bool local_heap_cross_ref;
264 //Pointer to the heap.
266 //Indicates if _heap is locally allocated (true) or not.
269 //Creates the maps if necessary.
274 _pred = Traits::createPredMap(*G);
278 _dist = Traits::createDistMap(*G);
281 local_processed = true;
282 _processed = Traits::createProcessedMap(*G);
284 if (!_heap_cross_ref) {
285 local_heap_cross_ref = true;
286 _heap_cross_ref = Traits::createHeapCrossRef(*G);
290 _heap = Traits::createHeap(*_heap_cross_ref);
296 typedef Dijkstra Create;
298 ///\name Named Template Parameters
303 struct SetPredMapTraits : public Traits {
305 static PredMap *createPredMap(const Digraph &)
307 LEMON_ASSERT(false, "PredMap is not initialized");
308 return 0; // ignore warnings
311 ///\brief \ref named-templ-param "Named parameter" for setting
314 ///\ref named-templ-param "Named parameter" for setting
316 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
319 : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
320 typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
324 struct SetDistMapTraits : public Traits {
326 static DistMap *createDistMap(const Digraph &)
328 LEMON_ASSERT(false, "DistMap is not initialized");
329 return 0; // ignore warnings
332 ///\brief \ref named-templ-param "Named parameter" for setting
335 ///\ref named-templ-param "Named parameter" for setting
337 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
340 : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
341 typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
345 struct SetProcessedMapTraits : public Traits {
346 typedef T ProcessedMap;
347 static ProcessedMap *createProcessedMap(const Digraph &)
349 LEMON_ASSERT(false, "ProcessedMap is not initialized");
350 return 0; // ignore warnings
353 ///\brief \ref named-templ-param "Named parameter" for setting
354 ///\c ProcessedMap type.
356 ///\ref named-templ-param "Named parameter" for setting
357 ///\c ProcessedMap type.
358 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
360 struct SetProcessedMap
361 : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
362 typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
365 struct SetStandardProcessedMapTraits : public Traits {
366 typedef typename Digraph::template NodeMap<bool> ProcessedMap;
367 static ProcessedMap *createProcessedMap(const Digraph &g)
369 return new ProcessedMap(g);
372 ///\brief \ref named-templ-param "Named parameter" for setting
373 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
375 ///\ref named-templ-param "Named parameter" for setting
376 ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
377 ///If you don't set it explicitly, it will be automatically allocated.
378 struct SetStandardProcessedMap
379 : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
380 typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
384 template <class H, class CR>
385 struct SetHeapTraits : public Traits {
386 typedef CR HeapCrossRef;
388 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
389 LEMON_ASSERT(false, "HeapCrossRef is not initialized");
390 return 0; // ignore warnings
392 static Heap *createHeap(HeapCrossRef &)
394 LEMON_ASSERT(false, "Heap is not initialized");
395 return 0; // ignore warnings
398 ///\brief \ref named-templ-param "Named parameter" for setting
399 ///heap and cross reference types
401 ///\ref named-templ-param "Named parameter" for setting heap and cross
402 ///reference types. If this named parameter is used, then external
403 ///heap and cross reference objects must be passed to the algorithm
404 ///using the \ref heap() function before calling \ref run(Node) "run()"
406 ///\sa SetStandardHeap
407 template <class H, class CR = typename Digraph::template NodeMap<int> >
409 : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
410 typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
413 template <class H, class CR>
414 struct SetStandardHeapTraits : public Traits {
415 typedef CR HeapCrossRef;
417 static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
418 return new HeapCrossRef(G);
420 static Heap *createHeap(HeapCrossRef &R)
425 ///\brief \ref named-templ-param "Named parameter" for setting
426 ///heap and cross reference types with automatic allocation
428 ///\ref named-templ-param "Named parameter" for setting heap and cross
429 ///reference types with automatic allocation.
430 ///They should have standard constructor interfaces to be able to
431 ///automatically created by the algorithm (i.e. the digraph should be
432 ///passed to the constructor of the cross reference and the cross
433 ///reference should be passed to the constructor of the heap).
434 ///However, external heap and cross reference objects could also be
435 ///passed to the algorithm using the \ref heap() function before
436 ///calling \ref run(Node) "run()" or \ref init().
438 template <class H, class CR = typename Digraph::template NodeMap<int> >
439 struct SetStandardHeap
440 : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
441 typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
446 struct SetOperationTraitsTraits : public Traits {
447 typedef T OperationTraits;
450 /// \brief \ref named-templ-param "Named parameter" for setting
451 ///\c OperationTraits type
453 ///\ref named-templ-param "Named parameter" for setting
454 ///\c OperationTraits type.
455 /// For more information, see \ref DijkstraDefaultOperationTraits.
457 struct SetOperationTraits
458 : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
459 typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
474 ///\param g The digraph the algorithm runs on.
475 ///\param length The length map used by the algorithm.
476 Dijkstra(const Digraph& g, const LengthMap& length) :
477 G(&g), _length(&length),
478 _pred(NULL), local_pred(false),
479 _dist(NULL), local_dist(false),
480 _processed(NULL), local_processed(false),
481 _heap_cross_ref(NULL), local_heap_cross_ref(false),
482 _heap(NULL), local_heap(false)
488 if(local_pred) delete _pred;
489 if(local_dist) delete _dist;
490 if(local_processed) delete _processed;
491 if(local_heap_cross_ref) delete _heap_cross_ref;
492 if(local_heap) delete _heap;
495 ///Sets the length map.
497 ///Sets the length map.
498 ///\return <tt> (*this) </tt>
499 Dijkstra &lengthMap(const LengthMap &m)
505 ///Sets the map that stores the predecessor arcs.
507 ///Sets the map that stores the predecessor arcs.
508 ///If you don't use this function before calling \ref run(Node) "run()"
509 ///or \ref init(), an instance will be allocated automatically.
510 ///The destructor deallocates this automatically allocated map,
512 ///\return <tt> (*this) </tt>
513 Dijkstra &predMap(PredMap &m)
523 ///Sets the map that indicates which nodes are processed.
525 ///Sets the map that indicates which nodes are processed.
526 ///If you don't use this function before calling \ref run(Node) "run()"
527 ///or \ref init(), an instance will be allocated automatically.
528 ///The destructor deallocates this automatically allocated map,
530 ///\return <tt> (*this) </tt>
531 Dijkstra &processedMap(ProcessedMap &m)
533 if(local_processed) {
535 local_processed=false;
541 ///Sets the map that stores the distances of the nodes.
543 ///Sets the map that stores the distances of the nodes calculated by the
545 ///If you don't use this function before calling \ref run(Node) "run()"
546 ///or \ref init(), an instance will be allocated automatically.
547 ///The destructor deallocates this automatically allocated map,
549 ///\return <tt> (*this) </tt>
550 Dijkstra &distMap(DistMap &m)
560 ///Sets the heap and the cross reference used by algorithm.
562 ///Sets the heap and the cross reference used by algorithm.
563 ///If you don't use this function before calling \ref run(Node) "run()"
564 ///or \ref init(), heap and cross reference instances will be
565 ///allocated automatically.
566 ///The destructor deallocates these automatically allocated objects,
568 ///\return <tt> (*this) </tt>
569 Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
571 if(local_heap_cross_ref) {
572 delete _heap_cross_ref;
573 local_heap_cross_ref=false;
575 _heap_cross_ref = &cr;
586 void finalizeNodeData(Node v,Value dst)
588 _processed->set(v,true);
594 ///\name Execution Control
595 ///The simplest way to execute the %Dijkstra algorithm is to use
596 ///one of the member functions called \ref run(Node) "run()".\n
597 ///If you need better control on the execution, you have to call
598 ///\ref init() first, then you can add several source nodes with
599 ///\ref addSource(). Finally the actual path computation can be
600 ///performed with one of the \ref start() functions.
604 ///\brief Initializes the internal data structures.
606 ///Initializes the internal data structures.
611 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
612 _pred->set(u,INVALID);
613 _processed->set(u,false);
614 _heap_cross_ref->set(u,Heap::PRE_HEAP);
618 ///Adds a new source node.
620 ///Adds a new source node to the priority heap.
621 ///The optional second parameter is the initial distance of the node.
623 ///The function checks if the node has already been added to the heap and
624 ///it is pushed to the heap only if either it was not in the heap
625 ///or the shortest path found till then is shorter than \c dst.
626 void addSource(Node s,Value dst=OperationTraits::zero())
628 if(_heap->state(s) != Heap::IN_HEAP) {
630 } else if(OperationTraits::less((*_heap)[s], dst)) {
632 _pred->set(s,INVALID);
636 ///Processes the next node in the priority heap
638 ///Processes the next node in the priority heap.
640 ///\return The processed node.
642 ///\warning The priority heap must not be empty.
643 Node processNextNode()
646 Value oldvalue=_heap->prio();
648 finalizeNodeData(v,oldvalue);
650 for(OutArcIt e(*G,v); e!=INVALID; ++e) {
652 switch(_heap->state(w)) {
654 _heap->push(w,OperationTraits::plus(oldvalue, (*_length)[e]));
659 Value newvalue = OperationTraits::plus(oldvalue, (*_length)[e]);
660 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
661 _heap->decrease(w, newvalue);
666 case Heap::POST_HEAP:
673 ///The next node to be processed.
675 ///Returns the next node to be processed or \c INVALID if the
676 ///priority heap is empty.
677 Node nextNode() const
679 return !_heap->empty()?_heap->top():INVALID;
682 ///Returns \c false if there are nodes to be processed.
684 ///Returns \c false if there are nodes to be processed
685 ///in the priority heap.
686 bool emptyQueue() const { return _heap->empty(); }
688 ///Returns the number of the nodes to be processed.
690 ///Returns the number of the nodes to be processed
691 ///in the priority heap.
692 int queueSize() const { return _heap->size(); }
694 ///Executes the algorithm.
696 ///Executes the algorithm.
698 ///This method runs the %Dijkstra algorithm from the root node(s)
699 ///in order to compute the shortest path to each node.
701 ///The algorithm computes
702 ///- the shortest path tree (forest),
703 ///- the distance of each node from the root(s).
705 ///\pre init() must be called and at least one root node should be
706 ///added with addSource() before using this function.
708 ///\note <tt>d.start()</tt> is just a shortcut of the following code.
710 /// while ( !d.emptyQueue() ) {
711 /// d.processNextNode();
716 while ( !emptyQueue() ) processNextNode();
719 ///Executes the algorithm until the given target node is processed.
721 ///Executes the algorithm until the given target node is processed.
723 ///This method runs the %Dijkstra algorithm from the root node(s)
724 ///in order to compute the shortest path to \c t.
726 ///The algorithm computes
727 ///- the shortest path to \c t,
728 ///- the distance of \c t from the root(s).
730 ///\pre init() must be called and at least one root node should be
731 ///added with addSource() before using this function.
734 while ( !_heap->empty() && _heap->top()!=t ) processNextNode();
735 if ( !_heap->empty() ) {
736 finalizeNodeData(_heap->top(),_heap->prio());
741 ///Executes the algorithm until a condition is met.
743 ///Executes the algorithm until a condition is met.
745 ///This method runs the %Dijkstra algorithm from the root node(s) in
746 ///order to compute the shortest path to a node \c v with
747 /// <tt>nm[v]</tt> true, if such a node can be found.
749 ///\param nm A \c bool (or convertible) node map. The algorithm
750 ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
752 ///\return The reached node \c v with <tt>nm[v]</tt> true or
753 ///\c INVALID if no such node was found.
755 ///\pre init() must be called and at least one root node should be
756 ///added with addSource() before using this function.
757 template<class NodeBoolMap>
758 Node start(const NodeBoolMap &nm)
760 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
761 if ( _heap->empty() ) return INVALID;
762 finalizeNodeData(_heap->top(),_heap->prio());
766 ///Runs the algorithm from the given source node.
768 ///This method runs the %Dijkstra algorithm from node \c s
769 ///in order to compute the shortest path to each node.
771 ///The algorithm computes
772 ///- the shortest path tree,
773 ///- the distance of each node from the root.
775 ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
787 ///Finds the shortest path between \c s and \c t.
789 ///This method runs the %Dijkstra algorithm from node \c s
790 ///in order to compute the shortest path to node \c t
791 ///(it stops searching when \c t is processed).
793 ///\return \c true if \c t is reachable form \c s.
795 ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
796 ///shortcut of the following code.
802 bool run(Node s,Node t) {
806 return (*_heap_cross_ref)[t] == Heap::POST_HEAP;
811 ///\name Query Functions
812 ///The results of the %Dijkstra algorithm can be obtained using these
814 ///Either \ref run(Node) "run()" or \ref init() should be called
815 ///before using them.
819 ///The shortest path to the given node.
821 ///Returns the shortest path to the given node from the root(s).
823 ///\warning \c t should be reached from the root(s).
825 ///\pre Either \ref run(Node) "run()" or \ref init()
826 ///must be called before using this function.
827 Path path(Node t) const { return Path(*G, *_pred, t); }
829 ///The distance of the given node from the root(s).
831 ///Returns the distance of the given node from the root(s).
833 ///\warning If node \c v is not reached from the root(s), then
834 ///the return value of this function is undefined.
836 ///\pre Either \ref run(Node) "run()" or \ref init()
837 ///must be called before using this function.
838 Value dist(Node v) const { return (*_dist)[v]; }
840 ///\brief Returns the 'previous arc' of the shortest path tree for
843 ///This function returns the 'previous arc' of the shortest path
844 ///tree for the node \c v, i.e. it returns the last arc of a
845 ///shortest path from a root to \c v. It is \c INVALID if \c v
846 ///is not reached from the root(s) or if \c v is a root.
848 ///The shortest path tree used here is equal to the shortest path
849 ///tree used in \ref predNode() and \ref predMap().
851 ///\pre Either \ref run(Node) "run()" or \ref init()
852 ///must be called before using this function.
853 Arc predArc(Node v) const { return (*_pred)[v]; }
855 ///\brief Returns the 'previous node' of the shortest path tree for
858 ///This function returns the 'previous node' of the shortest path
859 ///tree for the node \c v, i.e. it returns the last but one node
860 ///of a shortest path from a root to \c v. It is \c INVALID
861 ///if \c v is not reached from the root(s) or if \c v is a root.
863 ///The shortest path tree used here is equal to the shortest path
864 ///tree used in \ref predArc() and \ref predMap().
866 ///\pre Either \ref run(Node) "run()" or \ref init()
867 ///must be called before using this function.
868 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
869 G->source((*_pred)[v]); }
871 ///\brief Returns a const reference to the node map that stores the
872 ///distances of the nodes.
874 ///Returns a const reference to the node map that stores the distances
875 ///of the nodes calculated by the algorithm.
877 ///\pre Either \ref run(Node) "run()" or \ref init()
878 ///must be called before using this function.
879 const DistMap &distMap() const { return *_dist;}
881 ///\brief Returns a const reference to the node map that stores the
884 ///Returns a const reference to the node map that stores the predecessor
885 ///arcs, which form the shortest path tree (forest).
887 ///\pre Either \ref run(Node) "run()" or \ref init()
888 ///must be called before using this function.
889 const PredMap &predMap() const { return *_pred;}
891 ///Checks if the given node is reached from the root(s).
893 ///Returns \c true if \c v is reached from the root(s).
895 ///\pre Either \ref run(Node) "run()" or \ref init()
896 ///must be called before using this function.
897 bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
900 ///Checks if a node is processed.
902 ///Returns \c true if \c v is processed, i.e. the shortest
903 ///path to \c v has already found.
905 ///\pre Either \ref run(Node) "run()" or \ref init()
906 ///must be called before using this function.
907 bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
910 ///The current distance of the given node from the root(s).
912 ///Returns the current distance of the given node from the root(s).
913 ///It may be decreased in the following processes.
915 ///\pre Either \ref run(Node) "run()" or \ref init()
916 ///must be called before using this function and
917 ///node \c v must be reached but not necessarily processed.
918 Value currentDist(Node v) const {
919 return processed(v) ? (*_dist)[v] : (*_heap)[v];
926 ///Default traits class of dijkstra() function.
928 ///Default traits class of dijkstra() function.
929 ///\tparam GR The type of the digraph.
930 ///\tparam LEN The type of the length map.
931 template<class GR, class LEN>
932 struct DijkstraWizardDefaultTraits
934 ///The type of the digraph the algorithm runs on.
936 ///The type of the map that stores the arc lengths.
938 ///The type of the map that stores the arc lengths.
939 ///It must conform to the \ref concepts::ReadMap "ReadMap" concept.
940 typedef LEN LengthMap;
941 ///The type of the arc lengths.
942 typedef typename LEN::Value Value;
944 /// Operation traits for Dijkstra algorithm.
946 /// This class defines the operations that are used in the algorithm.
947 /// \see DijkstraDefaultOperationTraits
948 typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
950 /// The cross reference type used by the heap.
952 /// The cross reference type used by the heap.
953 /// Usually it is \c Digraph::NodeMap<int>.
954 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
955 ///Instantiates a \ref HeapCrossRef.
957 ///This function instantiates a \ref HeapCrossRef.
958 /// \param g is the digraph, to which we would like to define the
960 static HeapCrossRef *createHeapCrossRef(const Digraph &g)
962 return new HeapCrossRef(g);
965 ///The heap type used by the Dijkstra algorithm.
967 ///The heap type used by the Dijkstra algorithm.
971 typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
972 std::less<Value> > Heap;
974 ///Instantiates a \ref Heap.
976 ///This function instantiates a \ref Heap.
977 /// \param r is the HeapCrossRef which is used.
978 static Heap *createHeap(HeapCrossRef& r)
983 ///\brief The type of the map that stores the predecessor
984 ///arcs of the shortest paths.
986 ///The type of the map that stores the predecessor
987 ///arcs of the shortest paths.
988 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
989 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
990 ///Instantiates a PredMap.
992 ///This function instantiates a PredMap.
993 ///\param g is the digraph, to which we would like to define the
995 static PredMap *createPredMap(const Digraph &g)
997 return new PredMap(g);
1000 ///The type of the map that indicates which nodes are processed.
1002 ///The type of the map that indicates which nodes are processed.
1003 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1004 ///By default, it is a NullMap.
1005 typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
1006 ///Instantiates a ProcessedMap.
1008 ///This function instantiates a ProcessedMap.
1009 ///\param g is the digraph, to which
1010 ///we would like to define the ProcessedMap.
1012 static ProcessedMap *createProcessedMap(const Digraph &g)
1014 static ProcessedMap *createProcessedMap(const Digraph &)
1017 return new ProcessedMap();
1020 ///The type of the map that stores the distances of the nodes.
1022 ///The type of the map that stores the distances of the nodes.
1023 ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1024 typedef typename Digraph::template NodeMap<typename LEN::Value> DistMap;
1025 ///Instantiates a DistMap.
1027 ///This function instantiates a DistMap.
1028 ///\param g is the digraph, to which we would like to define
1030 static DistMap *createDistMap(const Digraph &g)
1032 return new DistMap(g);
1035 ///The type of the shortest paths.
1037 ///The type of the shortest paths.
1038 ///It must conform to the \ref concepts::Path "Path" concept.
1039 typedef lemon::Path<Digraph> Path;
1042 /// Default traits class used by DijkstraWizard
1044 /// Default traits class used by DijkstraWizard.
1045 /// \tparam GR The type of the digraph.
1046 /// \tparam LEN The type of the length map.
1047 template<typename GR, typename LEN>
1048 class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LEN>
1050 typedef DijkstraWizardDefaultTraits<GR,LEN> Base;
1052 //The type of the nodes in the digraph.
1053 typedef typename Base::Digraph::Node Node;
1055 //Pointer to the digraph the algorithm runs on.
1057 //Pointer to the length map.
1059 //Pointer to the map of processed nodes.
1061 //Pointer to the map of predecessors arcs.
1063 //Pointer to the map of distances.
1065 //Pointer to the shortest path to the target node.
1067 //Pointer to the distance of the target node.
1073 /// This constructor does not require parameters, therefore it initiates
1074 /// all of the attributes to \c 0.
1075 DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1076 _dist(0), _path(0), _di(0) {}
1080 /// This constructor requires two parameters,
1081 /// others are initiated to \c 0.
1082 /// \param g The digraph the algorithm runs on.
1083 /// \param l The length map.
1084 DijkstraWizardBase(const GR &g,const LEN &l) :
1085 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1086 _length(reinterpret_cast<void*>(const_cast<LEN*>(&l))),
1087 _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
1091 /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1093 /// This auxiliary class is created to implement the
1094 /// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm.
1095 /// It does not have own \ref run(Node) "run()" method, it uses the
1096 /// functions and features of the plain \ref Dijkstra.
1098 /// This class should only be used through the \ref dijkstra() function,
1099 /// which makes it easier to use the algorithm.
1101 /// \tparam TR The traits class that defines various types used by the
1104 class DijkstraWizard : public TR
1108 typedef typename TR::Digraph Digraph;
1110 typedef typename Digraph::Node Node;
1111 typedef typename Digraph::NodeIt NodeIt;
1112 typedef typename Digraph::Arc Arc;
1113 typedef typename Digraph::OutArcIt OutArcIt;
1115 typedef typename TR::LengthMap LengthMap;
1116 typedef typename LengthMap::Value Value;
1117 typedef typename TR::PredMap PredMap;
1118 typedef typename TR::DistMap DistMap;
1119 typedef typename TR::ProcessedMap ProcessedMap;
1120 typedef typename TR::Path Path;
1121 typedef typename TR::Heap Heap;
1126 DijkstraWizard() : TR() {}
1128 /// Constructor that requires parameters.
1130 /// Constructor that requires parameters.
1131 /// These parameters will be the default values for the traits class.
1132 /// \param g The digraph the algorithm runs on.
1133 /// \param l The length map.
1134 DijkstraWizard(const Digraph &g, const LengthMap &l) :
1138 DijkstraWizard(const TR &b) : TR(b) {}
1140 ~DijkstraWizard() {}
1142 ///Runs Dijkstra algorithm from the given source node.
1144 ///This method runs %Dijkstra algorithm from the given source node
1145 ///in order to compute the shortest path to each node.
1148 Dijkstra<Digraph,LengthMap,TR>
1149 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1150 *reinterpret_cast<const LengthMap*>(Base::_length));
1152 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1154 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1155 if (Base::_processed)
1156 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1160 ///Finds the shortest path between \c s and \c t.
1162 ///This method runs the %Dijkstra algorithm from node \c s
1163 ///in order to compute the shortest path to node \c t
1164 ///(it stops searching when \c t is processed).
1166 ///\return \c true if \c t is reachable form \c s.
1167 bool run(Node s, Node t)
1169 Dijkstra<Digraph,LengthMap,TR>
1170 dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1171 *reinterpret_cast<const LengthMap*>(Base::_length));
1173 dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1175 dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1176 if (Base::_processed)
1177 dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1180 *reinterpret_cast<Path*>(Base::_path) = dijk.path(t);
1182 *reinterpret_cast<Value*>(Base::_di) = dijk.dist(t);
1183 return dijk.reached(t);
1187 struct SetPredMapBase : public Base {
1189 static PredMap *createPredMap(const Digraph &) { return 0; };
1190 SetPredMapBase(const TR &b) : TR(b) {}
1193 ///\brief \ref named-templ-param "Named parameter" for setting
1194 ///the predecessor map.
1196 ///\ref named-templ-param "Named parameter" function for setting
1197 ///the map that stores the predecessor arcs of the nodes.
1199 DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1201 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1202 return DijkstraWizard<SetPredMapBase<T> >(*this);
1206 struct SetDistMapBase : public Base {
1208 static DistMap *createDistMap(const Digraph &) { return 0; };
1209 SetDistMapBase(const TR &b) : TR(b) {}
1212 ///\brief \ref named-templ-param "Named parameter" for setting
1213 ///the distance map.
1215 ///\ref named-templ-param "Named parameter" function for setting
1216 ///the map that stores the distances of the nodes calculated
1217 ///by the algorithm.
1219 DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1221 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1222 return DijkstraWizard<SetDistMapBase<T> >(*this);
1226 struct SetProcessedMapBase : public Base {
1227 typedef T ProcessedMap;
1228 static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1229 SetProcessedMapBase(const TR &b) : TR(b) {}
1232 ///\brief \ref named-func-param "Named parameter" for setting
1233 ///the processed map.
1235 ///\ref named-templ-param "Named parameter" function for setting
1236 ///the map that indicates which nodes are processed.
1238 DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1240 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1241 return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1245 struct SetPathBase : public Base {
1247 SetPathBase(const TR &b) : TR(b) {}
1250 ///\brief \ref named-func-param "Named parameter"
1251 ///for getting the shortest path to the target node.
1253 ///\ref named-func-param "Named parameter"
1254 ///for getting the shortest path to the target node.
1256 DijkstraWizard<SetPathBase<T> > path(const T &t)
1258 Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1259 return DijkstraWizard<SetPathBase<T> >(*this);
1262 ///\brief \ref named-func-param "Named parameter"
1263 ///for getting the distance of the target node.
1265 ///\ref named-func-param "Named parameter"
1266 ///for getting the distance of the target node.
1267 DijkstraWizard dist(const Value &d)
1269 Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1275 ///Function-type interface for Dijkstra algorithm.
1277 /// \ingroup shortest_path
1278 ///Function-type interface for Dijkstra algorithm.
1280 ///This function also has several \ref named-func-param "named parameters",
1281 ///they are declared as the members of class \ref DijkstraWizard.
1282 ///The following examples show how to use these parameters.
1284 /// // Compute shortest path from node s to each node
1285 /// dijkstra(g,length).predMap(preds).distMap(dists).run(s);
1287 /// // Compute shortest path from s to t
1288 /// bool reached = dijkstra(g,length).path(p).dist(d).run(s,t);
1290 ///\warning Don't forget to put the \ref DijkstraWizard::run(Node) "run()"
1291 ///to the end of the parameter list.
1292 ///\sa DijkstraWizard
1294 template<typename GR, typename LEN>
1295 DijkstraWizard<DijkstraWizardBase<GR,LEN> >
1296 dijkstra(const GR &digraph, const LEN &length)
1298 return DijkstraWizard<DijkstraWizardBase<GR,LEN> >(digraph,length);
1301 } //END OF NAMESPACE LEMON