1 | /* -*- C++ -*- |
---|
2 | * |
---|
3 | * This file is a part of LEMON, a generic C++ optimization library |
---|
4 | * |
---|
5 | * Copyright (C) 2003-2006 |
---|
6 | * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
---|
7 | * (Egervary Research Group on Combinatorial Optimization, EGRES). |
---|
8 | * |
---|
9 | * Permission to use, modify and distribute this software is granted |
---|
10 | * provided that this copyright notice appears in all copies. For |
---|
11 | * precise terms see the accompanying LICENSE file. |
---|
12 | * |
---|
13 | * This software is provided "AS IS" with no warranty of any kind, |
---|
14 | * express or implied, and with no claim as to its suitability for any |
---|
15 | * purpose. |
---|
16 | * |
---|
17 | */ |
---|
18 | |
---|
19 | #ifndef LEMON_BELMANN_FORD_H |
---|
20 | #define LEMON_BELMANN_FORD_H |
---|
21 | |
---|
22 | /// \ingroup flowalgs |
---|
23 | /// \file |
---|
24 | /// \brief BellmanFord algorithm. |
---|
25 | /// |
---|
26 | |
---|
27 | #include <lemon/list_graph.h> |
---|
28 | #include <lemon/bits/invalid.h> |
---|
29 | #include <lemon/error.h> |
---|
30 | #include <lemon/maps.h> |
---|
31 | |
---|
32 | #include <limits> |
---|
33 | |
---|
34 | namespace lemon { |
---|
35 | |
---|
36 | /// \brief Default OperationTraits for the BellmanFord algorithm class. |
---|
37 | /// |
---|
38 | /// It defines all computational operations and constants which are |
---|
39 | /// used in the bellman ford algorithm. The default implementation |
---|
40 | /// is based on the numeric_limits class. If the numeric type does not |
---|
41 | /// have infinity value then the maximum value is used as extremal |
---|
42 | /// infinity value. |
---|
43 | template < |
---|
44 | typename Value, |
---|
45 | bool has_infinity = std::numeric_limits<Value>::has_infinity> |
---|
46 | struct BellmanFordDefaultOperationTraits { |
---|
47 | /// \brief Gives back the zero value of the type. |
---|
48 | static Value zero() { |
---|
49 | return static_cast<Value>(0); |
---|
50 | } |
---|
51 | /// \brief Gives back the positive infinity value of the type. |
---|
52 | static Value infinity() { |
---|
53 | return std::numeric_limits<Value>::infinity(); |
---|
54 | } |
---|
55 | /// \brief Gives back the sum of the given two elements. |
---|
56 | static Value plus(const Value& left, const Value& right) { |
---|
57 | return left + right; |
---|
58 | } |
---|
59 | /// \brief Gives back true only if the first value less than the second. |
---|
60 | static bool less(const Value& left, const Value& right) { |
---|
61 | return left < right; |
---|
62 | } |
---|
63 | }; |
---|
64 | |
---|
65 | template <typename Value> |
---|
66 | struct BellmanFordDefaultOperationTraits<Value, false> { |
---|
67 | static Value zero() { |
---|
68 | return static_cast<Value>(0); |
---|
69 | } |
---|
70 | static Value infinity() { |
---|
71 | return std::numeric_limits<Value>::max(); |
---|
72 | } |
---|
73 | static Value plus(const Value& left, const Value& right) { |
---|
74 | if (left == infinity() || right == infinity()) return infinity(); |
---|
75 | return left + right; |
---|
76 | } |
---|
77 | static bool less(const Value& left, const Value& right) { |
---|
78 | return left < right; |
---|
79 | } |
---|
80 | }; |
---|
81 | |
---|
82 | /// \brief Default traits class of BellmanFord class. |
---|
83 | /// |
---|
84 | /// Default traits class of BellmanFord class. |
---|
85 | /// \param _Graph Graph type. |
---|
86 | /// \param _LegthMap Type of length map. |
---|
87 | template<class _Graph, class _LengthMap> |
---|
88 | struct BellmanFordDefaultTraits { |
---|
89 | /// The graph type the algorithm runs on. |
---|
90 | typedef _Graph Graph; |
---|
91 | |
---|
92 | /// \brief The type of the map that stores the edge lengths. |
---|
93 | /// |
---|
94 | /// The type of the map that stores the edge lengths. |
---|
95 | /// It must meet the \ref concept::ReadMap "ReadMap" concept. |
---|
96 | typedef _LengthMap LengthMap; |
---|
97 | |
---|
98 | // The type of the length of the edges. |
---|
99 | typedef typename _LengthMap::Value Value; |
---|
100 | |
---|
101 | /// \brief Operation traits for bellman-ford algorithm. |
---|
102 | /// |
---|
103 | /// It defines the infinity type on the given Value type |
---|
104 | /// and the used operation. |
---|
105 | /// \see BellmanFordDefaultOperationTraits |
---|
106 | typedef BellmanFordDefaultOperationTraits<Value> OperationTraits; |
---|
107 | |
---|
108 | /// \brief The type of the map that stores the last edges of the |
---|
109 | /// shortest paths. |
---|
110 | /// |
---|
111 | /// The type of the map that stores the last |
---|
112 | /// edges of the shortest paths. |
---|
113 | /// It must meet the \ref concept::WriteMap "WriteMap" concept. |
---|
114 | /// |
---|
115 | typedef typename Graph::template NodeMap<typename _Graph::Edge> PredMap; |
---|
116 | |
---|
117 | /// \brief Instantiates a PredMap. |
---|
118 | /// |
---|
119 | /// This function instantiates a \ref PredMap. |
---|
120 | /// \param graph is the graph, to which we would like to define the PredMap. |
---|
121 | static PredMap *createPredMap(const _Graph& graph) { |
---|
122 | return new PredMap(graph); |
---|
123 | } |
---|
124 | |
---|
125 | /// \brief 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 _LengthMap::Value> |
---|
131 | DistMap; |
---|
132 | |
---|
133 | /// \brief Instantiates a DistMap. |
---|
134 | /// |
---|
135 | /// This function instantiates a \ref DistMap. |
---|
136 | /// \param graph is the graph, to which we would like to define the |
---|
137 | /// \ref DistMap |
---|
138 | static DistMap *createDistMap(const _Graph& graph) { |
---|
139 | return new DistMap(graph); |
---|
140 | } |
---|
141 | |
---|
142 | }; |
---|
143 | |
---|
144 | /// \brief %BellmanFord algorithm class. |
---|
145 | /// |
---|
146 | /// \ingroup flowalgs |
---|
147 | /// This class provides an efficient implementation of \c Bellman-Ford |
---|
148 | /// algorithm. The edge lengths are passed to the algorithm using a |
---|
149 | /// \ref concept::ReadMap "ReadMap", so it is easy to change it to any |
---|
150 | /// kind of length. |
---|
151 | /// |
---|
152 | /// The Bellman-Ford algorithm solves the shortest path from one node |
---|
153 | /// problem when the edges can have negative length but the graph should |
---|
154 | /// not contain cycles with negative sum of length. If we can assume |
---|
155 | /// that all edge is non-negative in the graph then the dijkstra algorithm |
---|
156 | /// should be used rather. |
---|
157 | /// |
---|
158 | /// The maximal time complexity of the algorithm is \f$ O(ne) \f$. |
---|
159 | /// |
---|
160 | /// The type of the length is determined by the |
---|
161 | /// \ref concept::ReadMap::Value "Value" of the length map. |
---|
162 | /// |
---|
163 | /// \param _Graph The graph type the algorithm runs on. The default value |
---|
164 | /// is \ref ListGraph. The value of _Graph is not used directly by |
---|
165 | /// BellmanFord, it is only passed to \ref BellmanFordDefaultTraits. |
---|
166 | /// \param _LengthMap This read-only EdgeMap determines the lengths of the |
---|
167 | /// edges. The default map type is \ref concept::StaticGraph::EdgeMap |
---|
168 | /// "Graph::EdgeMap<int>". The value of _LengthMap is not used directly |
---|
169 | /// by BellmanFord, it is only passed to \ref BellmanFordDefaultTraits. |
---|
170 | /// \param _Traits Traits class to set various data types used by the |
---|
171 | /// algorithm. The default traits class is \ref BellmanFordDefaultTraits |
---|
172 | /// "BellmanFordDefaultTraits<_Graph,_LengthMap>". See \ref |
---|
173 | /// BellmanFordDefaultTraits for the documentation of a BellmanFord traits |
---|
174 | /// class. |
---|
175 | /// |
---|
176 | /// \author Balazs Dezso |
---|
177 | |
---|
178 | #ifdef DOXYGEN |
---|
179 | template <typename _Graph, typename _LengthMap, typename _Traits> |
---|
180 | #else |
---|
181 | template <typename _Graph=ListGraph, |
---|
182 | typename _LengthMap=typename _Graph::template EdgeMap<int>, |
---|
183 | typename _Traits=BellmanFordDefaultTraits<_Graph,_LengthMap> > |
---|
184 | #endif |
---|
185 | class BellmanFord { |
---|
186 | public: |
---|
187 | |
---|
188 | /// \brief \ref Exception for uninitialized parameters. |
---|
189 | /// |
---|
190 | /// This error represents problems in the initialization |
---|
191 | /// of the parameters of the algorithms. |
---|
192 | |
---|
193 | class UninitializedParameter : public lemon::UninitializedParameter { |
---|
194 | public: |
---|
195 | virtual const char* exceptionName() const { |
---|
196 | return "lemon::BellmanFord::UninitializedParameter"; |
---|
197 | } |
---|
198 | }; |
---|
199 | |
---|
200 | typedef _Traits Traits; |
---|
201 | ///The type of the underlying graph. |
---|
202 | typedef typename _Traits::Graph Graph; |
---|
203 | |
---|
204 | typedef typename Graph::Node Node; |
---|
205 | typedef typename Graph::NodeIt NodeIt; |
---|
206 | typedef typename Graph::Edge Edge; |
---|
207 | typedef typename Graph::OutEdgeIt OutEdgeIt; |
---|
208 | |
---|
209 | /// \brief The type of the length of the edges. |
---|
210 | typedef typename _Traits::LengthMap::Value Value; |
---|
211 | /// \brief The type of the map that stores the edge lengths. |
---|
212 | typedef typename _Traits::LengthMap LengthMap; |
---|
213 | /// \brief The type of the map that stores the last |
---|
214 | /// edges of the shortest paths. |
---|
215 | typedef typename _Traits::PredMap PredMap; |
---|
216 | /// \brief The type of the map that stores the dists of the nodes. |
---|
217 | typedef typename _Traits::DistMap DistMap; |
---|
218 | /// \brief The operation traits. |
---|
219 | typedef typename _Traits::OperationTraits OperationTraits; |
---|
220 | private: |
---|
221 | /// Pointer to the underlying graph. |
---|
222 | const Graph *graph; |
---|
223 | /// Pointer to the length map |
---|
224 | const LengthMap *length; |
---|
225 | ///Pointer to the map of predecessors edges. |
---|
226 | PredMap *_pred; |
---|
227 | ///Indicates if \ref _pred is locally allocated (\c true) or not. |
---|
228 | bool local_pred; |
---|
229 | ///Pointer to the map of distances. |
---|
230 | DistMap *_dist; |
---|
231 | ///Indicates if \ref _dist is locally allocated (\c true) or not. |
---|
232 | bool local_dist; |
---|
233 | |
---|
234 | typedef typename Graph::template NodeMap<bool> MaskMap; |
---|
235 | MaskMap *_mask; |
---|
236 | |
---|
237 | std::vector<Node> _process; |
---|
238 | |
---|
239 | /// Creates the maps if necessary. |
---|
240 | void create_maps() { |
---|
241 | if(!_pred) { |
---|
242 | local_pred = true; |
---|
243 | _pred = Traits::createPredMap(*graph); |
---|
244 | } |
---|
245 | if(!_dist) { |
---|
246 | local_dist = true; |
---|
247 | _dist = Traits::createDistMap(*graph); |
---|
248 | } |
---|
249 | _mask = new MaskMap(*graph, false); |
---|
250 | } |
---|
251 | |
---|
252 | public : |
---|
253 | |
---|
254 | typedef BellmanFord Create; |
---|
255 | |
---|
256 | /// \name Named template parameters |
---|
257 | |
---|
258 | ///@{ |
---|
259 | |
---|
260 | template <class T> |
---|
261 | struct DefPredMapTraits : public Traits { |
---|
262 | typedef T PredMap; |
---|
263 | static PredMap *createPredMap(const Graph&) { |
---|
264 | throw UninitializedParameter(); |
---|
265 | } |
---|
266 | }; |
---|
267 | |
---|
268 | /// \brief \ref named-templ-param "Named parameter" for setting PredMap |
---|
269 | /// type |
---|
270 | /// \ref named-templ-param "Named parameter" for setting PredMap type |
---|
271 | /// |
---|
272 | template <class T> |
---|
273 | struct DefPredMap |
---|
274 | : public BellmanFord< Graph, LengthMap, DefPredMapTraits<T> > { |
---|
275 | typedef BellmanFord< Graph, LengthMap, DefPredMapTraits<T> > Create; |
---|
276 | }; |
---|
277 | |
---|
278 | template <class T> |
---|
279 | struct DefDistMapTraits : public Traits { |
---|
280 | typedef T DistMap; |
---|
281 | static DistMap *createDistMap(const Graph&) { |
---|
282 | throw UninitializedParameter(); |
---|
283 | } |
---|
284 | }; |
---|
285 | |
---|
286 | /// \brief \ref named-templ-param "Named parameter" for setting DistMap |
---|
287 | /// type |
---|
288 | /// |
---|
289 | /// \ref named-templ-param "Named parameter" for setting DistMap type |
---|
290 | /// |
---|
291 | template <class T> |
---|
292 | struct DefDistMap |
---|
293 | : public BellmanFord< Graph, LengthMap, DefDistMapTraits<T> > { |
---|
294 | typedef BellmanFord< Graph, LengthMap, DefDistMapTraits<T> > Create; |
---|
295 | }; |
---|
296 | |
---|
297 | template <class T> |
---|
298 | struct DefOperationTraitsTraits : public Traits { |
---|
299 | typedef T OperationTraits; |
---|
300 | }; |
---|
301 | |
---|
302 | /// \brief \ref named-templ-param "Named parameter" for setting |
---|
303 | /// OperationTraits type |
---|
304 | /// |
---|
305 | /// \ref named-templ-param "Named parameter" for setting OperationTraits |
---|
306 | /// type |
---|
307 | template <class T> |
---|
308 | struct DefOperationTraits |
---|
309 | : public BellmanFord< Graph, LengthMap, DefOperationTraitsTraits<T> > { |
---|
310 | typedef BellmanFord< Graph, LengthMap, DefOperationTraitsTraits<T> > |
---|
311 | Create; |
---|
312 | }; |
---|
313 | |
---|
314 | ///@} |
---|
315 | |
---|
316 | protected: |
---|
317 | |
---|
318 | BellmanFord() {} |
---|
319 | |
---|
320 | public: |
---|
321 | |
---|
322 | /// \brief Constructor. |
---|
323 | /// |
---|
324 | /// \param _graph the graph the algorithm will run on. |
---|
325 | /// \param _length the length map used by the algorithm. |
---|
326 | BellmanFord(const Graph& _graph, const LengthMap& _length) : |
---|
327 | graph(&_graph), length(&_length), |
---|
328 | _pred(0), local_pred(false), |
---|
329 | _dist(0), local_dist(false) {} |
---|
330 | |
---|
331 | ///Destructor. |
---|
332 | ~BellmanFord() { |
---|
333 | if(local_pred) delete _pred; |
---|
334 | if(local_dist) delete _dist; |
---|
335 | delete _mask; |
---|
336 | } |
---|
337 | |
---|
338 | /// \brief Sets the length map. |
---|
339 | /// |
---|
340 | /// Sets the length map. |
---|
341 | /// \return \c (*this) |
---|
342 | BellmanFord &lengthMap(const LengthMap &m) { |
---|
343 | length = &m; |
---|
344 | return *this; |
---|
345 | } |
---|
346 | |
---|
347 | /// \brief Sets the map storing the predecessor edges. |
---|
348 | /// |
---|
349 | /// Sets the map storing the predecessor edges. |
---|
350 | /// If you don't use this function before calling \ref run(), |
---|
351 | /// it will allocate one. The destuctor deallocates this |
---|
352 | /// automatically allocated map, of course. |
---|
353 | /// \return \c (*this) |
---|
354 | BellmanFord &predMap(PredMap &m) { |
---|
355 | if(local_pred) { |
---|
356 | delete _pred; |
---|
357 | local_pred=false; |
---|
358 | } |
---|
359 | _pred = &m; |
---|
360 | return *this; |
---|
361 | } |
---|
362 | |
---|
363 | /// \brief Sets the map storing the distances calculated by the algorithm. |
---|
364 | /// |
---|
365 | /// Sets the map storing the distances calculated by the algorithm. |
---|
366 | /// If you don't use this function before calling \ref run(), |
---|
367 | /// it will allocate one. The destuctor deallocates this |
---|
368 | /// automatically allocated map, of course. |
---|
369 | /// \return \c (*this) |
---|
370 | BellmanFord &distMap(DistMap &m) { |
---|
371 | if(local_dist) { |
---|
372 | delete _dist; |
---|
373 | local_dist=false; |
---|
374 | } |
---|
375 | _dist = &m; |
---|
376 | return *this; |
---|
377 | } |
---|
378 | |
---|
379 | /// \name Execution control |
---|
380 | /// The simplest way to execute the algorithm is to use |
---|
381 | /// one of the member functions called \c run(...). |
---|
382 | /// \n |
---|
383 | /// If you need more control on the execution, |
---|
384 | /// first you must call \ref init(), then you can add several source nodes |
---|
385 | /// with \ref addSource(). |
---|
386 | /// Finally \ref start() will perform the actual path |
---|
387 | /// computation. |
---|
388 | |
---|
389 | ///@{ |
---|
390 | |
---|
391 | /// \brief Initializes the internal data structures. |
---|
392 | /// |
---|
393 | /// Initializes the internal data structures. |
---|
394 | void init(const Value value = OperationTraits::infinity()) { |
---|
395 | create_maps(); |
---|
396 | for (NodeIt it(*graph); it != INVALID; ++it) { |
---|
397 | _pred->set(it, INVALID); |
---|
398 | _dist->set(it, value); |
---|
399 | } |
---|
400 | _process.clear(); |
---|
401 | if (OperationTraits::less(value, OperationTraits::infinity())) { |
---|
402 | for (NodeIt it(*graph); it != INVALID; ++it) { |
---|
403 | _process.push_back(it); |
---|
404 | _mask->set(it, true); |
---|
405 | } |
---|
406 | } |
---|
407 | } |
---|
408 | |
---|
409 | /// \brief Adds a new source node. |
---|
410 | /// |
---|
411 | /// The optional second parameter is the initial distance of the node. |
---|
412 | /// It just sets the distance of the node to the given value. |
---|
413 | void addSource(Node source, Value dst = OperationTraits::zero()) { |
---|
414 | _dist->set(source, dst); |
---|
415 | if (!(*_mask)[source]) { |
---|
416 | _process.push_back(source); |
---|
417 | _mask->set(source, true); |
---|
418 | } |
---|
419 | } |
---|
420 | |
---|
421 | /// \brief Executes one round from the bellman ford algorithm. |
---|
422 | /// |
---|
423 | /// If the algoritm calculated the distances in the previous round |
---|
424 | /// exactly for all at most \f$ k \f$ length path lengths then it will |
---|
425 | /// calculate the distances exactly for all at most \f$ k + 1 \f$ |
---|
426 | /// length path lengths. With \f$ k \f$ iteration this function |
---|
427 | /// calculates the at most \f$ k \f$ length path lengths. |
---|
428 | /// |
---|
429 | /// \warning The paths with limited edge number cannot be retrieved |
---|
430 | /// easily with \ref getPath() or \ref predEdge() functions. If you |
---|
431 | /// need the shortest path and not just the distance you should store |
---|
432 | /// after each iteration the \ref predEdgeMap() map and manually build |
---|
433 | /// the path. |
---|
434 | /// |
---|
435 | /// \return %True when the algorithm have not found more shorter |
---|
436 | /// paths. |
---|
437 | bool processNextRound() { |
---|
438 | for (int i = 0; i < (int)_process.size(); ++i) { |
---|
439 | _mask->set(_process[i], false); |
---|
440 | } |
---|
441 | std::vector<Node> nextProcess; |
---|
442 | std::vector<Value> values(_process.size()); |
---|
443 | for (int i = 0; i < (int)_process.size(); ++i) { |
---|
444 | values[i] = (*_dist)[_process[i]]; |
---|
445 | } |
---|
446 | for (int i = 0; i < (int)_process.size(); ++i) { |
---|
447 | for (OutEdgeIt it(*graph, _process[i]); it != INVALID; ++it) { |
---|
448 | Node target = graph->target(it); |
---|
449 | Value relaxed = OperationTraits::plus(values[i], (*length)[it]); |
---|
450 | if (OperationTraits::less(relaxed, (*_dist)[target])) { |
---|
451 | _pred->set(target, it); |
---|
452 | _dist->set(target, relaxed); |
---|
453 | if (!(*_mask)[target]) { |
---|
454 | _mask->set(target, true); |
---|
455 | nextProcess.push_back(target); |
---|
456 | } |
---|
457 | } |
---|
458 | } |
---|
459 | } |
---|
460 | _process.swap(nextProcess); |
---|
461 | return _process.empty(); |
---|
462 | } |
---|
463 | |
---|
464 | /// \brief Executes one weak round from the bellman ford algorithm. |
---|
465 | /// |
---|
466 | /// If the algorithm calculated the distances in the |
---|
467 | /// previous round at least for all at most k length paths then it will |
---|
468 | /// calculate the distances at least for all at most k + 1 length paths. |
---|
469 | /// This function does not make it possible to calculate strictly the |
---|
470 | /// at most k length minimal paths, this is why it is |
---|
471 | /// called just weak round. |
---|
472 | /// \return %True when the algorithm have not found more shorter paths. |
---|
473 | bool processNextWeakRound() { |
---|
474 | for (int i = 0; i < (int)_process.size(); ++i) { |
---|
475 | _mask->set(_process[i], false); |
---|
476 | } |
---|
477 | std::vector<Node> nextProcess; |
---|
478 | for (int i = 0; i < (int)_process.size(); ++i) { |
---|
479 | for (OutEdgeIt it(*graph, _process[i]); it != INVALID; ++it) { |
---|
480 | Node target = graph->target(it); |
---|
481 | Value relaxed = |
---|
482 | OperationTraits::plus((*_dist)[_process[i]], (*length)[it]); |
---|
483 | if (OperationTraits::less(relaxed, (*_dist)[target])) { |
---|
484 | _pred->set(target, it); |
---|
485 | _dist->set(target, relaxed); |
---|
486 | if (!(*_mask)[target]) { |
---|
487 | _mask->set(target, true); |
---|
488 | nextProcess.push_back(target); |
---|
489 | } |
---|
490 | } |
---|
491 | } |
---|
492 | } |
---|
493 | _process.swap(nextProcess); |
---|
494 | return _process.empty(); |
---|
495 | } |
---|
496 | |
---|
497 | /// \brief Executes the algorithm. |
---|
498 | /// |
---|
499 | /// \pre init() must be called and at least one node should be added |
---|
500 | /// with addSource() before using this function. |
---|
501 | /// |
---|
502 | /// This method runs the %BellmanFord algorithm from the root node(s) |
---|
503 | /// in order to compute the shortest path to each node. The algorithm |
---|
504 | /// computes |
---|
505 | /// - The shortest path tree. |
---|
506 | /// - The distance of each node from the root(s). |
---|
507 | void start() { |
---|
508 | int num = countNodes(*graph) - 1; |
---|
509 | for (int i = 0; i < num; ++i) { |
---|
510 | if (processNextWeakRound()) break; |
---|
511 | } |
---|
512 | } |
---|
513 | |
---|
514 | /// \brief Executes the algorithm and checks the negative cycles. |
---|
515 | /// |
---|
516 | /// \pre init() must be called and at least one node should be added |
---|
517 | /// with addSource() before using this function. If there is |
---|
518 | /// a negative cycles in the graph it gives back false. |
---|
519 | /// |
---|
520 | /// This method runs the %BellmanFord algorithm from the root node(s) |
---|
521 | /// in order to compute the shortest path to each node. The algorithm |
---|
522 | /// computes |
---|
523 | /// - The shortest path tree. |
---|
524 | /// - The distance of each node from the root(s). |
---|
525 | bool checkedStart() { |
---|
526 | int num = countNodes(*graph); |
---|
527 | for (int i = 0; i < num; ++i) { |
---|
528 | if (processNextWeakRound()) return true; |
---|
529 | } |
---|
530 | return false; |
---|
531 | } |
---|
532 | |
---|
533 | /// \brief Executes the algorithm with path length limit. |
---|
534 | /// |
---|
535 | /// \pre init() must be called and at least one node should be added |
---|
536 | /// with addSource() before using this function. |
---|
537 | /// |
---|
538 | /// This method runs the %BellmanFord algorithm from the root |
---|
539 | /// node(s) in order to compute the shortest path lengths with at |
---|
540 | /// most \c num edge. |
---|
541 | /// |
---|
542 | /// \warning The paths with limited edge number cannot be retrieved |
---|
543 | /// easily with \ref getPath() or \ref predEdge() functions. If you |
---|
544 | /// need the shortest path and not just the distance you should store |
---|
545 | /// after each iteration the \ref predEdgeMap() map and manually build |
---|
546 | /// the path. |
---|
547 | /// |
---|
548 | /// The algorithm computes |
---|
549 | /// - The predecessor edge from each node. |
---|
550 | /// - The limited distance of each node from the root(s). |
---|
551 | void limitedStart(int num) { |
---|
552 | for (int i = 0; i < num; ++i) { |
---|
553 | if (processNextRound()) break; |
---|
554 | } |
---|
555 | } |
---|
556 | |
---|
557 | /// \brief Runs %BellmanFord algorithm from node \c s. |
---|
558 | /// |
---|
559 | /// This method runs the %BellmanFord algorithm from a root node \c s |
---|
560 | /// in order to compute the shortest path to each node. The algorithm |
---|
561 | /// 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 | /// \brief Runs %BellmanFord algorithm with limited path length |
---|
578 | /// from node \c s. |
---|
579 | /// |
---|
580 | /// This method runs the %BellmanFord algorithm from a root node \c s |
---|
581 | /// in order to compute the shortest path with at most \c len edges |
---|
582 | /// to each node. The algorithm computes |
---|
583 | /// - The shortest path tree. |
---|
584 | /// - The distance of each node from the root. |
---|
585 | /// |
---|
586 | /// \note d.run(s, len) is just a shortcut of the following code. |
---|
587 | ///\code |
---|
588 | /// d.init(); |
---|
589 | /// d.addSource(s); |
---|
590 | /// d.limitedStart(len); |
---|
591 | ///\endcode |
---|
592 | void run(Node s, int len) { |
---|
593 | init(); |
---|
594 | addSource(s); |
---|
595 | limitedStart(len); |
---|
596 | } |
---|
597 | |
---|
598 | ///@} |
---|
599 | |
---|
600 | /// \name Query Functions |
---|
601 | /// The result of the %BellmanFord algorithm can be obtained using these |
---|
602 | /// functions.\n |
---|
603 | /// Before the use of these functions, |
---|
604 | /// either run() or start() must be called. |
---|
605 | |
---|
606 | ///@{ |
---|
607 | |
---|
608 | /// \brief Copies the shortest path to \c t into \c p |
---|
609 | /// |
---|
610 | /// This function copies the shortest path to \c t into \c p. |
---|
611 | /// If it \c t is a source itself or unreachable, then it does not |
---|
612 | /// alter \c p. |
---|
613 | /// |
---|
614 | /// \return Returns \c true if a path to \c t was actually copied to \c p, |
---|
615 | /// \c false otherwise. |
---|
616 | /// \sa DirPath |
---|
617 | template <typename Path> |
---|
618 | bool getPath(Path &p, Node t) { |
---|
619 | if(reached(t)) { |
---|
620 | p.clear(); |
---|
621 | typename Path::Builder b(p); |
---|
622 | for(b.setStartNode(t);predEdge(t)!=INVALID;t=predNode(t)) |
---|
623 | b.pushFront(predEdge(t)); |
---|
624 | b.commit(); |
---|
625 | return true; |
---|
626 | } |
---|
627 | return false; |
---|
628 | } |
---|
629 | |
---|
630 | /// \brief 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 | /// \brief 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 |
---|
641 | /// tree, i.e. it returns the last edge of a shortest path from the root |
---|
642 | /// to \c v. It is \ref INVALID if \c v is unreachable from the root or |
---|
643 | /// if \c v=s. The shortest path tree used here is equal to the shortest |
---|
644 | /// path tree used in \ref predNode(). |
---|
645 | /// \pre \ref run() must be called before using |
---|
646 | /// this function. |
---|
647 | Edge predEdge(Node v) const { return (*_pred)[v]; } |
---|
648 | |
---|
649 | /// \brief Returns the 'previous node' of the shortest path tree. |
---|
650 | /// |
---|
651 | /// For a node \c v it returns the 'previous node' of the shortest path |
---|
652 | /// tree, i.e. it returns the last but one node from a shortest path from |
---|
653 | /// the root to \c /v. It is INVALID if \c v is unreachable from the root |
---|
654 | /// or if \c v=s. The shortest path tree used here is equal to the |
---|
655 | /// shortest path tree used in \ref predEdge(). \pre \ref run() must be |
---|
656 | /// called before using this function. |
---|
657 | Node predNode(Node v) const { |
---|
658 | return (*_pred)[v] == INVALID ? INVALID : graph->source((*_pred)[v]); |
---|
659 | } |
---|
660 | |
---|
661 | /// \brief 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 | /// \brief 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 | /// \brief Checks if a node is reachable from the root. |
---|
675 | /// |
---|
676 | /// Returns \c true if \c v is reachable from the root. |
---|
677 | /// \pre \ref run() must be called before using this function. |
---|
678 | /// |
---|
679 | bool reached(Node v) { return (*_dist)[v] != OperationTraits::infinity(); } |
---|
680 | |
---|
681 | ///@} |
---|
682 | }; |
---|
683 | |
---|
684 | /// \brief Default traits class of BellmanFord function. |
---|
685 | /// |
---|
686 | /// Default traits class of BellmanFord function. |
---|
687 | /// \param _Graph Graph type. |
---|
688 | /// \param _LengthMap Type of length map. |
---|
689 | template <typename _Graph, typename _LengthMap> |
---|
690 | struct BellmanFordWizardDefaultTraits { |
---|
691 | /// \brief The graph type the algorithm runs on. |
---|
692 | typedef _Graph Graph; |
---|
693 | |
---|
694 | /// \brief The type of the map that stores the edge lengths. |
---|
695 | /// |
---|
696 | /// The type of the map that stores the edge lengths. |
---|
697 | /// It must meet the \ref concept::ReadMap "ReadMap" concept. |
---|
698 | typedef _LengthMap LengthMap; |
---|
699 | |
---|
700 | /// \brief The value type of the length map. |
---|
701 | typedef typename _LengthMap::Value Value; |
---|
702 | |
---|
703 | /// \brief Operation traits for bellman-ford algorithm. |
---|
704 | /// |
---|
705 | /// It defines the infinity type on the given Value type |
---|
706 | /// and the used operation. |
---|
707 | /// \see BellmanFordDefaultOperationTraits |
---|
708 | typedef BellmanFordDefaultOperationTraits<Value> OperationTraits; |
---|
709 | |
---|
710 | /// \brief The type of the map that stores the last |
---|
711 | /// edges of the shortest paths. |
---|
712 | /// |
---|
713 | /// The type of the map that stores the last |
---|
714 | /// edges of the shortest paths. |
---|
715 | /// It must meet the \ref concept::WriteMap "WriteMap" concept. |
---|
716 | typedef NullMap <typename _Graph::Node,typename _Graph::Edge> PredMap; |
---|
717 | |
---|
718 | /// \brief Instantiates a PredMap. |
---|
719 | /// |
---|
720 | /// This function instantiates a \ref PredMap. |
---|
721 | static PredMap *createPredMap(const _Graph &) { |
---|
722 | return new PredMap(); |
---|
723 | } |
---|
724 | /// \brief The type of the map that stores the dists of the nodes. |
---|
725 | /// |
---|
726 | /// The type of the map that stores the dists of the nodes. |
---|
727 | /// It must meet the \ref concept::WriteMap "WriteMap" concept. |
---|
728 | typedef NullMap<typename Graph::Node, Value> DistMap; |
---|
729 | /// \brief Instantiates a DistMap. |
---|
730 | /// |
---|
731 | /// This function instantiates a \ref DistMap. |
---|
732 | static DistMap *createDistMap(const _Graph &) { |
---|
733 | return new DistMap(); |
---|
734 | } |
---|
735 | }; |
---|
736 | |
---|
737 | /// \brief Default traits used by \ref BellmanFordWizard |
---|
738 | /// |
---|
739 | /// To make it easier to use BellmanFord algorithm |
---|
740 | /// we have created a wizard class. |
---|
741 | /// This \ref BellmanFordWizard class needs default traits, |
---|
742 | /// as well as the \ref BellmanFord class. |
---|
743 | /// The \ref BellmanFordWizardBase is a class to be the default traits of the |
---|
744 | /// \ref BellmanFordWizard class. |
---|
745 | /// \todo More named parameters are required... |
---|
746 | template<class _Graph,class _LengthMap> |
---|
747 | class BellmanFordWizardBase |
---|
748 | : public BellmanFordWizardDefaultTraits<_Graph,_LengthMap> { |
---|
749 | |
---|
750 | typedef BellmanFordWizardDefaultTraits<_Graph,_LengthMap> Base; |
---|
751 | protected: |
---|
752 | /// Type of the nodes in the graph. |
---|
753 | typedef typename Base::Graph::Node Node; |
---|
754 | |
---|
755 | /// Pointer to the underlying graph. |
---|
756 | void *_graph; |
---|
757 | /// Pointer to the length map |
---|
758 | void *_length; |
---|
759 | ///Pointer to the map of predecessors edges. |
---|
760 | void *_pred; |
---|
761 | ///Pointer to the map of distances. |
---|
762 | void *_dist; |
---|
763 | ///Pointer to the source node. |
---|
764 | Node _source; |
---|
765 | |
---|
766 | public: |
---|
767 | /// Constructor. |
---|
768 | |
---|
769 | /// This constructor does not require parameters, therefore it initiates |
---|
770 | /// all of the attributes to default values (0, INVALID). |
---|
771 | BellmanFordWizardBase() : _graph(0), _length(0), _pred(0), |
---|
772 | _dist(0), _source(INVALID) {} |
---|
773 | |
---|
774 | /// Constructor. |
---|
775 | |
---|
776 | /// This constructor requires some parameters, |
---|
777 | /// listed in the parameters list. |
---|
778 | /// Others are initiated to 0. |
---|
779 | /// \param graph is the initial value of \ref _graph |
---|
780 | /// \param length is the initial value of \ref _length |
---|
781 | /// \param source is the initial value of \ref _source |
---|
782 | BellmanFordWizardBase(const _Graph& graph, |
---|
783 | const _LengthMap& length, |
---|
784 | Node source = INVALID) : |
---|
785 | _graph((void *)&graph), _length((void *)&length), _pred(0), |
---|
786 | _dist(0), _source(source) {} |
---|
787 | |
---|
788 | }; |
---|
789 | |
---|
790 | /// A class to make the usage of BellmanFord algorithm easier |
---|
791 | |
---|
792 | /// This class is created to make it easier to use BellmanFord algorithm. |
---|
793 | /// It uses the functions and features of the plain \ref BellmanFord, |
---|
794 | /// but it is much simpler to use it. |
---|
795 | /// |
---|
796 | /// Simplicity means that the way to change the types defined |
---|
797 | /// in the traits class is based on functions that returns the new class |
---|
798 | /// and not on templatable built-in classes. |
---|
799 | /// When using the plain \ref BellmanFord |
---|
800 | /// the new class with the modified type comes from |
---|
801 | /// the original class by using the :: |
---|
802 | /// operator. In the case of \ref BellmanFordWizard only |
---|
803 | /// a function have to be called and it will |
---|
804 | /// return the needed class. |
---|
805 | /// |
---|
806 | /// It does not have own \ref run method. When its \ref run method is called |
---|
807 | /// it initiates a plain \ref BellmanFord class, and calls the \ref |
---|
808 | /// BellmanFord::run method of it. |
---|
809 | template<class _Traits> |
---|
810 | class BellmanFordWizard : public _Traits { |
---|
811 | typedef _Traits Base; |
---|
812 | |
---|
813 | ///The type of the underlying graph. |
---|
814 | typedef typename _Traits::Graph Graph; |
---|
815 | |
---|
816 | typedef typename Graph::Node Node; |
---|
817 | typedef typename Graph::NodeIt NodeIt; |
---|
818 | typedef typename Graph::Edge Edge; |
---|
819 | typedef typename Graph::OutEdgeIt EdgeIt; |
---|
820 | |
---|
821 | ///The type of the map that stores the edge lengths. |
---|
822 | typedef typename _Traits::LengthMap LengthMap; |
---|
823 | |
---|
824 | ///The type of the length of the edges. |
---|
825 | typedef typename LengthMap::Value Value; |
---|
826 | |
---|
827 | ///\brief The type of the map that stores the last |
---|
828 | ///edges of the shortest paths. |
---|
829 | typedef typename _Traits::PredMap PredMap; |
---|
830 | |
---|
831 | ///The type of the map that stores the dists of the nodes. |
---|
832 | typedef typename _Traits::DistMap DistMap; |
---|
833 | |
---|
834 | public: |
---|
835 | /// Constructor. |
---|
836 | BellmanFordWizard() : _Traits() {} |
---|
837 | |
---|
838 | /// \brief Constructor that requires parameters. |
---|
839 | /// |
---|
840 | /// Constructor that requires parameters. |
---|
841 | /// These parameters will be the default values for the traits class. |
---|
842 | BellmanFordWizard(const Graph& graph, const LengthMap& length, |
---|
843 | Node source = INVALID) |
---|
844 | : _Traits(graph, length, source) {} |
---|
845 | |
---|
846 | /// \brief Copy constructor |
---|
847 | BellmanFordWizard(const _Traits &b) : _Traits(b) {} |
---|
848 | |
---|
849 | ~BellmanFordWizard() {} |
---|
850 | |
---|
851 | /// \brief Runs BellmanFord algorithm from a given node. |
---|
852 | /// |
---|
853 | /// Runs BellmanFord algorithm from a given node. |
---|
854 | /// The node can be given by the \ref source function. |
---|
855 | void run() { |
---|
856 | if(Base::_source == INVALID) throw UninitializedParameter(); |
---|
857 | BellmanFord<Graph,LengthMap,_Traits> |
---|
858 | bf(*(Graph*)Base::_graph, *(LengthMap*)Base::_length); |
---|
859 | if (Base::_pred) bf.predMap(*(PredMap*)Base::_pred); |
---|
860 | if (Base::_dist) bf.distMap(*(DistMap*)Base::_dist); |
---|
861 | bf.run(Base::_source); |
---|
862 | } |
---|
863 | |
---|
864 | /// \brief Runs BellmanFord algorithm from the given node. |
---|
865 | /// |
---|
866 | /// Runs BellmanFord algorithm from the given node. |
---|
867 | /// \param source is the given source. |
---|
868 | void run(Node source) { |
---|
869 | Base::_source = source; |
---|
870 | run(); |
---|
871 | } |
---|
872 | |
---|
873 | template<class T> |
---|
874 | struct DefPredMapBase : public Base { |
---|
875 | typedef T PredMap; |
---|
876 | static PredMap *createPredMap(const Graph &) { return 0; }; |
---|
877 | DefPredMapBase(const _Traits &b) : _Traits(b) {} |
---|
878 | }; |
---|
879 | |
---|
880 | ///\brief \ref named-templ-param "Named parameter" |
---|
881 | ///function for setting PredMap type |
---|
882 | /// |
---|
883 | /// \ref named-templ-param "Named parameter" |
---|
884 | ///function for setting PredMap type |
---|
885 | /// |
---|
886 | template<class T> |
---|
887 | BellmanFordWizard<DefPredMapBase<T> > predMap(const T &t) |
---|
888 | { |
---|
889 | Base::_pred=(void *)&t; |
---|
890 | return BellmanFordWizard<DefPredMapBase<T> >(*this); |
---|
891 | } |
---|
892 | |
---|
893 | template<class T> |
---|
894 | struct DefDistMapBase : public Base { |
---|
895 | typedef T DistMap; |
---|
896 | static DistMap *createDistMap(const Graph &) { return 0; }; |
---|
897 | DefDistMapBase(const _Traits &b) : _Traits(b) {} |
---|
898 | }; |
---|
899 | |
---|
900 | ///\brief \ref named-templ-param "Named parameter" |
---|
901 | ///function for setting DistMap type |
---|
902 | /// |
---|
903 | /// \ref named-templ-param "Named parameter" |
---|
904 | ///function for setting DistMap type |
---|
905 | /// |
---|
906 | template<class T> |
---|
907 | BellmanFordWizard<DefDistMapBase<T> > distMap(const T &t) { |
---|
908 | Base::_dist=(void *)&t; |
---|
909 | return BellmanFordWizard<DefDistMapBase<T> >(*this); |
---|
910 | } |
---|
911 | |
---|
912 | template<class T> |
---|
913 | struct DefOperationTraitsBase : public Base { |
---|
914 | typedef T OperationTraits; |
---|
915 | DefOperationTraitsBase(const _Traits &b) : _Traits(b) {} |
---|
916 | }; |
---|
917 | |
---|
918 | ///\brief \ref named-templ-param "Named parameter" |
---|
919 | ///function for setting OperationTraits type |
---|
920 | /// |
---|
921 | /// \ref named-templ-param "Named parameter" |
---|
922 | ///function for setting OperationTraits type |
---|
923 | /// |
---|
924 | template<class T> |
---|
925 | BellmanFordWizard<DefOperationTraitsBase<T> > distMap() { |
---|
926 | return BellmanFordWizard<DefDistMapBase<T> >(*this); |
---|
927 | } |
---|
928 | |
---|
929 | /// \brief Sets the source node, from which the BellmanFord algorithm runs. |
---|
930 | /// |
---|
931 | /// Sets the source node, from which the BellmanFord algorithm runs. |
---|
932 | /// \param source is the source node. |
---|
933 | BellmanFordWizard<_Traits>& source(Node source) { |
---|
934 | Base::_source = source; |
---|
935 | return *this; |
---|
936 | } |
---|
937 | |
---|
938 | }; |
---|
939 | |
---|
940 | /// \brief Function type interface for BellmanFord algorithm. |
---|
941 | /// |
---|
942 | /// \ingroup flowalgs |
---|
943 | /// Function type interface for BellmanFord algorithm. |
---|
944 | /// |
---|
945 | /// This function also has several \ref named-templ-func-param |
---|
946 | /// "named parameters", they are declared as the members of class |
---|
947 | /// \ref BellmanFordWizard. |
---|
948 | /// The following |
---|
949 | /// example shows how to use these parameters. |
---|
950 | ///\code |
---|
951 | /// bellmanford(g,length,source).predMap(preds).run(); |
---|
952 | ///\endcode |
---|
953 | /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()" |
---|
954 | /// to the end of the parameter list. |
---|
955 | /// \sa BellmanFordWizard |
---|
956 | /// \sa BellmanFord |
---|
957 | template<class _Graph, class _LengthMap> |
---|
958 | BellmanFordWizard<BellmanFordWizardBase<_Graph,_LengthMap> > |
---|
959 | bellmanFord(const _Graph& graph, |
---|
960 | const _LengthMap& length, |
---|
961 | typename _Graph::Node source = INVALID) { |
---|
962 | return BellmanFordWizard<BellmanFordWizardBase<_Graph,_LengthMap> > |
---|
963 | (graph, length, source); |
---|
964 | } |
---|
965 | |
---|
966 | } //END OF NAMESPACE LEMON |
---|
967 | |
---|
968 | #endif |
---|
969 | |
---|