0
2
0
1 | 1 |
/* -*- C++ -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2008 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_BELLMAN_FORD_H |
20 | 20 |
#define LEMON_BELLMAN_FORD_H |
21 | 21 |
|
22 | 22 |
/// \ingroup shortest_path |
23 | 23 |
/// \file |
24 | 24 |
/// \brief Bellman-Ford algorithm. |
25 | 25 |
|
26 |
#include <lemon/list_graph.h> |
|
26 | 27 |
#include <lemon/bits/path_dump.h> |
27 | 28 |
#include <lemon/core.h> |
28 | 29 |
#include <lemon/error.h> |
29 | 30 |
#include <lemon/maps.h> |
30 | 31 |
#include <lemon/path.h> |
31 | 32 |
|
32 | 33 |
#include <limits> |
33 | 34 |
|
34 | 35 |
namespace lemon { |
35 | 36 |
|
36 | 37 |
/// \brief Default OperationTraits for the BellmanFord algorithm class. |
37 | 38 |
/// |
38 | 39 |
/// This operation traits class defines all computational operations |
39 | 40 |
/// and constants that are used in the Bellman-Ford algorithm. |
40 | 41 |
/// The default implementation is based on the \c numeric_limits class. |
41 | 42 |
/// If the numeric type does not have infinity value, then the maximum |
42 | 43 |
/// value is used as extremal infinity value. |
43 | 44 |
template < |
44 | 45 |
typename V, |
45 | 46 |
bool has_inf = std::numeric_limits<V>::has_infinity> |
46 | 47 |
struct BellmanFordDefaultOperationTraits { |
47 | 48 |
/// \e |
48 | 49 |
typedef V Value; |
49 | 50 |
/// \brief Gives back the zero value of the type. |
50 | 51 |
static Value zero() { |
51 | 52 |
return static_cast<Value>(0); |
52 | 53 |
} |
53 | 54 |
/// \brief Gives back the positive infinity value of the type. |
54 | 55 |
static Value infinity() { |
55 | 56 |
return std::numeric_limits<Value>::infinity(); |
56 | 57 |
} |
57 | 58 |
/// \brief Gives back the sum of the given two elements. |
58 | 59 |
static Value plus(const Value& left, const Value& right) { |
59 | 60 |
return left + right; |
60 | 61 |
} |
61 | 62 |
/// \brief Gives back \c true only if the first value is less than |
62 | 63 |
/// the second. |
63 | 64 |
static bool less(const Value& left, const Value& right) { |
64 | 65 |
return left < right; |
65 | 66 |
} |
66 | 67 |
}; |
67 | 68 |
|
68 | 69 |
template <typename V> |
69 | 70 |
struct BellmanFordDefaultOperationTraits<V, false> { |
70 | 71 |
typedef V Value; |
71 | 72 |
static Value zero() { |
72 | 73 |
return static_cast<Value>(0); |
73 | 74 |
} |
74 | 75 |
static Value infinity() { |
75 | 76 |
return std::numeric_limits<Value>::max(); |
76 | 77 |
} |
77 | 78 |
static Value plus(const Value& left, const Value& right) { |
78 | 79 |
if (left == infinity() || right == infinity()) return infinity(); |
79 | 80 |
return left + right; |
80 | 81 |
} |
81 | 82 |
static bool less(const Value& left, const Value& right) { |
82 | 83 |
return left < right; |
83 | 84 |
} |
84 | 85 |
}; |
85 | 86 |
|
86 | 87 |
/// \brief Default traits class of BellmanFord class. |
87 | 88 |
/// |
88 | 89 |
/// Default traits class of BellmanFord class. |
89 | 90 |
/// \param GR The type of the digraph. |
90 | 91 |
/// \param LEN The type of the length map. |
91 | 92 |
template<typename GR, typename LEN> |
92 | 93 |
struct BellmanFordDefaultTraits { |
93 | 94 |
/// The type of the digraph the algorithm runs on. |
94 | 95 |
typedef GR Digraph; |
95 | 96 |
|
96 | 97 |
/// \brief The type of the map that stores the arc lengths. |
97 | 98 |
/// |
98 | 99 |
/// The type of the map that stores the arc lengths. |
99 | 100 |
/// It must conform to the \ref concepts::ReadMap "ReadMap" concept. |
100 | 101 |
typedef LEN LengthMap; |
101 | 102 |
|
102 | 103 |
/// The type of the arc lengths. |
103 | 104 |
typedef typename LEN::Value Value; |
104 | 105 |
|
105 | 106 |
/// \brief Operation traits for Bellman-Ford algorithm. |
106 | 107 |
/// |
107 | 108 |
/// It defines the used operations and the infinity value for the |
108 | 109 |
/// given \c Value type. |
109 | 110 |
/// \see BellmanFordDefaultOperationTraits |
110 | 111 |
typedef BellmanFordDefaultOperationTraits<Value> OperationTraits; |
111 | 112 |
|
112 | 113 |
/// \brief The type of the map that stores the last arcs of the |
113 | 114 |
/// shortest paths. |
114 | 115 |
/// |
115 | 116 |
/// The type of the map that stores the last |
116 | 117 |
/// arcs of the shortest paths. |
117 | 118 |
/// It must conform to the \ref concepts::WriteMap "WriteMap" concept. |
118 | 119 |
typedef typename GR::template NodeMap<typename GR::Arc> PredMap; |
119 | 120 |
|
120 | 121 |
/// \brief Instantiates a \c PredMap. |
121 | 122 |
/// |
122 | 123 |
/// This function instantiates a \ref PredMap. |
123 | 124 |
/// \param g is the digraph to which we would like to define the |
124 | 125 |
/// \ref PredMap. |
125 | 126 |
static PredMap *createPredMap(const GR& g) { |
126 | 127 |
return new PredMap(g); |
127 | 128 |
} |
128 | 129 |
|
129 | 130 |
/// \brief The type of the map that stores the distances of the nodes. |
130 | 131 |
/// |
131 | 132 |
/// The type of the map that stores the distances of the nodes. |
132 | 133 |
/// It must conform to the \ref concepts::WriteMap "WriteMap" concept. |
133 | 134 |
typedef typename GR::template NodeMap<typename LEN::Value> DistMap; |
134 | 135 |
|
135 | 136 |
/// \brief Instantiates a \c DistMap. |
136 | 137 |
/// |
137 | 138 |
/// This function instantiates a \ref DistMap. |
138 | 139 |
/// \param g is the digraph to which we would like to define the |
139 | 140 |
/// \ref DistMap. |
140 | 141 |
static DistMap *createDistMap(const GR& g) { |
141 | 142 |
return new DistMap(g); |
142 | 143 |
} |
143 | 144 |
|
144 | 145 |
}; |
145 | 146 |
|
146 | 147 |
/// \brief %BellmanFord algorithm class. |
147 | 148 |
/// |
148 | 149 |
/// \ingroup shortest_path |
149 | 150 |
/// This class provides an efficient implementation of the Bellman-Ford |
150 | 151 |
/// algorithm. The maximum time complexity of the algorithm is |
151 | 152 |
/// <tt>O(ne)</tt>. |
152 | 153 |
/// |
153 | 154 |
/// The Bellman-Ford algorithm solves the single-source shortest path |
154 | 155 |
/// problem when the arcs can have negative lengths, but the digraph |
155 | 156 |
/// should not contain directed cycles with negative total length. |
156 | 157 |
/// If all arc costs are non-negative, consider to use the Dijkstra |
157 | 158 |
/// algorithm instead, since it is more efficient. |
158 | 159 |
/// |
159 | 160 |
/// The arc lengths are passed to the algorithm using a |
160 | 161 |
/// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any |
161 | 162 |
/// kind of length. The type of the length values is determined by the |
162 | 163 |
/// \ref concepts::ReadMap::Value "Value" type of the length map. |
163 | 164 |
/// |
164 | 165 |
/// There is also a \ref bellmanFord() "function-type interface" for the |
165 | 166 |
/// Bellman-Ford algorithm, which is convenient in the simplier cases and |
166 | 167 |
/// it can be used easier. |
167 | 168 |
/// |
168 | 169 |
/// \tparam GR The type of the digraph the algorithm runs on. |
169 | 170 |
/// The default type is \ref ListDigraph. |
170 | 171 |
/// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies |
171 | 172 |
/// the lengths of the arcs. The default map type is |
172 | 173 |
/// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>". |
173 | 174 |
#ifdef DOXYGEN |
174 | 175 |
template <typename GR, typename LEN, typename TR> |
175 | 176 |
#else |
176 | 177 |
template <typename GR=ListDigraph, |
177 | 178 |
typename LEN=typename GR::template ArcMap<int>, |
178 | 179 |
typename TR=BellmanFordDefaultTraits<GR,LEN> > |
179 | 180 |
#endif |
180 | 181 |
class BellmanFord { |
181 | 182 |
public: |
182 | 183 |
|
183 | 184 |
///The type of the underlying digraph. |
184 | 185 |
typedef typename TR::Digraph Digraph; |
185 | 186 |
|
186 | 187 |
/// \brief The type of the arc lengths. |
187 | 188 |
typedef typename TR::LengthMap::Value Value; |
188 | 189 |
/// \brief The type of the map that stores the arc lengths. |
189 | 190 |
typedef typename TR::LengthMap LengthMap; |
190 | 191 |
/// \brief The type of the map that stores the last |
191 | 192 |
/// arcs of the shortest paths. |
192 | 193 |
typedef typename TR::PredMap PredMap; |
193 | 194 |
/// \brief The type of the map that stores the distances of the nodes. |
194 | 195 |
typedef typename TR::DistMap DistMap; |
195 | 196 |
/// The type of the paths. |
196 | 197 |
typedef PredMapPath<Digraph, PredMap> Path; |
197 | 198 |
///\brief The \ref BellmanFordDefaultOperationTraits |
198 | 199 |
/// "operation traits class" of the algorithm. |
199 | 200 |
typedef typename TR::OperationTraits OperationTraits; |
200 | 201 |
|
201 | 202 |
///The \ref BellmanFordDefaultTraits "traits class" of the algorithm. |
202 | 203 |
typedef TR Traits; |
203 | 204 |
|
204 | 205 |
private: |
205 | 206 |
|
206 | 207 |
typedef typename Digraph::Node Node; |
207 | 208 |
typedef typename Digraph::NodeIt NodeIt; |
208 | 209 |
typedef typename Digraph::Arc Arc; |
209 | 210 |
typedef typename Digraph::OutArcIt OutArcIt; |
210 | 211 |
|
211 | 212 |
// Pointer to the underlying digraph. |
212 | 213 |
const Digraph *_gr; |
213 | 214 |
// Pointer to the length map |
214 | 215 |
const LengthMap *_length; |
215 | 216 |
// Pointer to the map of predecessors arcs. |
216 | 217 |
PredMap *_pred; |
217 | 218 |
// Indicates if _pred is locally allocated (true) or not. |
218 | 219 |
bool _local_pred; |
219 | 220 |
// Pointer to the map of distances. |
220 | 221 |
DistMap *_dist; |
221 | 222 |
// Indicates if _dist is locally allocated (true) or not. |
222 | 223 |
bool _local_dist; |
223 | 224 |
|
224 | 225 |
typedef typename Digraph::template NodeMap<bool> MaskMap; |
225 | 226 |
MaskMap *_mask; |
226 | 227 |
|
227 | 228 |
std::vector<Node> _process; |
228 | 229 |
|
229 | 230 |
// Creates the maps if necessary. |
230 | 231 |
void create_maps() { |
231 | 232 |
if(!_pred) { |
232 | 233 |
_local_pred = true; |
233 | 234 |
_pred = Traits::createPredMap(*_gr); |
234 | 235 |
} |
235 | 236 |
if(!_dist) { |
236 | 237 |
_local_dist = true; |
237 | 238 |
_dist = Traits::createDistMap(*_gr); |
238 | 239 |
} |
239 | 240 |
_mask = new MaskMap(*_gr, false); |
240 | 241 |
} |
241 | 242 |
|
242 | 243 |
public : |
243 | 244 |
|
244 | 245 |
typedef BellmanFord Create; |
245 | 246 |
|
246 | 247 |
/// \name Named Template Parameters |
247 | 248 |
|
248 | 249 |
///@{ |
249 | 250 |
|
250 | 251 |
template <class T> |
251 | 252 |
struct SetPredMapTraits : public Traits { |
252 | 253 |
typedef T PredMap; |
253 | 254 |
static PredMap *createPredMap(const Digraph&) { |
254 | 255 |
LEMON_ASSERT(false, "PredMap is not initialized"); |
255 | 256 |
return 0; // ignore warnings |
256 | 257 |
} |
257 | 258 |
}; |
258 | 259 |
|
259 | 260 |
/// \brief \ref named-templ-param "Named parameter" for setting |
260 | 261 |
/// \c PredMap type. |
261 | 262 |
/// |
262 | 263 |
/// \ref named-templ-param "Named parameter" for setting |
263 | 264 |
/// \c PredMap type. |
264 | 265 |
/// It must conform to the \ref concepts::WriteMap "WriteMap" concept. |
265 | 266 |
template <class T> |
266 | 267 |
struct SetPredMap |
267 | 268 |
: public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > { |
268 | 269 |
typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create; |
269 | 270 |
}; |
270 | 271 |
|
271 | 272 |
template <class T> |
272 | 273 |
struct SetDistMapTraits : public Traits { |
273 | 274 |
typedef T DistMap; |
274 | 275 |
static DistMap *createDistMap(const Digraph&) { |
275 | 276 |
LEMON_ASSERT(false, "DistMap is not initialized"); |
276 | 277 |
return 0; // ignore warnings |
277 | 278 |
} |
278 | 279 |
}; |
279 | 280 |
|
280 | 281 |
/// \brief \ref named-templ-param "Named parameter" for setting |
281 | 282 |
/// \c DistMap type. |
282 | 283 |
/// |
283 | 284 |
/// \ref named-templ-param "Named parameter" for setting |
284 | 285 |
/// \c DistMap type. |
285 | 286 |
/// It must conform to the \ref concepts::WriteMap "WriteMap" concept. |
286 | 287 |
template <class T> |
287 | 288 |
struct SetDistMap |
288 | 289 |
: public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > { |
289 | 290 |
typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create; |
290 | 291 |
}; |
291 | 292 |
|
292 | 293 |
template <class T> |
293 | 294 |
struct SetOperationTraitsTraits : public Traits { |
294 | 295 |
typedef T OperationTraits; |
295 | 296 |
}; |
296 | 297 |
|
297 | 298 |
/// \brief \ref named-templ-param "Named parameter" for setting |
298 | 299 |
/// \c OperationTraits type. |
299 | 300 |
/// |
300 | 301 |
/// \ref named-templ-param "Named parameter" for setting |
301 | 302 |
/// \c OperationTraits type. |
302 | 303 |
/// For more information see \ref BellmanFordDefaultOperationTraits. |
303 | 304 |
template <class T> |
304 | 305 |
struct SetOperationTraits |
305 | 306 |
: public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > { |
306 | 307 |
typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > |
307 | 308 |
Create; |
308 | 309 |
}; |
309 | 310 |
|
310 | 311 |
///@} |
311 | 312 |
|
312 | 313 |
protected: |
313 | 314 |
|
314 | 315 |
BellmanFord() {} |
315 | 316 |
|
316 | 317 |
public: |
317 | 318 |
|
318 | 319 |
/// \brief Constructor. |
319 | 320 |
/// |
320 | 321 |
/// Constructor. |
321 | 322 |
/// \param g The digraph the algorithm runs on. |
322 | 323 |
/// \param length The length map used by the algorithm. |
323 | 324 |
BellmanFord(const Digraph& g, const LengthMap& length) : |
324 | 325 |
_gr(&g), _length(&length), |
325 | 326 |
_pred(0), _local_pred(false), |
326 | 327 |
_dist(0), _local_dist(false), _mask(0) {} |
327 | 328 |
|
328 | 329 |
///Destructor. |
329 | 330 |
~BellmanFord() { |
330 | 331 |
if(_local_pred) delete _pred; |
331 | 332 |
if(_local_dist) delete _dist; |
332 | 333 |
if(_mask) delete _mask; |
333 | 334 |
} |
334 | 335 |
|
335 | 336 |
/// \brief Sets the length map. |
336 | 337 |
/// |
337 | 338 |
/// Sets the length map. |
338 | 339 |
/// \return <tt>(*this)</tt> |
339 | 340 |
BellmanFord &lengthMap(const LengthMap &map) { |
340 | 341 |
_length = ↦ |
341 | 342 |
return *this; |
342 | 343 |
} |
343 | 344 |
|
344 | 345 |
/// \brief Sets the map that stores the predecessor arcs. |
345 | 346 |
/// |
346 | 347 |
/// Sets the map that stores the predecessor arcs. |
347 | 348 |
/// If you don't use this function before calling \ref run() |
348 | 349 |
/// or \ref init(), an instance will be allocated automatically. |
349 | 350 |
/// The destructor deallocates this automatically allocated map, |
350 | 351 |
/// of course. |
351 | 352 |
/// \return <tt>(*this)</tt> |
352 | 353 |
BellmanFord &predMap(PredMap &map) { |
353 | 354 |
if(_local_pred) { |
354 | 355 |
delete _pred; |
355 | 356 |
_local_pred=false; |
356 | 357 |
} |
357 | 358 |
_pred = ↦ |
358 | 359 |
return *this; |
359 | 360 |
} |
360 | 361 |
|
361 | 362 |
/// \brief Sets the map that stores the distances of the nodes. |
362 | 363 |
/// |
363 | 364 |
/// Sets the map that stores the distances of the nodes calculated |
364 | 365 |
/// by the algorithm. |
365 | 366 |
/// If you don't use this function before calling \ref run() |
366 | 367 |
/// or \ref init(), an instance will be allocated automatically. |
367 | 368 |
/// The destructor deallocates this automatically allocated map, |
368 | 369 |
/// of course. |
369 | 370 |
/// \return <tt>(*this)</tt> |
370 | 371 |
BellmanFord &distMap(DistMap &map) { |
371 | 372 |
if(_local_dist) { |
372 | 373 |
delete _dist; |
373 | 374 |
_local_dist=false; |
374 | 375 |
} |
375 | 376 |
_dist = ↦ |
376 | 377 |
return *this; |
377 | 378 |
} |
378 | 379 |
|
379 | 380 |
/// \name Execution Control |
380 | 381 |
/// The simplest way to execute the Bellman-Ford algorithm is to use |
381 | 382 |
/// one of the member functions called \ref run().\n |
382 | 383 |
/// If you need better control on the execution, you have to call |
383 | 384 |
/// \ref init() first, then you can add several source nodes |
384 | 385 |
/// with \ref addSource(). Finally the actual path computation can be |
385 | 386 |
/// performed with \ref start(), \ref checkedStart() or |
386 | 387 |
/// \ref limitedStart(). |
387 | 388 |
|
388 | 389 |
///@{ |
389 | 390 |
|
390 | 391 |
/// \brief Initializes the internal data structures. |
391 | 392 |
/// |
392 | 393 |
/// Initializes the internal data structures. The optional parameter |
393 | 394 |
/// is the initial distance of each node. |
394 | 395 |
void init(const Value value = OperationTraits::infinity()) { |
395 | 396 |
create_maps(); |
396 | 397 |
for (NodeIt it(*_gr); it != INVALID; ++it) { |
397 | 398 |
_pred->set(it, INVALID); |
398 | 399 |
_dist->set(it, value); |
399 | 400 |
} |
400 | 401 |
_process.clear(); |
401 | 402 |
if (OperationTraits::less(value, OperationTraits::infinity())) { |
402 | 403 |
for (NodeIt it(*_gr); it != INVALID; ++it) { |
403 | 404 |
_process.push_back(it); |
404 | 405 |
_mask->set(it, true); |
405 | 406 |
} |
406 | 407 |
} |
407 | 408 |
} |
408 | 409 |
|
409 | 410 |
/// \brief Adds a new source node. |
410 | 411 |
/// |
411 | 412 |
/// This function adds a new source node. The optional second parameter |
412 | 413 |
/// is the initial distance of the node. |
413 | 414 |
void addSource(Node source, Value dst = OperationTraits::zero()) { |
414 | 415 |
_dist->set(source, dst); |
415 | 416 |
if (!(*_mask)[source]) { |
416 | 417 |
_process.push_back(source); |
417 | 418 |
_mask->set(source, true); |
418 | 419 |
} |
419 | 420 |
} |
420 | 421 |
|
421 | 422 |
/// \brief Executes one round from the Bellman-Ford algorithm. |
422 | 423 |
/// |
423 | 424 |
/// If the algoritm calculated the distances in the previous round |
424 | 425 |
/// exactly for the paths of at most \c k arcs, then this function |
425 | 426 |
/// will calculate the distances exactly for the paths of at most |
426 | 427 |
/// <tt>k+1</tt> arcs. Performing \c k iterations using this function |
427 | 428 |
/// calculates the shortest path distances exactly for the paths |
428 | 429 |
/// consisting of at most \c k arcs. |
429 | 430 |
/// |
430 | 431 |
/// \warning The paths with limited arc number cannot be retrieved |
431 | 432 |
/// easily with \ref path() or \ref predArc() functions. If you also |
432 | 433 |
/// need the shortest paths and not only the distances, you should |
433 | 434 |
/// store the \ref predMap() "predecessor map" after each iteration |
434 | 435 |
/// and build the path manually. |
435 | 436 |
/// |
436 | 437 |
/// \return \c true when the algorithm have not found more shorter |
437 | 438 |
/// paths. |
438 | 439 |
/// |
439 | 440 |
/// \see ActiveIt |
440 | 441 |
bool processNextRound() { |
441 | 442 |
for (int i = 0; i < int(_process.size()); ++i) { |
442 | 443 |
_mask->set(_process[i], false); |
443 | 444 |
} |
444 | 445 |
std::vector<Node> nextProcess; |
445 | 446 |
std::vector<Value> values(_process.size()); |
446 | 447 |
for (int i = 0; i < int(_process.size()); ++i) { |
447 | 448 |
values[i] = (*_dist)[_process[i]]; |
448 | 449 |
} |
449 | 450 |
for (int i = 0; i < int(_process.size()); ++i) { |
450 | 451 |
for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) { |
451 | 452 |
Node target = _gr->target(it); |
452 | 453 |
Value relaxed = OperationTraits::plus(values[i], (*_length)[it]); |
453 | 454 |
if (OperationTraits::less(relaxed, (*_dist)[target])) { |
454 | 455 |
_pred->set(target, it); |
455 | 456 |
_dist->set(target, relaxed); |
456 | 457 |
if (!(*_mask)[target]) { |
457 | 458 |
_mask->set(target, true); |
458 | 459 |
nextProcess.push_back(target); |
459 | 460 |
} |
460 | 461 |
} |
461 | 462 |
} |
462 | 463 |
} |
463 | 464 |
_process.swap(nextProcess); |
464 | 465 |
return _process.empty(); |
465 | 466 |
} |
466 | 467 |
|
467 | 468 |
/// \brief Executes one weak round from the Bellman-Ford algorithm. |
468 | 469 |
/// |
469 | 470 |
/// If the algorithm calculated the distances in the previous round |
470 | 471 |
/// at least for the paths of at most \c k arcs, then this function |
471 | 472 |
/// will calculate the distances at least for the paths of at most |
472 | 473 |
/// <tt>k+1</tt> arcs. |
473 | 474 |
/// This function does not make it possible to calculate the shortest |
474 | 475 |
/// path distances exactly for paths consisting of at most \c k arcs, |
475 | 476 |
/// this is why it is called weak round. |
476 | 477 |
/// |
477 | 478 |
/// \return \c true when the algorithm have not found more shorter |
478 | 479 |
/// paths. |
479 | 480 |
/// |
480 | 481 |
/// \see ActiveIt |
481 | 482 |
bool processNextWeakRound() { |
482 | 483 |
for (int i = 0; i < int(_process.size()); ++i) { |
483 | 484 |
_mask->set(_process[i], false); |
484 | 485 |
} |
485 | 486 |
std::vector<Node> nextProcess; |
486 | 487 |
for (int i = 0; i < int(_process.size()); ++i) { |
487 | 488 |
for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) { |
488 | 489 |
Node target = _gr->target(it); |
489 | 490 |
Value relaxed = |
490 | 491 |
OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]); |
491 | 492 |
if (OperationTraits::less(relaxed, (*_dist)[target])) { |
492 | 493 |
_pred->set(target, it); |
493 | 494 |
_dist->set(target, relaxed); |
494 | 495 |
if (!(*_mask)[target]) { |
495 | 496 |
_mask->set(target, true); |
496 | 497 |
nextProcess.push_back(target); |
497 | 498 |
} |
498 | 499 |
} |
499 | 500 |
} |
500 | 501 |
} |
501 | 502 |
_process.swap(nextProcess); |
502 | 503 |
return _process.empty(); |
503 | 504 |
} |
504 | 505 |
|
505 | 506 |
/// \brief Executes the algorithm. |
506 | 507 |
/// |
507 | 508 |
/// Executes the algorithm. |
508 | 509 |
/// |
509 | 510 |
/// This method runs the Bellman-Ford algorithm from the root node(s) |
510 | 511 |
/// in order to compute the shortest path to each node. |
511 | 512 |
/// |
512 | 513 |
/// The algorithm computes |
513 | 514 |
/// - the shortest path tree (forest), |
514 | 515 |
/// - the distance of each node from the root(s). |
515 | 516 |
/// |
516 | 517 |
/// \pre init() must be called and at least one root node should be |
517 | 518 |
/// added with addSource() before using this function. |
518 | 519 |
void start() { |
519 | 520 |
int num = countNodes(*_gr) - 1; |
520 | 521 |
for (int i = 0; i < num; ++i) { |
521 | 522 |
if (processNextWeakRound()) break; |
522 | 523 |
} |
523 | 524 |
} |
524 | 525 |
|
525 | 526 |
/// \brief Executes the algorithm and checks the negative cycles. |
526 | 527 |
/// |
527 | 528 |
/// Executes the algorithm and checks the negative cycles. |
528 | 529 |
/// |
529 | 530 |
/// This method runs the Bellman-Ford algorithm from the root node(s) |
530 | 531 |
/// in order to compute the shortest path to each node and also checks |
531 | 532 |
/// if the digraph contains cycles with negative total length. |
532 | 533 |
/// |
533 | 534 |
/// The algorithm computes |
534 | 535 |
/// - the shortest path tree (forest), |
535 | 536 |
/// - the distance of each node from the root(s). |
536 | 537 |
/// |
537 | 538 |
/// \return \c false if there is a negative cycle in the digraph. |
538 | 539 |
/// |
539 | 540 |
/// \pre init() must be called and at least one root node should be |
540 | 541 |
/// added with addSource() before using this function. |
541 | 542 |
bool checkedStart() { |
542 | 543 |
int num = countNodes(*_gr); |
543 | 544 |
for (int i = 0; i < num; ++i) { |
544 | 545 |
if (processNextWeakRound()) return true; |
545 | 546 |
} |
546 | 547 |
return _process.empty(); |
547 | 548 |
} |
548 | 549 |
|
549 | 550 |
/// \brief Executes the algorithm with arc number limit. |
550 | 551 |
/// |
551 | 552 |
/// Executes the algorithm with arc number limit. |
552 | 553 |
/// |
553 | 554 |
/// This method runs the Bellman-Ford algorithm from the root node(s) |
554 | 555 |
/// in order to compute the shortest path distance for each node |
555 | 556 |
/// using only the paths consisting of at most \c num arcs. |
556 | 557 |
/// |
557 | 558 |
/// The algorithm computes |
558 | 559 |
/// - the limited distance of each node from the root(s), |
559 | 560 |
/// - the predecessor arc for each node. |
560 | 561 |
/// |
561 | 562 |
/// \warning The paths with limited arc number cannot be retrieved |
562 | 563 |
/// easily with \ref path() or \ref predArc() functions. If you also |
563 | 564 |
/// need the shortest paths and not only the distances, you should |
564 | 565 |
/// store the \ref predMap() "predecessor map" after each iteration |
565 | 566 |
/// and build the path manually. |
566 | 567 |
/// |
567 | 568 |
/// \pre init() must be called and at least one root node should be |
568 | 569 |
/// added with addSource() before using this function. |
569 | 570 |
void limitedStart(int num) { |
570 | 571 |
for (int i = 0; i < num; ++i) { |
571 | 572 |
if (processNextRound()) break; |
572 | 573 |
} |
573 | 574 |
} |
574 | 575 |
|
575 | 576 |
/// \brief Runs the algorithm from the given root node. |
576 | 577 |
/// |
577 | 578 |
/// This method runs the Bellman-Ford algorithm from the given root |
578 | 579 |
/// node \c s in order to compute the shortest path to each node. |
579 | 580 |
/// |
580 | 581 |
/// The algorithm computes |
581 | 582 |
/// - the shortest path tree (forest), |
582 | 583 |
/// - the distance of each node from the root(s). |
583 | 584 |
/// |
584 | 585 |
/// \note bf.run(s) is just a shortcut of the following code. |
585 | 586 |
/// \code |
586 | 587 |
/// bf.init(); |
587 | 588 |
/// bf.addSource(s); |
588 | 589 |
/// bf.start(); |
589 | 590 |
/// \endcode |
590 | 591 |
void run(Node s) { |
591 | 592 |
init(); |
592 | 593 |
addSource(s); |
593 | 594 |
start(); |
594 | 595 |
} |
595 | 596 |
|
596 | 597 |
/// \brief Runs the algorithm from the given root node with arc |
597 | 598 |
/// number limit. |
598 | 599 |
/// |
599 | 600 |
/// This method runs the Bellman-Ford algorithm from the given root |
600 | 601 |
/// node \c s in order to compute the shortest path distance for each |
601 | 602 |
/// node using only the paths consisting of at most \c num arcs. |
602 | 603 |
/// |
603 | 604 |
/// The algorithm computes |
604 | 605 |
/// - the limited distance of each node from the root(s), |
605 | 606 |
/// - the predecessor arc for each node. |
606 | 607 |
/// |
607 | 608 |
/// \warning The paths with limited arc number cannot be retrieved |
608 | 609 |
/// easily with \ref path() or \ref predArc() functions. If you also |
609 | 610 |
/// need the shortest paths and not only the distances, you should |
610 | 611 |
/// store the \ref predMap() "predecessor map" after each iteration |
611 | 612 |
/// and build the path manually. |
612 | 613 |
/// |
613 | 614 |
/// \note bf.run(s, num) is just a shortcut of the following code. |
614 | 615 |
/// \code |
615 | 616 |
/// bf.init(); |
616 | 617 |
/// bf.addSource(s); |
617 | 618 |
/// bf.limitedStart(num); |
618 | 619 |
/// \endcode |
619 | 620 |
void run(Node s, int num) { |
620 | 621 |
init(); |
621 | 622 |
addSource(s); |
622 | 623 |
limitedStart(num); |
623 | 624 |
} |
624 | 625 |
|
625 | 626 |
///@} |
626 | 627 |
|
627 | 628 |
/// \brief LEMON iterator for getting the active nodes. |
628 | 629 |
/// |
629 | 630 |
/// This class provides a common style LEMON iterator that traverses |
630 | 631 |
/// the active nodes of the Bellman-Ford algorithm after the last |
631 | 632 |
/// phase. These nodes should be checked in the next phase to |
632 | 633 |
/// find augmenting arcs outgoing from them. |
633 | 634 |
class ActiveIt { |
634 | 635 |
public: |
635 | 636 |
|
636 | 637 |
/// \brief Constructor. |
637 | 638 |
/// |
638 | 639 |
/// Constructor for getting the active nodes of the given BellmanFord |
639 | 640 |
/// instance. |
640 | 641 |
ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm) |
641 | 642 |
{ |
642 | 643 |
_index = _algorithm->_process.size() - 1; |
643 | 644 |
} |
644 | 645 |
|
645 | 646 |
/// \brief Invalid constructor. |
646 | 647 |
/// |
647 | 648 |
/// Invalid constructor. |
648 | 649 |
ActiveIt(Invalid) : _algorithm(0), _index(-1) {} |
649 | 650 |
|
650 | 651 |
/// \brief Conversion to \c Node. |
651 | 652 |
/// |
652 | 653 |
/// Conversion to \c Node. |
653 | 654 |
operator Node() const { |
654 | 655 |
return _index >= 0 ? _algorithm->_process[_index] : INVALID; |
655 | 656 |
} |
656 | 657 |
|
657 | 658 |
/// \brief Increment operator. |
658 | 659 |
/// |
659 | 660 |
/// Increment operator. |
660 | 661 |
ActiveIt& operator++() { |
661 | 662 |
--_index; |
662 | 663 |
return *this; |
663 | 664 |
} |
664 | 665 |
|
665 | 666 |
bool operator==(const ActiveIt& it) const { |
666 | 667 |
return static_cast<Node>(*this) == static_cast<Node>(it); |
667 | 668 |
} |
668 | 669 |
bool operator!=(const ActiveIt& it) const { |
669 | 670 |
return static_cast<Node>(*this) != static_cast<Node>(it); |
670 | 671 |
} |
671 | 672 |
bool operator<(const ActiveIt& it) const { |
672 | 673 |
return static_cast<Node>(*this) < static_cast<Node>(it); |
673 | 674 |
} |
674 | 675 |
|
675 | 676 |
private: |
676 | 677 |
const BellmanFord* _algorithm; |
677 | 678 |
int _index; |
678 | 679 |
}; |
679 | 680 |
|
680 | 681 |
/// \name Query Functions |
681 | 682 |
/// The result of the Bellman-Ford algorithm can be obtained using these |
682 | 683 |
/// functions.\n |
683 | 684 |
/// Either \ref run() or \ref init() should be called before using them. |
684 | 685 |
|
685 | 686 |
///@{ |
686 | 687 |
|
687 | 688 |
/// \brief The shortest path to the given node. |
688 | 689 |
/// |
689 | 690 |
/// Gives back the shortest path to the given node from the root(s). |
690 | 691 |
/// |
691 | 692 |
/// \warning \c t should be reached from the root(s). |
692 | 693 |
/// |
693 | 694 |
/// \pre Either \ref run() or \ref init() must be called before |
694 | 695 |
/// using this function. |
695 | 696 |
Path path(Node t) const |
696 | 697 |
{ |
697 | 698 |
return Path(*_gr, *_pred, t); |
698 | 699 |
} |
699 | 700 |
|
700 | 701 |
/// \brief The distance of the given node from the root(s). |
701 | 702 |
/// |
702 | 703 |
/// Returns the distance of the given node from the root(s). |
703 | 704 |
/// |
704 | 705 |
/// \warning If node \c v is not reached from the root(s), then |
705 | 706 |
/// the return value of this function is undefined. |
706 | 707 |
/// |
707 | 708 |
/// \pre Either \ref run() or \ref init() must be called before |
708 | 709 |
/// using this function. |
709 | 710 |
Value dist(Node v) const { return (*_dist)[v]; } |
710 | 711 |
|
711 | 712 |
/// \brief Returns the 'previous arc' of the shortest path tree for |
712 | 713 |
/// the given node. |
713 | 714 |
/// |
714 | 715 |
/// This function returns the 'previous arc' of the shortest path |
715 | 716 |
/// tree for node \c v, i.e. it returns the last arc of a |
716 | 717 |
/// shortest path from a root to \c v. It is \c INVALID if \c v |
717 | 718 |
/// is not reached from the root(s) or if \c v is a root. |
718 | 719 |
/// |
719 | 720 |
/// The shortest path tree used here is equal to the shortest path |
720 | 721 |
/// tree used in \ref predNode() and \predMap(). |
721 | 722 |
/// |
722 | 723 |
/// \pre Either \ref run() or \ref init() must be called before |
723 | 724 |
/// using this function. |
724 | 725 |
Arc predArc(Node v) const { return (*_pred)[v]; } |
725 | 726 |
|
726 | 727 |
/// \brief Returns the 'previous node' of the shortest path tree for |
727 | 728 |
/// the given node. |
728 | 729 |
/// |
729 | 730 |
/// This function returns the 'previous node' of the shortest path |
730 | 731 |
/// tree for node \c v, i.e. it returns the last but one node of |
731 | 732 |
/// a shortest path from a root to \c v. It is \c INVALID if \c v |
732 | 733 |
/// is not reached from the root(s) or if \c v is a root. |
733 | 734 |
/// |
734 | 735 |
/// The shortest path tree used here is equal to the shortest path |
735 | 736 |
/// tree used in \ref predArc() and \predMap(). |
736 | 737 |
/// |
737 | 738 |
/// \pre Either \ref run() or \ref init() must be called before |
738 | 739 |
/// using this function. |
739 | 740 |
Node predNode(Node v) const { |
740 | 741 |
return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]); |
741 | 742 |
} |
742 | 743 |
|
743 | 744 |
/// \brief Returns a const reference to the node map that stores the |
744 | 745 |
/// distances of the nodes. |
745 | 746 |
/// |
746 | 747 |
/// Returns a const reference to the node map that stores the distances |
747 | 748 |
/// of the nodes calculated by the algorithm. |
748 | 749 |
/// |
749 | 750 |
/// \pre Either \ref run() or \ref init() must be called before |
750 | 751 |
/// using this function. |
751 | 752 |
const DistMap &distMap() const { return *_dist;} |
752 | 753 |
|
753 | 754 |
/// \brief Returns a const reference to the node map that stores the |
754 | 755 |
/// predecessor arcs. |
755 | 756 |
/// |
756 | 757 |
/// Returns a const reference to the node map that stores the predecessor |
757 | 758 |
/// arcs, which form the shortest path tree (forest). |
758 | 759 |
/// |
759 | 760 |
/// \pre Either \ref run() or \ref init() must be called before |
760 | 761 |
/// using this function. |
761 | 762 |
const PredMap &predMap() const { return *_pred; } |
762 | 763 |
|
763 | 764 |
/// \brief Checks if a node is reached from the root(s). |
764 | 765 |
/// |
765 | 766 |
/// Returns \c true if \c v is reached from the root(s). |
766 | 767 |
/// |
767 | 768 |
/// \pre Either \ref run() or \ref init() must be called before |
768 | 769 |
/// using this function. |
769 | 770 |
bool reached(Node v) const { |
770 | 771 |
return (*_dist)[v] != OperationTraits::infinity(); |
771 | 772 |
} |
772 | 773 |
|
773 | 774 |
/// \brief Gives back a negative cycle. |
774 | 775 |
/// |
775 | 776 |
/// This function gives back a directed cycle with negative total |
776 | 777 |
/// length if the algorithm has already found one. |
777 | 778 |
/// Otherwise it gives back an empty path. |
778 |
lemon::Path<Digraph> negativeCycle() { |
|
779 |
lemon::Path<Digraph> negativeCycle() const { |
|
779 | 780 |
typename Digraph::template NodeMap<int> state(*_gr, -1); |
780 | 781 |
lemon::Path<Digraph> cycle; |
781 | 782 |
for (int i = 0; i < int(_process.size()); ++i) { |
782 | 783 |
if (state[_process[i]] != -1) continue; |
783 | 784 |
for (Node v = _process[i]; (*_pred)[v] != INVALID; |
784 | 785 |
v = _gr->source((*_pred)[v])) { |
785 | 786 |
if (state[v] == i) { |
786 | 787 |
cycle.addFront((*_pred)[v]); |
787 | 788 |
for (Node u = _gr->source((*_pred)[v]); u != v; |
788 | 789 |
u = _gr->source((*_pred)[u])) { |
789 | 790 |
cycle.addFront((*_pred)[u]); |
790 | 791 |
} |
791 | 792 |
return cycle; |
792 | 793 |
} |
793 | 794 |
else if (state[v] >= 0) { |
794 | 795 |
break; |
795 | 796 |
} |
796 | 797 |
state[v] = i; |
797 | 798 |
} |
798 | 799 |
} |
799 | 800 |
return cycle; |
800 | 801 |
} |
801 | 802 |
|
802 | 803 |
///@} |
803 | 804 |
}; |
804 | 805 |
|
805 | 806 |
/// \brief Default traits class of bellmanFord() function. |
806 | 807 |
/// |
807 | 808 |
/// Default traits class of bellmanFord() function. |
808 | 809 |
/// \tparam GR The type of the digraph. |
809 | 810 |
/// \tparam LEN The type of the length map. |
810 | 811 |
template <typename GR, typename LEN> |
811 | 812 |
struct BellmanFordWizardDefaultTraits { |
812 | 813 |
/// The type of the digraph the algorithm runs on. |
813 | 814 |
typedef GR Digraph; |
814 | 815 |
|
815 | 816 |
/// \brief The type of the map that stores the arc lengths. |
816 | 817 |
/// |
817 | 818 |
/// The type of the map that stores the arc lengths. |
818 | 819 |
/// It must meet the \ref concepts::ReadMap "ReadMap" concept. |
819 | 820 |
typedef LEN LengthMap; |
820 | 821 |
|
821 | 822 |
/// The type of the arc lengths. |
822 | 823 |
typedef typename LEN::Value Value; |
823 | 824 |
|
824 | 825 |
/// \brief Operation traits for Bellman-Ford algorithm. |
825 | 826 |
/// |
826 | 827 |
/// It defines the used operations and the infinity value for the |
827 | 828 |
/// given \c Value type. |
828 | 829 |
/// \see BellmanFordDefaultOperationTraits |
829 | 830 |
typedef BellmanFordDefaultOperationTraits<Value> OperationTraits; |
830 | 831 |
|
831 | 832 |
/// \brief The type of the map that stores the last |
832 | 833 |
/// arcs of the shortest paths. |
833 | 834 |
/// |
834 | 835 |
/// The type of the map that stores the last arcs of the shortest paths. |
835 | 836 |
/// It must conform to the \ref concepts::WriteMap "WriteMap" concept. |
836 | 837 |
typedef typename GR::template NodeMap<typename GR::Arc> PredMap; |
837 | 838 |
|
838 | 839 |
/// \brief Instantiates a \c PredMap. |
839 | 840 |
/// |
840 | 841 |
/// This function instantiates a \ref PredMap. |
841 | 842 |
/// \param g is the digraph to which we would like to define the |
842 | 843 |
/// \ref PredMap. |
843 | 844 |
static PredMap *createPredMap(const GR &g) { |
844 | 845 |
return new PredMap(g); |
845 | 846 |
} |
846 | 847 |
|
847 | 848 |
/// \brief The type of the map that stores the distances of the nodes. |
848 | 849 |
/// |
849 | 850 |
/// The type of the map that stores the distances of the nodes. |
850 | 851 |
/// It must conform to the \ref concepts::WriteMap "WriteMap" concept. |
851 | 852 |
typedef typename GR::template NodeMap<Value> DistMap; |
852 | 853 |
|
853 | 854 |
/// \brief Instantiates a \c DistMap. |
854 | 855 |
/// |
855 | 856 |
/// This function instantiates a \ref DistMap. |
856 | 857 |
/// \param g is the digraph to which we would like to define the |
857 | 858 |
/// \ref DistMap. |
858 | 859 |
static DistMap *createDistMap(const GR &g) { |
859 | 860 |
return new DistMap(g); |
860 | 861 |
} |
861 | 862 |
|
862 | 863 |
///The type of the shortest paths. |
863 | 864 |
|
864 | 865 |
///The type of the shortest paths. |
865 | 866 |
///It must meet the \ref concepts::Path "Path" concept. |
866 | 867 |
typedef lemon::Path<Digraph> Path; |
867 | 868 |
}; |
868 | 869 |
|
869 | 870 |
/// \brief Default traits class used by BellmanFordWizard. |
870 | 871 |
/// |
871 | 872 |
/// Default traits class used by BellmanFordWizard. |
872 | 873 |
/// \tparam GR The type of the digraph. |
873 | 874 |
/// \tparam LEN The type of the length map. |
874 | 875 |
template <typename GR, typename LEN> |
875 | 876 |
class BellmanFordWizardBase |
876 | 877 |
: public BellmanFordWizardDefaultTraits<GR, LEN> { |
877 | 878 |
|
878 | 879 |
typedef BellmanFordWizardDefaultTraits<GR, LEN> Base; |
879 | 880 |
protected: |
880 | 881 |
// Type of the nodes in the digraph. |
881 | 882 |
typedef typename Base::Digraph::Node Node; |
882 | 883 |
|
883 | 884 |
// Pointer to the underlying digraph. |
884 | 885 |
void *_graph; |
885 | 886 |
// Pointer to the length map |
886 | 887 |
void *_length; |
887 | 888 |
// Pointer to the map of predecessors arcs. |
888 | 889 |
void *_pred; |
889 | 890 |
// Pointer to the map of distances. |
890 | 891 |
void *_dist; |
891 | 892 |
//Pointer to the shortest path to the target node. |
892 | 893 |
void *_path; |
893 | 894 |
//Pointer to the distance of the target node. |
894 | 895 |
void *_di; |
895 | 896 |
|
896 | 897 |
public: |
897 | 898 |
/// Constructor. |
898 | 899 |
|
899 | 900 |
/// This constructor does not require parameters, it initiates |
900 | 901 |
/// all of the attributes to default values \c 0. |
901 | 902 |
BellmanFordWizardBase() : |
902 | 903 |
_graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {} |
903 | 904 |
|
904 | 905 |
/// Constructor. |
905 | 906 |
|
906 | 907 |
/// This constructor requires two parameters, |
907 | 908 |
/// others are initiated to \c 0. |
908 | 909 |
/// \param gr The digraph the algorithm runs on. |
909 | 910 |
/// \param len The length map. |
910 | 911 |
BellmanFordWizardBase(const GR& gr, |
911 | 912 |
const LEN& len) : |
912 | 913 |
_graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))), |
913 | 914 |
_length(reinterpret_cast<void*>(const_cast<LEN*>(&len))), |
914 | 915 |
_pred(0), _dist(0), _path(0), _di(0) {} |
915 | 916 |
|
916 | 917 |
}; |
917 | 918 |
|
918 | 919 |
/// \brief Auxiliary class for the function-type interface of the |
919 | 920 |
/// \ref BellmanFord "Bellman-Ford" algorithm. |
920 | 921 |
/// |
921 | 922 |
/// This auxiliary class is created to implement the |
922 | 923 |
/// \ref bellmanFord() "function-type interface" of the |
923 | 924 |
/// \ref BellmanFord "Bellman-Ford" algorithm. |
924 | 925 |
/// It does not have own \ref run() method, it uses the |
925 | 926 |
/// functions and features of the plain \ref BellmanFord. |
926 | 927 |
/// |
927 | 928 |
/// This class should only be used through the \ref bellmanFord() |
928 | 929 |
/// function, which makes it easier to use the algorithm. |
929 | 930 |
template<class TR> |
930 | 931 |
class BellmanFordWizard : public TR { |
931 | 932 |
typedef TR Base; |
932 | 933 |
|
933 | 934 |
typedef typename TR::Digraph Digraph; |
934 | 935 |
|
935 | 936 |
typedef typename Digraph::Node Node; |
936 | 937 |
typedef typename Digraph::NodeIt NodeIt; |
937 | 938 |
typedef typename Digraph::Arc Arc; |
938 | 939 |
typedef typename Digraph::OutArcIt ArcIt; |
939 | 940 |
|
940 | 941 |
typedef typename TR::LengthMap LengthMap; |
941 | 942 |
typedef typename LengthMap::Value Value; |
942 | 943 |
typedef typename TR::PredMap PredMap; |
943 | 944 |
typedef typename TR::DistMap DistMap; |
944 | 945 |
typedef typename TR::Path Path; |
945 | 946 |
|
946 | 947 |
public: |
947 | 948 |
/// Constructor. |
948 | 949 |
BellmanFordWizard() : TR() {} |
949 | 950 |
|
950 | 951 |
/// \brief Constructor that requires parameters. |
951 | 952 |
/// |
952 | 953 |
/// Constructor that requires parameters. |
953 | 954 |
/// These parameters will be the default values for the traits class. |
954 | 955 |
/// \param gr The digraph the algorithm runs on. |
955 | 956 |
/// \param len The length map. |
956 | 957 |
BellmanFordWizard(const Digraph& gr, const LengthMap& len) |
957 | 958 |
: TR(gr, len) {} |
958 | 959 |
|
959 | 960 |
/// \brief Copy constructor |
960 | 961 |
BellmanFordWizard(const TR &b) : TR(b) {} |
961 | 962 |
|
962 | 963 |
~BellmanFordWizard() {} |
963 | 964 |
|
964 | 965 |
/// \brief Runs the Bellman-Ford algorithm from the given source node. |
965 | 966 |
/// |
966 | 967 |
/// This method runs the Bellman-Ford algorithm from the given source |
967 | 968 |
/// node in order to compute the shortest path to each node. |
968 | 969 |
void run(Node s) { |
969 | 970 |
BellmanFord<Digraph,LengthMap,TR> |
970 | 971 |
bf(*reinterpret_cast<const Digraph*>(Base::_graph), |
971 | 972 |
*reinterpret_cast<const LengthMap*>(Base::_length)); |
972 | 973 |
if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
973 | 974 |
if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
974 | 975 |
bf.run(s); |
975 | 976 |
} |
976 | 977 |
|
977 | 978 |
/// \brief Runs the Bellman-Ford algorithm to find the shortest path |
978 | 979 |
/// between \c s and \c t. |
979 | 980 |
/// |
980 | 981 |
/// This method runs the Bellman-Ford algorithm from node \c s |
981 | 982 |
/// in order to compute the shortest path to node \c t. |
982 | 983 |
/// Actually, it computes the shortest path to each node, but using |
983 | 984 |
/// this function you can retrieve the distance and the shortest path |
984 | 985 |
/// for a single target node easier. |
985 | 986 |
/// |
986 | 987 |
/// \return \c true if \c t is reachable form \c s. |
987 | 988 |
bool run(Node s, Node t) { |
988 | 989 |
BellmanFord<Digraph,LengthMap,TR> |
989 | 990 |
bf(*reinterpret_cast<const Digraph*>(Base::_graph), |
990 | 991 |
*reinterpret_cast<const LengthMap*>(Base::_length)); |
991 | 992 |
if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
992 | 993 |
if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
993 | 994 |
bf.run(s); |
994 | 995 |
if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t); |
995 | 996 |
if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t); |
996 | 997 |
return bf.reached(t); |
997 | 998 |
} |
998 | 999 |
|
999 | 1000 |
template<class T> |
1000 | 1001 |
struct SetPredMapBase : public Base { |
1001 | 1002 |
typedef T PredMap; |
1002 | 1003 |
static PredMap *createPredMap(const Digraph &) { return 0; }; |
1003 | 1004 |
SetPredMapBase(const TR &b) : TR(b) {} |
1004 | 1005 |
}; |
1005 | 1006 |
|
1006 | 1007 |
/// \brief \ref named-templ-param "Named parameter" for setting |
1007 | 1008 |
/// the predecessor map. |
1008 | 1009 |
/// |
1009 | 1010 |
/// \ref named-templ-param "Named parameter" for setting |
1010 | 1011 |
/// the map that stores the predecessor arcs of the nodes. |
1011 | 1012 |
template<class T> |
1012 | 1013 |
BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) { |
1013 | 1014 |
Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1014 | 1015 |
return BellmanFordWizard<SetPredMapBase<T> >(*this); |
1015 | 1016 |
} |
1016 | 1017 |
|
1017 | 1018 |
template<class T> |
1018 | 1019 |
struct SetDistMapBase : public Base { |
1019 | 1020 |
typedef T DistMap; |
1020 | 1021 |
static DistMap *createDistMap(const Digraph &) { return 0; }; |
1021 | 1022 |
SetDistMapBase(const TR &b) : TR(b) {} |
1022 | 1023 |
}; |
1023 | 1024 |
|
1024 | 1025 |
/// \brief \ref named-templ-param "Named parameter" for setting |
1025 | 1026 |
/// the distance map. |
1026 | 1027 |
/// |
1027 | 1028 |
/// \ref named-templ-param "Named parameter" for setting |
1028 | 1029 |
/// the map that stores the distances of the nodes calculated |
1029 | 1030 |
/// by the algorithm. |
1030 | 1031 |
template<class T> |
1031 | 1032 |
BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) { |
1032 | 1033 |
Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1033 | 1034 |
return BellmanFordWizard<SetDistMapBase<T> >(*this); |
1034 | 1035 |
} |
1035 | 1036 |
|
1036 | 1037 |
template<class T> |
1037 | 1038 |
struct SetPathBase : public Base { |
1038 | 1039 |
typedef T Path; |
1039 | 1040 |
SetPathBase(const TR &b) : TR(b) {} |
1040 | 1041 |
}; |
1041 | 1042 |
|
1042 | 1043 |
/// \brief \ref named-func-param "Named parameter" for getting |
1043 | 1044 |
/// the shortest path to the target node. |
1044 | 1045 |
/// |
1045 | 1046 |
/// \ref named-func-param "Named parameter" for getting |
1046 | 1047 |
/// the shortest path to the target node. |
1047 | 1048 |
template<class T> |
1048 | 1049 |
BellmanFordWizard<SetPathBase<T> > path(const T &t) |
1049 | 1050 |
{ |
1050 | 1051 |
Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1051 | 1052 |
return BellmanFordWizard<SetPathBase<T> >(*this); |
1052 | 1053 |
} |
1053 | 1054 |
|
1054 | 1055 |
/// \brief \ref named-func-param "Named parameter" for getting |
1055 | 1056 |
/// the distance of the target node. |
1056 | 1057 |
/// |
1057 | 1058 |
/// \ref named-func-param "Named parameter" for getting |
1058 | 1059 |
/// the distance of the target node. |
1059 | 1060 |
BellmanFordWizard dist(const Value &d) |
1060 | 1061 |
{ |
1061 | 1062 |
Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d)); |
1062 | 1063 |
return *this; |
1063 | 1064 |
} |
1064 | 1065 |
|
1065 | 1066 |
}; |
1066 | 1067 |
|
1067 | 1068 |
/// \brief Function type interface for the \ref BellmanFord "Bellman-Ford" |
1068 | 1069 |
/// algorithm. |
1069 | 1070 |
/// |
1070 | 1071 |
/// \ingroup shortest_path |
1071 | 1072 |
/// Function type interface for the \ref BellmanFord "Bellman-Ford" |
1072 | 1073 |
/// algorithm. |
1073 | 1074 |
/// |
1074 | 1075 |
/// This function also has several \ref named-templ-func-param |
1075 | 1076 |
/// "named parameters", they are declared as the members of class |
1076 | 1077 |
/// \ref BellmanFordWizard. |
1077 | 1078 |
/// The following examples show how to use these parameters. |
1078 | 1079 |
/// \code |
1079 | 1080 |
/// // Compute shortest path from node s to each node |
1080 | 1081 |
/// bellmanFord(g,length).predMap(preds).distMap(dists).run(s); |
1081 | 1082 |
/// |
1082 | 1083 |
/// // Compute shortest path from s to t |
1083 | 1084 |
/// bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t); |
1084 | 1085 |
/// \endcode |
1085 | 1086 |
/// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()" |
1086 | 1087 |
/// to the end of the parameter list. |
1087 | 1088 |
/// \sa BellmanFordWizard |
1088 | 1089 |
/// \sa BellmanFord |
1089 | 1090 |
template<typename GR, typename LEN> |
1090 | 1091 |
BellmanFordWizard<BellmanFordWizardBase<GR,LEN> > |
1091 | 1092 |
bellmanFord(const GR& digraph, |
1092 | 1093 |
const LEN& length) |
1093 | 1094 |
{ |
1094 | 1095 |
return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length); |
1095 | 1096 |
} |
1096 | 1097 |
|
1097 | 1098 |
} //END OF NAMESPACE LEMON |
1098 | 1099 |
|
1099 | 1100 |
#endif |
1100 | 1101 |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2009 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#include <lemon/concepts/digraph.h> |
20 | 20 |
#include <lemon/smart_graph.h> |
21 | 21 |
#include <lemon/list_graph.h> |
22 | 22 |
#include <lemon/lgf_reader.h> |
23 | 23 |
#include <lemon/bellman_ford.h> |
24 | 24 |
#include <lemon/path.h> |
25 | 25 |
|
26 | 26 |
#include "graph_test.h" |
27 | 27 |
#include "test_tools.h" |
28 | 28 |
|
29 | 29 |
using namespace lemon; |
30 | 30 |
|
31 | 31 |
char test_lgf[] = |
32 | 32 |
"@nodes\n" |
33 | 33 |
"label\n" |
34 | 34 |
"0\n" |
35 | 35 |
"1\n" |
36 | 36 |
"2\n" |
37 | 37 |
"3\n" |
38 | 38 |
"4\n" |
39 | 39 |
"@arcs\n" |
40 | 40 |
" length\n" |
41 | 41 |
"0 1 3\n" |
42 | 42 |
"1 2 -3\n" |
43 | 43 |
"1 2 -5\n" |
44 | 44 |
"1 3 -2\n" |
45 | 45 |
"0 2 -1\n" |
46 | 46 |
"1 2 -4\n" |
47 | 47 |
"0 3 2\n" |
48 | 48 |
"4 2 -5\n" |
49 | 49 |
"2 3 1\n" |
50 | 50 |
"@attributes\n" |
51 | 51 |
"source 0\n" |
52 | 52 |
"target 3\n"; |
53 | 53 |
|
54 | 54 |
|
55 | 55 |
void checkBellmanFordCompile() |
56 | 56 |
{ |
57 | 57 |
typedef int Value; |
58 | 58 |
typedef concepts::Digraph Digraph; |
59 | 59 |
typedef concepts::ReadMap<Digraph::Arc,Value> LengthMap; |
60 | 60 |
typedef BellmanFord<Digraph, LengthMap> BF; |
61 | 61 |
typedef Digraph::Node Node; |
62 | 62 |
typedef Digraph::Arc Arc; |
63 | 63 |
|
64 | 64 |
Digraph gr; |
65 | 65 |
Node s, t, n; |
66 | 66 |
Arc e; |
67 | 67 |
Value l; |
68 | 68 |
int k; |
69 | 69 |
bool b; |
70 | 70 |
BF::DistMap d(gr); |
71 | 71 |
BF::PredMap p(gr); |
72 | 72 |
LengthMap length; |
73 | 73 |
concepts::Path<Digraph> pp; |
74 | 74 |
|
75 | 75 |
{ |
76 | 76 |
BF bf_test(gr,length); |
77 | 77 |
const BF& const_bf_test = bf_test; |
78 | 78 |
|
79 | 79 |
bf_test.run(s); |
80 | 80 |
bf_test.run(s,k); |
81 | 81 |
|
82 | 82 |
bf_test.init(); |
83 | 83 |
bf_test.addSource(s); |
84 | 84 |
bf_test.addSource(s, 1); |
85 | 85 |
b = bf_test.processNextRound(); |
86 | 86 |
b = bf_test.processNextWeakRound(); |
87 | 87 |
|
88 | 88 |
bf_test.start(); |
89 | 89 |
bf_test.checkedStart(); |
90 | 90 |
bf_test.limitedStart(k); |
91 | 91 |
|
92 | 92 |
l = const_bf_test.dist(t); |
93 | 93 |
e = const_bf_test.predArc(t); |
94 | 94 |
s = const_bf_test.predNode(t); |
95 | 95 |
b = const_bf_test.reached(t); |
96 | 96 |
d = const_bf_test.distMap(); |
97 | 97 |
p = const_bf_test.predMap(); |
98 | 98 |
pp = const_bf_test.path(t); |
99 |
pp = const_bf_test.negativeCycle(); |
|
99 | 100 |
|
100 | 101 |
for (BF::ActiveIt it(const_bf_test); it != INVALID; ++it) {} |
101 | 102 |
} |
102 | 103 |
{ |
103 | 104 |
BF::SetPredMap<concepts::ReadWriteMap<Node,Arc> > |
104 | 105 |
::SetDistMap<concepts::ReadWriteMap<Node,Value> > |
105 | 106 |
::SetOperationTraits<BellmanFordDefaultOperationTraits<Value> > |
106 | 107 |
::Create bf_test(gr,length); |
107 | 108 |
|
108 | 109 |
LengthMap length_map; |
109 | 110 |
concepts::ReadWriteMap<Node,Arc> pred_map; |
110 | 111 |
concepts::ReadWriteMap<Node,Value> dist_map; |
111 | 112 |
|
112 | 113 |
bf_test |
113 | 114 |
.lengthMap(length_map) |
114 | 115 |
.predMap(pred_map) |
115 | 116 |
.distMap(dist_map); |
116 | 117 |
|
117 | 118 |
bf_test.run(s); |
118 | 119 |
bf_test.run(s,k); |
119 | 120 |
|
120 | 121 |
bf_test.init(); |
121 | 122 |
bf_test.addSource(s); |
122 | 123 |
bf_test.addSource(s, 1); |
123 | 124 |
b = bf_test.processNextRound(); |
124 | 125 |
b = bf_test.processNextWeakRound(); |
125 | 126 |
|
126 | 127 |
bf_test.start(); |
127 | 128 |
bf_test.checkedStart(); |
128 | 129 |
bf_test.limitedStart(k); |
129 | 130 |
|
130 | 131 |
l = bf_test.dist(t); |
131 | 132 |
e = bf_test.predArc(t); |
132 | 133 |
s = bf_test.predNode(t); |
133 | 134 |
b = bf_test.reached(t); |
134 | 135 |
pp = bf_test.path(t); |
136 |
pp = bf_test.negativeCycle(); |
|
135 | 137 |
} |
136 | 138 |
} |
137 | 139 |
|
138 | 140 |
void checkBellmanFordFunctionCompile() |
139 | 141 |
{ |
140 | 142 |
typedef int Value; |
141 | 143 |
typedef concepts::Digraph Digraph; |
142 | 144 |
typedef Digraph::Arc Arc; |
143 | 145 |
typedef Digraph::Node Node; |
144 | 146 |
typedef concepts::ReadMap<Digraph::Arc,Value> LengthMap; |
145 | 147 |
|
146 | 148 |
Digraph g; |
147 | 149 |
bool b; |
148 | 150 |
bellmanFord(g,LengthMap()).run(Node()); |
149 | 151 |
b = bellmanFord(g,LengthMap()).run(Node(),Node()); |
150 | 152 |
bellmanFord(g,LengthMap()) |
151 | 153 |
.predMap(concepts::ReadWriteMap<Node,Arc>()) |
152 | 154 |
.distMap(concepts::ReadWriteMap<Node,Value>()) |
153 | 155 |
.run(Node()); |
154 | 156 |
b=bellmanFord(g,LengthMap()) |
155 | 157 |
.predMap(concepts::ReadWriteMap<Node,Arc>()) |
156 | 158 |
.distMap(concepts::ReadWriteMap<Node,Value>()) |
157 | 159 |
.path(concepts::Path<Digraph>()) |
158 | 160 |
.dist(Value()) |
159 | 161 |
.run(Node(),Node()); |
160 | 162 |
} |
161 | 163 |
|
162 | 164 |
|
163 | 165 |
template <typename Digraph, typename Value> |
164 | 166 |
void checkBellmanFord() { |
165 | 167 |
TEMPLATE_DIGRAPH_TYPEDEFS(Digraph); |
166 | 168 |
typedef typename Digraph::template ArcMap<Value> LengthMap; |
167 | 169 |
|
168 | 170 |
Digraph gr; |
169 | 171 |
Node s, t; |
170 | 172 |
LengthMap length(gr); |
171 | 173 |
|
172 | 174 |
std::istringstream input(test_lgf); |
173 | 175 |
digraphReader(gr, input). |
174 | 176 |
arcMap("length", length). |
175 | 177 |
node("source", s). |
176 | 178 |
node("target", t). |
177 | 179 |
run(); |
178 | 180 |
|
179 | 181 |
BellmanFord<Digraph, LengthMap> |
180 | 182 |
bf(gr, length); |
181 | 183 |
bf.run(s); |
182 | 184 |
Path<Digraph> p = bf.path(t); |
183 | 185 |
|
184 | 186 |
check(bf.reached(t) && bf.dist(t) == -1, "Bellman-Ford found a wrong path."); |
185 | 187 |
check(p.length() == 3, "path() found a wrong path."); |
186 | 188 |
check(checkPath(gr, p), "path() found a wrong path."); |
187 | 189 |
check(pathSource(gr, p) == s, "path() found a wrong path."); |
188 | 190 |
check(pathTarget(gr, p) == t, "path() found a wrong path."); |
189 | 191 |
|
190 | 192 |
ListPath<Digraph> path; |
191 | 193 |
Value dist; |
192 | 194 |
bool reached = bellmanFord(gr,length).path(path).dist(dist).run(s,t); |
193 | 195 |
|
194 | 196 |
check(reached && dist == -1, "Bellman-Ford found a wrong path."); |
195 | 197 |
check(path.length() == 3, "path() found a wrong path."); |
196 | 198 |
check(checkPath(gr, path), "path() found a wrong path."); |
197 | 199 |
check(pathSource(gr, path) == s, "path() found a wrong path."); |
198 | 200 |
check(pathTarget(gr, path) == t, "path() found a wrong path."); |
199 | 201 |
|
200 | 202 |
for(ArcIt e(gr); e!=INVALID; ++e) { |
201 | 203 |
Node u=gr.source(e); |
202 | 204 |
Node v=gr.target(e); |
203 | 205 |
check(!bf.reached(u) || (bf.dist(v) - bf.dist(u) <= length[e]), |
204 | 206 |
"Wrong output. dist(target)-dist(source)-arc_length=" << |
205 | 207 |
bf.dist(v) - bf.dist(u) - length[e]); |
206 | 208 |
} |
207 | 209 |
|
208 | 210 |
for(NodeIt v(gr); v!=INVALID; ++v) { |
209 | 211 |
if (bf.reached(v)) { |
210 | 212 |
check(v==s || bf.predArc(v)!=INVALID, "Wrong tree."); |
211 | 213 |
if (bf.predArc(v)!=INVALID ) { |
212 | 214 |
Arc e=bf.predArc(v); |
213 | 215 |
Node u=gr.source(e); |
214 | 216 |
check(u==bf.predNode(v),"Wrong tree."); |
215 | 217 |
check(bf.dist(v) - bf.dist(u) == length[e], |
216 | 218 |
"Wrong distance! Difference: " << |
217 | 219 |
bf.dist(v) - bf.dist(u) - length[e]); |
218 | 220 |
} |
219 | 221 |
} |
220 | 222 |
} |
221 | 223 |
} |
222 | 224 |
|
223 | 225 |
void checkBellmanFordNegativeCycle() { |
224 | 226 |
DIGRAPH_TYPEDEFS(SmartDigraph); |
225 | 227 |
|
226 | 228 |
SmartDigraph gr; |
227 | 229 |
IntArcMap length(gr); |
228 | 230 |
|
229 | 231 |
Node n1 = gr.addNode(); |
230 | 232 |
Node n2 = gr.addNode(); |
231 | 233 |
Node n3 = gr.addNode(); |
232 | 234 |
Node n4 = gr.addNode(); |
233 | 235 |
|
234 | 236 |
Arc a1 = gr.addArc(n1, n2); |
235 | 237 |
Arc a2 = gr.addArc(n2, n2); |
236 | 238 |
|
237 | 239 |
length[a1] = 2; |
238 | 240 |
length[a2] = -1; |
239 | 241 |
|
240 | 242 |
{ |
241 | 243 |
BellmanFord<SmartDigraph, IntArcMap> bf(gr, length); |
242 | 244 |
bf.run(n1); |
243 | 245 |
StaticPath<SmartDigraph> p = bf.negativeCycle(); |
244 | 246 |
check(p.length() == 1 && p.front() == p.back() && p.front() == a2, |
245 | 247 |
"Wrong negative cycle."); |
246 | 248 |
} |
247 | 249 |
|
248 | 250 |
length[a2] = 0; |
249 | 251 |
|
250 | 252 |
{ |
251 | 253 |
BellmanFord<SmartDigraph, IntArcMap> bf(gr, length); |
252 | 254 |
bf.run(n1); |
253 | 255 |
check(bf.negativeCycle().empty(), |
254 | 256 |
"Negative cycle should not be found."); |
255 | 257 |
} |
256 | 258 |
|
257 | 259 |
length[gr.addArc(n1, n3)] = 5; |
258 | 260 |
length[gr.addArc(n4, n3)] = 1; |
259 | 261 |
length[gr.addArc(n2, n4)] = 2; |
260 | 262 |
length[gr.addArc(n3, n2)] = -4; |
261 | 263 |
|
262 | 264 |
{ |
263 | 265 |
BellmanFord<SmartDigraph, IntArcMap> bf(gr, length); |
264 | 266 |
bf.init(); |
265 | 267 |
bf.addSource(n1); |
266 | 268 |
for (int i = 0; i < 4; ++i) { |
267 | 269 |
check(bf.negativeCycle().empty(), |
268 | 270 |
"Negative cycle should not be found."); |
269 | 271 |
bf.processNextRound(); |
270 | 272 |
} |
271 | 273 |
StaticPath<SmartDigraph> p = bf.negativeCycle(); |
272 | 274 |
check(p.length() == 3, "Wrong negative cycle."); |
273 | 275 |
check(length[p.nth(0)] + length[p.nth(1)] + length[p.nth(2)] == -1, |
274 | 276 |
"Wrong negative cycle."); |
275 | 277 |
} |
276 | 278 |
} |
277 | 279 |
|
278 | 280 |
int main() { |
279 | 281 |
checkBellmanFord<ListDigraph, int>(); |
280 | 282 |
checkBellmanFord<SmartDigraph, double>(); |
281 | 283 |
checkBellmanFordNegativeCycle(); |
282 | 284 |
return 0; |
283 | 285 |
} |
0 comments (0 inline)