1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/lemon/bellman_ford.h Fri Sep 25 09:06:32 2009 +0200
1.3 @@ -0,0 +1,1100 @@
1.4 +/* -*- C++ -*-
1.5 + *
1.6 + * This file is a part of LEMON, a generic C++ optimization library
1.7 + *
1.8 + * Copyright (C) 2003-2008
1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
1.11 + *
1.12 + * Permission to use, modify and distribute this software is granted
1.13 + * provided that this copyright notice appears in all copies. For
1.14 + * precise terms see the accompanying LICENSE file.
1.15 + *
1.16 + * This software is provided "AS IS" with no warranty of any kind,
1.17 + * express or implied, and with no claim as to its suitability for any
1.18 + * purpose.
1.19 + *
1.20 + */
1.21 +
1.22 +#ifndef LEMON_BELLMAN_FORD_H
1.23 +#define LEMON_BELLMAN_FORD_H
1.24 +
1.25 +/// \ingroup shortest_path
1.26 +/// \file
1.27 +/// \brief Bellman-Ford algorithm.
1.28 +
1.29 +#include <lemon/bits/path_dump.h>
1.30 +#include <lemon/core.h>
1.31 +#include <lemon/error.h>
1.32 +#include <lemon/maps.h>
1.33 +#include <lemon/path.h>
1.34 +
1.35 +#include <limits>
1.36 +
1.37 +namespace lemon {
1.38 +
1.39 + /// \brief Default OperationTraits for the BellmanFord algorithm class.
1.40 + ///
1.41 + /// This operation traits class defines all computational operations
1.42 + /// and constants that are used in the Bellman-Ford algorithm.
1.43 + /// The default implementation is based on the \c numeric_limits class.
1.44 + /// If the numeric type does not have infinity value, then the maximum
1.45 + /// value is used as extremal infinity value.
1.46 + template <
1.47 + typename V,
1.48 + bool has_inf = std::numeric_limits<V>::has_infinity>
1.49 + struct BellmanFordDefaultOperationTraits {
1.50 + /// \e
1.51 + typedef V Value;
1.52 + /// \brief Gives back the zero value of the type.
1.53 + static Value zero() {
1.54 + return static_cast<Value>(0);
1.55 + }
1.56 + /// \brief Gives back the positive infinity value of the type.
1.57 + static Value infinity() {
1.58 + return std::numeric_limits<Value>::infinity();
1.59 + }
1.60 + /// \brief Gives back the sum of the given two elements.
1.61 + static Value plus(const Value& left, const Value& right) {
1.62 + return left + right;
1.63 + }
1.64 + /// \brief Gives back \c true only if the first value is less than
1.65 + /// the second.
1.66 + static bool less(const Value& left, const Value& right) {
1.67 + return left < right;
1.68 + }
1.69 + };
1.70 +
1.71 + template <typename V>
1.72 + struct BellmanFordDefaultOperationTraits<V, false> {
1.73 + typedef V Value;
1.74 + static Value zero() {
1.75 + return static_cast<Value>(0);
1.76 + }
1.77 + static Value infinity() {
1.78 + return std::numeric_limits<Value>::max();
1.79 + }
1.80 + static Value plus(const Value& left, const Value& right) {
1.81 + if (left == infinity() || right == infinity()) return infinity();
1.82 + return left + right;
1.83 + }
1.84 + static bool less(const Value& left, const Value& right) {
1.85 + return left < right;
1.86 + }
1.87 + };
1.88 +
1.89 + /// \brief Default traits class of BellmanFord class.
1.90 + ///
1.91 + /// Default traits class of BellmanFord class.
1.92 + /// \param GR The type of the digraph.
1.93 + /// \param LEN The type of the length map.
1.94 + template<typename GR, typename LEN>
1.95 + struct BellmanFordDefaultTraits {
1.96 + /// The type of the digraph the algorithm runs on.
1.97 + typedef GR Digraph;
1.98 +
1.99 + /// \brief The type of the map that stores the arc lengths.
1.100 + ///
1.101 + /// The type of the map that stores the arc lengths.
1.102 + /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
1.103 + typedef LEN LengthMap;
1.104 +
1.105 + /// The type of the arc lengths.
1.106 + typedef typename LEN::Value Value;
1.107 +
1.108 + /// \brief Operation traits for Bellman-Ford algorithm.
1.109 + ///
1.110 + /// It defines the used operations and the infinity value for the
1.111 + /// given \c Value type.
1.112 + /// \see BellmanFordDefaultOperationTraits
1.113 + typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
1.114 +
1.115 + /// \brief The type of the map that stores the last arcs of the
1.116 + /// shortest paths.
1.117 + ///
1.118 + /// The type of the map that stores the last
1.119 + /// arcs of the shortest paths.
1.120 + /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1.121 + typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
1.122 +
1.123 + /// \brief Instantiates a \c PredMap.
1.124 + ///
1.125 + /// This function instantiates a \ref PredMap.
1.126 + /// \param g is the digraph to which we would like to define the
1.127 + /// \ref PredMap.
1.128 + static PredMap *createPredMap(const GR& g) {
1.129 + return new PredMap(g);
1.130 + }
1.131 +
1.132 + /// \brief The type of the map that stores the distances of the nodes.
1.133 + ///
1.134 + /// The type of the map that stores the distances of the nodes.
1.135 + /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1.136 + typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
1.137 +
1.138 + /// \brief Instantiates a \c DistMap.
1.139 + ///
1.140 + /// This function instantiates a \ref DistMap.
1.141 + /// \param g is the digraph to which we would like to define the
1.142 + /// \ref DistMap.
1.143 + static DistMap *createDistMap(const GR& g) {
1.144 + return new DistMap(g);
1.145 + }
1.146 +
1.147 + };
1.148 +
1.149 + /// \brief %BellmanFord algorithm class.
1.150 + ///
1.151 + /// \ingroup shortest_path
1.152 + /// This class provides an efficient implementation of the Bellman-Ford
1.153 + /// algorithm. The maximum time complexity of the algorithm is
1.154 + /// <tt>O(ne)</tt>.
1.155 + ///
1.156 + /// The Bellman-Ford algorithm solves the single-source shortest path
1.157 + /// problem when the arcs can have negative lengths, but the digraph
1.158 + /// should not contain directed cycles with negative total length.
1.159 + /// If all arc costs are non-negative, consider to use the Dijkstra
1.160 + /// algorithm instead, since it is more efficient.
1.161 + ///
1.162 + /// The arc lengths are passed to the algorithm using a
1.163 + /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
1.164 + /// kind of length. The type of the length values is determined by the
1.165 + /// \ref concepts::ReadMap::Value "Value" type of the length map.
1.166 + ///
1.167 + /// There is also a \ref bellmanFord() "function-type interface" for the
1.168 + /// Bellman-Ford algorithm, which is convenient in the simplier cases and
1.169 + /// it can be used easier.
1.170 + ///
1.171 + /// \tparam GR The type of the digraph the algorithm runs on.
1.172 + /// The default type is \ref ListDigraph.
1.173 + /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
1.174 + /// the lengths of the arcs. The default map type is
1.175 + /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
1.176 +#ifdef DOXYGEN
1.177 + template <typename GR, typename LEN, typename TR>
1.178 +#else
1.179 + template <typename GR=ListDigraph,
1.180 + typename LEN=typename GR::template ArcMap<int>,
1.181 + typename TR=BellmanFordDefaultTraits<GR,LEN> >
1.182 +#endif
1.183 + class BellmanFord {
1.184 + public:
1.185 +
1.186 + ///The type of the underlying digraph.
1.187 + typedef typename TR::Digraph Digraph;
1.188 +
1.189 + /// \brief The type of the arc lengths.
1.190 + typedef typename TR::LengthMap::Value Value;
1.191 + /// \brief The type of the map that stores the arc lengths.
1.192 + typedef typename TR::LengthMap LengthMap;
1.193 + /// \brief The type of the map that stores the last
1.194 + /// arcs of the shortest paths.
1.195 + typedef typename TR::PredMap PredMap;
1.196 + /// \brief The type of the map that stores the distances of the nodes.
1.197 + typedef typename TR::DistMap DistMap;
1.198 + /// The type of the paths.
1.199 + typedef PredMapPath<Digraph, PredMap> Path;
1.200 + ///\brief The \ref BellmanFordDefaultOperationTraits
1.201 + /// "operation traits class" of the algorithm.
1.202 + typedef typename TR::OperationTraits OperationTraits;
1.203 +
1.204 + ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
1.205 + typedef TR Traits;
1.206 +
1.207 + private:
1.208 +
1.209 + typedef typename Digraph::Node Node;
1.210 + typedef typename Digraph::NodeIt NodeIt;
1.211 + typedef typename Digraph::Arc Arc;
1.212 + typedef typename Digraph::OutArcIt OutArcIt;
1.213 +
1.214 + // Pointer to the underlying digraph.
1.215 + const Digraph *_gr;
1.216 + // Pointer to the length map
1.217 + const LengthMap *_length;
1.218 + // Pointer to the map of predecessors arcs.
1.219 + PredMap *_pred;
1.220 + // Indicates if _pred is locally allocated (true) or not.
1.221 + bool _local_pred;
1.222 + // Pointer to the map of distances.
1.223 + DistMap *_dist;
1.224 + // Indicates if _dist is locally allocated (true) or not.
1.225 + bool _local_dist;
1.226 +
1.227 + typedef typename Digraph::template NodeMap<bool> MaskMap;
1.228 + MaskMap *_mask;
1.229 +
1.230 + std::vector<Node> _process;
1.231 +
1.232 + // Creates the maps if necessary.
1.233 + void create_maps() {
1.234 + if(!_pred) {
1.235 + _local_pred = true;
1.236 + _pred = Traits::createPredMap(*_gr);
1.237 + }
1.238 + if(!_dist) {
1.239 + _local_dist = true;
1.240 + _dist = Traits::createDistMap(*_gr);
1.241 + }
1.242 + _mask = new MaskMap(*_gr, false);
1.243 + }
1.244 +
1.245 + public :
1.246 +
1.247 + typedef BellmanFord Create;
1.248 +
1.249 + /// \name Named Template Parameters
1.250 +
1.251 + ///@{
1.252 +
1.253 + template <class T>
1.254 + struct SetPredMapTraits : public Traits {
1.255 + typedef T PredMap;
1.256 + static PredMap *createPredMap(const Digraph&) {
1.257 + LEMON_ASSERT(false, "PredMap is not initialized");
1.258 + return 0; // ignore warnings
1.259 + }
1.260 + };
1.261 +
1.262 + /// \brief \ref named-templ-param "Named parameter" for setting
1.263 + /// \c PredMap type.
1.264 + ///
1.265 + /// \ref named-templ-param "Named parameter" for setting
1.266 + /// \c PredMap type.
1.267 + /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1.268 + template <class T>
1.269 + struct SetPredMap
1.270 + : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
1.271 + typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
1.272 + };
1.273 +
1.274 + template <class T>
1.275 + struct SetDistMapTraits : public Traits {
1.276 + typedef T DistMap;
1.277 + static DistMap *createDistMap(const Digraph&) {
1.278 + LEMON_ASSERT(false, "DistMap is not initialized");
1.279 + return 0; // ignore warnings
1.280 + }
1.281 + };
1.282 +
1.283 + /// \brief \ref named-templ-param "Named parameter" for setting
1.284 + /// \c DistMap type.
1.285 + ///
1.286 + /// \ref named-templ-param "Named parameter" for setting
1.287 + /// \c DistMap type.
1.288 + /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1.289 + template <class T>
1.290 + struct SetDistMap
1.291 + : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
1.292 + typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
1.293 + };
1.294 +
1.295 + template <class T>
1.296 + struct SetOperationTraitsTraits : public Traits {
1.297 + typedef T OperationTraits;
1.298 + };
1.299 +
1.300 + /// \brief \ref named-templ-param "Named parameter" for setting
1.301 + /// \c OperationTraits type.
1.302 + ///
1.303 + /// \ref named-templ-param "Named parameter" for setting
1.304 + /// \c OperationTraits type.
1.305 + /// For more information see \ref BellmanFordDefaultOperationTraits.
1.306 + template <class T>
1.307 + struct SetOperationTraits
1.308 + : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
1.309 + typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
1.310 + Create;
1.311 + };
1.312 +
1.313 + ///@}
1.314 +
1.315 + protected:
1.316 +
1.317 + BellmanFord() {}
1.318 +
1.319 + public:
1.320 +
1.321 + /// \brief Constructor.
1.322 + ///
1.323 + /// Constructor.
1.324 + /// \param g The digraph the algorithm runs on.
1.325 + /// \param length The length map used by the algorithm.
1.326 + BellmanFord(const Digraph& g, const LengthMap& length) :
1.327 + _gr(&g), _length(&length),
1.328 + _pred(0), _local_pred(false),
1.329 + _dist(0), _local_dist(false), _mask(0) {}
1.330 +
1.331 + ///Destructor.
1.332 + ~BellmanFord() {
1.333 + if(_local_pred) delete _pred;
1.334 + if(_local_dist) delete _dist;
1.335 + if(_mask) delete _mask;
1.336 + }
1.337 +
1.338 + /// \brief Sets the length map.
1.339 + ///
1.340 + /// Sets the length map.
1.341 + /// \return <tt>(*this)</tt>
1.342 + BellmanFord &lengthMap(const LengthMap &map) {
1.343 + _length = ↦
1.344 + return *this;
1.345 + }
1.346 +
1.347 + /// \brief Sets the map that stores the predecessor arcs.
1.348 + ///
1.349 + /// Sets the map that stores the predecessor arcs.
1.350 + /// If you don't use this function before calling \ref run()
1.351 + /// or \ref init(), an instance will be allocated automatically.
1.352 + /// The destructor deallocates this automatically allocated map,
1.353 + /// of course.
1.354 + /// \return <tt>(*this)</tt>
1.355 + BellmanFord &predMap(PredMap &map) {
1.356 + if(_local_pred) {
1.357 + delete _pred;
1.358 + _local_pred=false;
1.359 + }
1.360 + _pred = ↦
1.361 + return *this;
1.362 + }
1.363 +
1.364 + /// \brief Sets the map that stores the distances of the nodes.
1.365 + ///
1.366 + /// Sets the map that stores the distances of the nodes calculated
1.367 + /// by the algorithm.
1.368 + /// If you don't use this function before calling \ref run()
1.369 + /// or \ref init(), an instance will be allocated automatically.
1.370 + /// The destructor deallocates this automatically allocated map,
1.371 + /// of course.
1.372 + /// \return <tt>(*this)</tt>
1.373 + BellmanFord &distMap(DistMap &map) {
1.374 + if(_local_dist) {
1.375 + delete _dist;
1.376 + _local_dist=false;
1.377 + }
1.378 + _dist = ↦
1.379 + return *this;
1.380 + }
1.381 +
1.382 + /// \name Execution Control
1.383 + /// The simplest way to execute the Bellman-Ford algorithm is to use
1.384 + /// one of the member functions called \ref run().\n
1.385 + /// If you need better control on the execution, you have to call
1.386 + /// \ref init() first, then you can add several source nodes
1.387 + /// with \ref addSource(). Finally the actual path computation can be
1.388 + /// performed with \ref start(), \ref checkedStart() or
1.389 + /// \ref limitedStart().
1.390 +
1.391 + ///@{
1.392 +
1.393 + /// \brief Initializes the internal data structures.
1.394 + ///
1.395 + /// Initializes the internal data structures. The optional parameter
1.396 + /// is the initial distance of each node.
1.397 + void init(const Value value = OperationTraits::infinity()) {
1.398 + create_maps();
1.399 + for (NodeIt it(*_gr); it != INVALID; ++it) {
1.400 + _pred->set(it, INVALID);
1.401 + _dist->set(it, value);
1.402 + }
1.403 + _process.clear();
1.404 + if (OperationTraits::less(value, OperationTraits::infinity())) {
1.405 + for (NodeIt it(*_gr); it != INVALID; ++it) {
1.406 + _process.push_back(it);
1.407 + _mask->set(it, true);
1.408 + }
1.409 + }
1.410 + }
1.411 +
1.412 + /// \brief Adds a new source node.
1.413 + ///
1.414 + /// This function adds a new source node. The optional second parameter
1.415 + /// is the initial distance of the node.
1.416 + void addSource(Node source, Value dst = OperationTraits::zero()) {
1.417 + _dist->set(source, dst);
1.418 + if (!(*_mask)[source]) {
1.419 + _process.push_back(source);
1.420 + _mask->set(source, true);
1.421 + }
1.422 + }
1.423 +
1.424 + /// \brief Executes one round from the Bellman-Ford algorithm.
1.425 + ///
1.426 + /// If the algoritm calculated the distances in the previous round
1.427 + /// exactly for the paths of at most \c k arcs, then this function
1.428 + /// will calculate the distances exactly for the paths of at most
1.429 + /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
1.430 + /// calculates the shortest path distances exactly for the paths
1.431 + /// consisting of at most \c k arcs.
1.432 + ///
1.433 + /// \warning The paths with limited arc number cannot be retrieved
1.434 + /// easily with \ref path() or \ref predArc() functions. If you also
1.435 + /// need the shortest paths and not only the distances, you should
1.436 + /// store the \ref predMap() "predecessor map" after each iteration
1.437 + /// and build the path manually.
1.438 + ///
1.439 + /// \return \c true when the algorithm have not found more shorter
1.440 + /// paths.
1.441 + ///
1.442 + /// \see ActiveIt
1.443 + bool processNextRound() {
1.444 + for (int i = 0; i < int(_process.size()); ++i) {
1.445 + _mask->set(_process[i], false);
1.446 + }
1.447 + std::vector<Node> nextProcess;
1.448 + std::vector<Value> values(_process.size());
1.449 + for (int i = 0; i < int(_process.size()); ++i) {
1.450 + values[i] = (*_dist)[_process[i]];
1.451 + }
1.452 + for (int i = 0; i < int(_process.size()); ++i) {
1.453 + for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
1.454 + Node target = _gr->target(it);
1.455 + Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
1.456 + if (OperationTraits::less(relaxed, (*_dist)[target])) {
1.457 + _pred->set(target, it);
1.458 + _dist->set(target, relaxed);
1.459 + if (!(*_mask)[target]) {
1.460 + _mask->set(target, true);
1.461 + nextProcess.push_back(target);
1.462 + }
1.463 + }
1.464 + }
1.465 + }
1.466 + _process.swap(nextProcess);
1.467 + return _process.empty();
1.468 + }
1.469 +
1.470 + /// \brief Executes one weak round from the Bellman-Ford algorithm.
1.471 + ///
1.472 + /// If the algorithm calculated the distances in the previous round
1.473 + /// at least for the paths of at most \c k arcs, then this function
1.474 + /// will calculate the distances at least for the paths of at most
1.475 + /// <tt>k+1</tt> arcs.
1.476 + /// This function does not make it possible to calculate the shortest
1.477 + /// path distances exactly for paths consisting of at most \c k arcs,
1.478 + /// this is why it is called weak round.
1.479 + ///
1.480 + /// \return \c true when the algorithm have not found more shorter
1.481 + /// paths.
1.482 + ///
1.483 + /// \see ActiveIt
1.484 + bool processNextWeakRound() {
1.485 + for (int i = 0; i < int(_process.size()); ++i) {
1.486 + _mask->set(_process[i], false);
1.487 + }
1.488 + std::vector<Node> nextProcess;
1.489 + for (int i = 0; i < int(_process.size()); ++i) {
1.490 + for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
1.491 + Node target = _gr->target(it);
1.492 + Value relaxed =
1.493 + OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
1.494 + if (OperationTraits::less(relaxed, (*_dist)[target])) {
1.495 + _pred->set(target, it);
1.496 + _dist->set(target, relaxed);
1.497 + if (!(*_mask)[target]) {
1.498 + _mask->set(target, true);
1.499 + nextProcess.push_back(target);
1.500 + }
1.501 + }
1.502 + }
1.503 + }
1.504 + _process.swap(nextProcess);
1.505 + return _process.empty();
1.506 + }
1.507 +
1.508 + /// \brief Executes the algorithm.
1.509 + ///
1.510 + /// Executes the algorithm.
1.511 + ///
1.512 + /// This method runs the Bellman-Ford algorithm from the root node(s)
1.513 + /// in order to compute the shortest path to each node.
1.514 + ///
1.515 + /// The algorithm computes
1.516 + /// - the shortest path tree (forest),
1.517 + /// - the distance of each node from the root(s).
1.518 + ///
1.519 + /// \pre init() must be called and at least one root node should be
1.520 + /// added with addSource() before using this function.
1.521 + void start() {
1.522 + int num = countNodes(*_gr) - 1;
1.523 + for (int i = 0; i < num; ++i) {
1.524 + if (processNextWeakRound()) break;
1.525 + }
1.526 + }
1.527 +
1.528 + /// \brief Executes the algorithm and checks the negative cycles.
1.529 + ///
1.530 + /// Executes the algorithm and checks the negative cycles.
1.531 + ///
1.532 + /// This method runs the Bellman-Ford algorithm from the root node(s)
1.533 + /// in order to compute the shortest path to each node and also checks
1.534 + /// if the digraph contains cycles with negative total length.
1.535 + ///
1.536 + /// The algorithm computes
1.537 + /// - the shortest path tree (forest),
1.538 + /// - the distance of each node from the root(s).
1.539 + ///
1.540 + /// \return \c false if there is a negative cycle in the digraph.
1.541 + ///
1.542 + /// \pre init() must be called and at least one root node should be
1.543 + /// added with addSource() before using this function.
1.544 + bool checkedStart() {
1.545 + int num = countNodes(*_gr);
1.546 + for (int i = 0; i < num; ++i) {
1.547 + if (processNextWeakRound()) return true;
1.548 + }
1.549 + return _process.empty();
1.550 + }
1.551 +
1.552 + /// \brief Executes the algorithm with arc number limit.
1.553 + ///
1.554 + /// Executes the algorithm with arc number limit.
1.555 + ///
1.556 + /// This method runs the Bellman-Ford algorithm from the root node(s)
1.557 + /// in order to compute the shortest path distance for each node
1.558 + /// using only the paths consisting of at most \c num arcs.
1.559 + ///
1.560 + /// The algorithm computes
1.561 + /// - the limited distance of each node from the root(s),
1.562 + /// - the predecessor arc for each node.
1.563 + ///
1.564 + /// \warning The paths with limited arc number cannot be retrieved
1.565 + /// easily with \ref path() or \ref predArc() functions. If you also
1.566 + /// need the shortest paths and not only the distances, you should
1.567 + /// store the \ref predMap() "predecessor map" after each iteration
1.568 + /// and build the path manually.
1.569 + ///
1.570 + /// \pre init() must be called and at least one root node should be
1.571 + /// added with addSource() before using this function.
1.572 + void limitedStart(int num) {
1.573 + for (int i = 0; i < num; ++i) {
1.574 + if (processNextRound()) break;
1.575 + }
1.576 + }
1.577 +
1.578 + /// \brief Runs the algorithm from the given root node.
1.579 + ///
1.580 + /// This method runs the Bellman-Ford algorithm from the given root
1.581 + /// node \c s in order to compute the shortest path to each node.
1.582 + ///
1.583 + /// The algorithm computes
1.584 + /// - the shortest path tree (forest),
1.585 + /// - the distance of each node from the root(s).
1.586 + ///
1.587 + /// \note bf.run(s) is just a shortcut of the following code.
1.588 + /// \code
1.589 + /// bf.init();
1.590 + /// bf.addSource(s);
1.591 + /// bf.start();
1.592 + /// \endcode
1.593 + void run(Node s) {
1.594 + init();
1.595 + addSource(s);
1.596 + start();
1.597 + }
1.598 +
1.599 + /// \brief Runs the algorithm from the given root node with arc
1.600 + /// number limit.
1.601 + ///
1.602 + /// This method runs the Bellman-Ford algorithm from the given root
1.603 + /// node \c s in order to compute the shortest path distance for each
1.604 + /// node using only the paths consisting of at most \c num arcs.
1.605 + ///
1.606 + /// The algorithm computes
1.607 + /// - the limited distance of each node from the root(s),
1.608 + /// - the predecessor arc for each node.
1.609 + ///
1.610 + /// \warning The paths with limited arc number cannot be retrieved
1.611 + /// easily with \ref path() or \ref predArc() functions. If you also
1.612 + /// need the shortest paths and not only the distances, you should
1.613 + /// store the \ref predMap() "predecessor map" after each iteration
1.614 + /// and build the path manually.
1.615 + ///
1.616 + /// \note bf.run(s, num) is just a shortcut of the following code.
1.617 + /// \code
1.618 + /// bf.init();
1.619 + /// bf.addSource(s);
1.620 + /// bf.limitedStart(num);
1.621 + /// \endcode
1.622 + void run(Node s, int num) {
1.623 + init();
1.624 + addSource(s);
1.625 + limitedStart(num);
1.626 + }
1.627 +
1.628 + ///@}
1.629 +
1.630 + /// \brief LEMON iterator for getting the active nodes.
1.631 + ///
1.632 + /// This class provides a common style LEMON iterator that traverses
1.633 + /// the active nodes of the Bellman-Ford algorithm after the last
1.634 + /// phase. These nodes should be checked in the next phase to
1.635 + /// find augmenting arcs outgoing from them.
1.636 + class ActiveIt {
1.637 + public:
1.638 +
1.639 + /// \brief Constructor.
1.640 + ///
1.641 + /// Constructor for getting the active nodes of the given BellmanFord
1.642 + /// instance.
1.643 + ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
1.644 + {
1.645 + _index = _algorithm->_process.size() - 1;
1.646 + }
1.647 +
1.648 + /// \brief Invalid constructor.
1.649 + ///
1.650 + /// Invalid constructor.
1.651 + ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
1.652 +
1.653 + /// \brief Conversion to \c Node.
1.654 + ///
1.655 + /// Conversion to \c Node.
1.656 + operator Node() const {
1.657 + return _index >= 0 ? _algorithm->_process[_index] : INVALID;
1.658 + }
1.659 +
1.660 + /// \brief Increment operator.
1.661 + ///
1.662 + /// Increment operator.
1.663 + ActiveIt& operator++() {
1.664 + --_index;
1.665 + return *this;
1.666 + }
1.667 +
1.668 + bool operator==(const ActiveIt& it) const {
1.669 + return static_cast<Node>(*this) == static_cast<Node>(it);
1.670 + }
1.671 + bool operator!=(const ActiveIt& it) const {
1.672 + return static_cast<Node>(*this) != static_cast<Node>(it);
1.673 + }
1.674 + bool operator<(const ActiveIt& it) const {
1.675 + return static_cast<Node>(*this) < static_cast<Node>(it);
1.676 + }
1.677 +
1.678 + private:
1.679 + const BellmanFord* _algorithm;
1.680 + int _index;
1.681 + };
1.682 +
1.683 + /// \name Query Functions
1.684 + /// The result of the Bellman-Ford algorithm can be obtained using these
1.685 + /// functions.\n
1.686 + /// Either \ref run() or \ref init() should be called before using them.
1.687 +
1.688 + ///@{
1.689 +
1.690 + /// \brief The shortest path to the given node.
1.691 + ///
1.692 + /// Gives back the shortest path to the given node from the root(s).
1.693 + ///
1.694 + /// \warning \c t should be reached from the root(s).
1.695 + ///
1.696 + /// \pre Either \ref run() or \ref init() must be called before
1.697 + /// using this function.
1.698 + Path path(Node t) const
1.699 + {
1.700 + return Path(*_gr, *_pred, t);
1.701 + }
1.702 +
1.703 + /// \brief The distance of the given node from the root(s).
1.704 + ///
1.705 + /// Returns the distance of the given node from the root(s).
1.706 + ///
1.707 + /// \warning If node \c v is not reached from the root(s), then
1.708 + /// the return value of this function is undefined.
1.709 + ///
1.710 + /// \pre Either \ref run() or \ref init() must be called before
1.711 + /// using this function.
1.712 + Value dist(Node v) const { return (*_dist)[v]; }
1.713 +
1.714 + /// \brief Returns the 'previous arc' of the shortest path tree for
1.715 + /// the given node.
1.716 + ///
1.717 + /// This function returns the 'previous arc' of the shortest path
1.718 + /// tree for node \c v, i.e. it returns the last arc of a
1.719 + /// shortest path from a root to \c v. It is \c INVALID if \c v
1.720 + /// is not reached from the root(s) or if \c v is a root.
1.721 + ///
1.722 + /// The shortest path tree used here is equal to the shortest path
1.723 + /// tree used in \ref predNode() and \predMap().
1.724 + ///
1.725 + /// \pre Either \ref run() or \ref init() must be called before
1.726 + /// using this function.
1.727 + Arc predArc(Node v) const { return (*_pred)[v]; }
1.728 +
1.729 + /// \brief Returns the 'previous node' of the shortest path tree for
1.730 + /// the given node.
1.731 + ///
1.732 + /// This function returns the 'previous node' of the shortest path
1.733 + /// tree for node \c v, i.e. it returns the last but one node of
1.734 + /// a shortest path from a root to \c v. It is \c INVALID if \c v
1.735 + /// is not reached from the root(s) or if \c v is a root.
1.736 + ///
1.737 + /// The shortest path tree used here is equal to the shortest path
1.738 + /// tree used in \ref predArc() and \predMap().
1.739 + ///
1.740 + /// \pre Either \ref run() or \ref init() must be called before
1.741 + /// using this function.
1.742 + Node predNode(Node v) const {
1.743 + return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
1.744 + }
1.745 +
1.746 + /// \brief Returns a const reference to the node map that stores the
1.747 + /// distances of the nodes.
1.748 + ///
1.749 + /// Returns a const reference to the node map that stores the distances
1.750 + /// of the nodes calculated by the algorithm.
1.751 + ///
1.752 + /// \pre Either \ref run() or \ref init() must be called before
1.753 + /// using this function.
1.754 + const DistMap &distMap() const { return *_dist;}
1.755 +
1.756 + /// \brief Returns a const reference to the node map that stores the
1.757 + /// predecessor arcs.
1.758 + ///
1.759 + /// Returns a const reference to the node map that stores the predecessor
1.760 + /// arcs, which form the shortest path tree (forest).
1.761 + ///
1.762 + /// \pre Either \ref run() or \ref init() must be called before
1.763 + /// using this function.
1.764 + const PredMap &predMap() const { return *_pred; }
1.765 +
1.766 + /// \brief Checks if a node is reached from the root(s).
1.767 + ///
1.768 + /// Returns \c true if \c v is reached from the root(s).
1.769 + ///
1.770 + /// \pre Either \ref run() or \ref init() must be called before
1.771 + /// using this function.
1.772 + bool reached(Node v) const {
1.773 + return (*_dist)[v] != OperationTraits::infinity();
1.774 + }
1.775 +
1.776 + /// \brief Gives back a negative cycle.
1.777 + ///
1.778 + /// This function gives back a directed cycle with negative total
1.779 + /// length if the algorithm has already found one.
1.780 + /// Otherwise it gives back an empty path.
1.781 + lemon::Path<Digraph> negativeCycle() {
1.782 + typename Digraph::template NodeMap<int> state(*_gr, -1);
1.783 + lemon::Path<Digraph> cycle;
1.784 + for (int i = 0; i < int(_process.size()); ++i) {
1.785 + if (state[_process[i]] != -1) continue;
1.786 + for (Node v = _process[i]; (*_pred)[v] != INVALID;
1.787 + v = _gr->source((*_pred)[v])) {
1.788 + if (state[v] == i) {
1.789 + cycle.addFront((*_pred)[v]);
1.790 + for (Node u = _gr->source((*_pred)[v]); u != v;
1.791 + u = _gr->source((*_pred)[u])) {
1.792 + cycle.addFront((*_pred)[u]);
1.793 + }
1.794 + return cycle;
1.795 + }
1.796 + else if (state[v] >= 0) {
1.797 + break;
1.798 + }
1.799 + state[v] = i;
1.800 + }
1.801 + }
1.802 + return cycle;
1.803 + }
1.804 +
1.805 + ///@}
1.806 + };
1.807 +
1.808 + /// \brief Default traits class of bellmanFord() function.
1.809 + ///
1.810 + /// Default traits class of bellmanFord() function.
1.811 + /// \tparam GR The type of the digraph.
1.812 + /// \tparam LEN The type of the length map.
1.813 + template <typename GR, typename LEN>
1.814 + struct BellmanFordWizardDefaultTraits {
1.815 + /// The type of the digraph the algorithm runs on.
1.816 + typedef GR Digraph;
1.817 +
1.818 + /// \brief The type of the map that stores the arc lengths.
1.819 + ///
1.820 + /// The type of the map that stores the arc lengths.
1.821 + /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
1.822 + typedef LEN LengthMap;
1.823 +
1.824 + /// The type of the arc lengths.
1.825 + typedef typename LEN::Value Value;
1.826 +
1.827 + /// \brief Operation traits for Bellman-Ford algorithm.
1.828 + ///
1.829 + /// It defines the used operations and the infinity value for the
1.830 + /// given \c Value type.
1.831 + /// \see BellmanFordDefaultOperationTraits
1.832 + typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
1.833 +
1.834 + /// \brief The type of the map that stores the last
1.835 + /// arcs of the shortest paths.
1.836 + ///
1.837 + /// The type of the map that stores the last arcs of the shortest paths.
1.838 + /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1.839 + typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
1.840 +
1.841 + /// \brief Instantiates a \c PredMap.
1.842 + ///
1.843 + /// This function instantiates a \ref PredMap.
1.844 + /// \param g is the digraph to which we would like to define the
1.845 + /// \ref PredMap.
1.846 + static PredMap *createPredMap(const GR &g) {
1.847 + return new PredMap(g);
1.848 + }
1.849 +
1.850 + /// \brief The type of the map that stores the distances of the nodes.
1.851 + ///
1.852 + /// The type of the map that stores the distances of the nodes.
1.853 + /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
1.854 + typedef typename GR::template NodeMap<Value> DistMap;
1.855 +
1.856 + /// \brief Instantiates a \c DistMap.
1.857 + ///
1.858 + /// This function instantiates a \ref DistMap.
1.859 + /// \param g is the digraph to which we would like to define the
1.860 + /// \ref DistMap.
1.861 + static DistMap *createDistMap(const GR &g) {
1.862 + return new DistMap(g);
1.863 + }
1.864 +
1.865 + ///The type of the shortest paths.
1.866 +
1.867 + ///The type of the shortest paths.
1.868 + ///It must meet the \ref concepts::Path "Path" concept.
1.869 + typedef lemon::Path<Digraph> Path;
1.870 + };
1.871 +
1.872 + /// \brief Default traits class used by BellmanFordWizard.
1.873 + ///
1.874 + /// Default traits class used by BellmanFordWizard.
1.875 + /// \tparam GR The type of the digraph.
1.876 + /// \tparam LEN The type of the length map.
1.877 + template <typename GR, typename LEN>
1.878 + class BellmanFordWizardBase
1.879 + : public BellmanFordWizardDefaultTraits<GR, LEN> {
1.880 +
1.881 + typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
1.882 + protected:
1.883 + // Type of the nodes in the digraph.
1.884 + typedef typename Base::Digraph::Node Node;
1.885 +
1.886 + // Pointer to the underlying digraph.
1.887 + void *_graph;
1.888 + // Pointer to the length map
1.889 + void *_length;
1.890 + // Pointer to the map of predecessors arcs.
1.891 + void *_pred;
1.892 + // Pointer to the map of distances.
1.893 + void *_dist;
1.894 + //Pointer to the shortest path to the target node.
1.895 + void *_path;
1.896 + //Pointer to the distance of the target node.
1.897 + void *_di;
1.898 +
1.899 + public:
1.900 + /// Constructor.
1.901 +
1.902 + /// This constructor does not require parameters, it initiates
1.903 + /// all of the attributes to default values \c 0.
1.904 + BellmanFordWizardBase() :
1.905 + _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
1.906 +
1.907 + /// Constructor.
1.908 +
1.909 + /// This constructor requires two parameters,
1.910 + /// others are initiated to \c 0.
1.911 + /// \param gr The digraph the algorithm runs on.
1.912 + /// \param len The length map.
1.913 + BellmanFordWizardBase(const GR& gr,
1.914 + const LEN& len) :
1.915 + _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
1.916 + _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
1.917 + _pred(0), _dist(0), _path(0), _di(0) {}
1.918 +
1.919 + };
1.920 +
1.921 + /// \brief Auxiliary class for the function-type interface of the
1.922 + /// \ref BellmanFord "Bellman-Ford" algorithm.
1.923 + ///
1.924 + /// This auxiliary class is created to implement the
1.925 + /// \ref bellmanFord() "function-type interface" of the
1.926 + /// \ref BellmanFord "Bellman-Ford" algorithm.
1.927 + /// It does not have own \ref run() method, it uses the
1.928 + /// functions and features of the plain \ref BellmanFord.
1.929 + ///
1.930 + /// This class should only be used through the \ref bellmanFord()
1.931 + /// function, which makes it easier to use the algorithm.
1.932 + template<class TR>
1.933 + class BellmanFordWizard : public TR {
1.934 + typedef TR Base;
1.935 +
1.936 + typedef typename TR::Digraph Digraph;
1.937 +
1.938 + typedef typename Digraph::Node Node;
1.939 + typedef typename Digraph::NodeIt NodeIt;
1.940 + typedef typename Digraph::Arc Arc;
1.941 + typedef typename Digraph::OutArcIt ArcIt;
1.942 +
1.943 + typedef typename TR::LengthMap LengthMap;
1.944 + typedef typename LengthMap::Value Value;
1.945 + typedef typename TR::PredMap PredMap;
1.946 + typedef typename TR::DistMap DistMap;
1.947 + typedef typename TR::Path Path;
1.948 +
1.949 + public:
1.950 + /// Constructor.
1.951 + BellmanFordWizard() : TR() {}
1.952 +
1.953 + /// \brief Constructor that requires parameters.
1.954 + ///
1.955 + /// Constructor that requires parameters.
1.956 + /// These parameters will be the default values for the traits class.
1.957 + /// \param gr The digraph the algorithm runs on.
1.958 + /// \param len The length map.
1.959 + BellmanFordWizard(const Digraph& gr, const LengthMap& len)
1.960 + : TR(gr, len) {}
1.961 +
1.962 + /// \brief Copy constructor
1.963 + BellmanFordWizard(const TR &b) : TR(b) {}
1.964 +
1.965 + ~BellmanFordWizard() {}
1.966 +
1.967 + /// \brief Runs the Bellman-Ford algorithm from the given source node.
1.968 + ///
1.969 + /// This method runs the Bellman-Ford algorithm from the given source
1.970 + /// node in order to compute the shortest path to each node.
1.971 + void run(Node s) {
1.972 + BellmanFord<Digraph,LengthMap,TR>
1.973 + bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1.974 + *reinterpret_cast<const LengthMap*>(Base::_length));
1.975 + if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1.976 + if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1.977 + bf.run(s);
1.978 + }
1.979 +
1.980 + /// \brief Runs the Bellman-Ford algorithm to find the shortest path
1.981 + /// between \c s and \c t.
1.982 + ///
1.983 + /// This method runs the Bellman-Ford algorithm from node \c s
1.984 + /// in order to compute the shortest path to node \c t.
1.985 + /// Actually, it computes the shortest path to each node, but using
1.986 + /// this function you can retrieve the distance and the shortest path
1.987 + /// for a single target node easier.
1.988 + ///
1.989 + /// \return \c true if \c t is reachable form \c s.
1.990 + bool run(Node s, Node t) {
1.991 + BellmanFord<Digraph,LengthMap,TR>
1.992 + bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1.993 + *reinterpret_cast<const LengthMap*>(Base::_length));
1.994 + if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1.995 + if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1.996 + bf.run(s);
1.997 + if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1.998 + if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1.999 + return bf.reached(t);
1.1000 + }
1.1001 +
1.1002 + template<class T>
1.1003 + struct SetPredMapBase : public Base {
1.1004 + typedef T PredMap;
1.1005 + static PredMap *createPredMap(const Digraph &) { return 0; };
1.1006 + SetPredMapBase(const TR &b) : TR(b) {}
1.1007 + };
1.1008 +
1.1009 + /// \brief \ref named-templ-param "Named parameter" for setting
1.1010 + /// the predecessor map.
1.1011 + ///
1.1012 + /// \ref named-templ-param "Named parameter" for setting
1.1013 + /// the map that stores the predecessor arcs of the nodes.
1.1014 + template<class T>
1.1015 + BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1.1016 + Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1.1017 + return BellmanFordWizard<SetPredMapBase<T> >(*this);
1.1018 + }
1.1019 +
1.1020 + template<class T>
1.1021 + struct SetDistMapBase : public Base {
1.1022 + typedef T DistMap;
1.1023 + static DistMap *createDistMap(const Digraph &) { return 0; };
1.1024 + SetDistMapBase(const TR &b) : TR(b) {}
1.1025 + };
1.1026 +
1.1027 + /// \brief \ref named-templ-param "Named parameter" for setting
1.1028 + /// the distance map.
1.1029 + ///
1.1030 + /// \ref named-templ-param "Named parameter" for setting
1.1031 + /// the map that stores the distances of the nodes calculated
1.1032 + /// by the algorithm.
1.1033 + template<class T>
1.1034 + BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1.1035 + Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1.1036 + return BellmanFordWizard<SetDistMapBase<T> >(*this);
1.1037 + }
1.1038 +
1.1039 + template<class T>
1.1040 + struct SetPathBase : public Base {
1.1041 + typedef T Path;
1.1042 + SetPathBase(const TR &b) : TR(b) {}
1.1043 + };
1.1044 +
1.1045 + /// \brief \ref named-func-param "Named parameter" for getting
1.1046 + /// the shortest path to the target node.
1.1047 + ///
1.1048 + /// \ref named-func-param "Named parameter" for getting
1.1049 + /// the shortest path to the target node.
1.1050 + template<class T>
1.1051 + BellmanFordWizard<SetPathBase<T> > path(const T &t)
1.1052 + {
1.1053 + Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1.1054 + return BellmanFordWizard<SetPathBase<T> >(*this);
1.1055 + }
1.1056 +
1.1057 + /// \brief \ref named-func-param "Named parameter" for getting
1.1058 + /// the distance of the target node.
1.1059 + ///
1.1060 + /// \ref named-func-param "Named parameter" for getting
1.1061 + /// the distance of the target node.
1.1062 + BellmanFordWizard dist(const Value &d)
1.1063 + {
1.1064 + Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1.1065 + return *this;
1.1066 + }
1.1067 +
1.1068 + };
1.1069 +
1.1070 + /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1.1071 + /// algorithm.
1.1072 + ///
1.1073 + /// \ingroup shortest_path
1.1074 + /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1.1075 + /// algorithm.
1.1076 + ///
1.1077 + /// This function also has several \ref named-templ-func-param
1.1078 + /// "named parameters", they are declared as the members of class
1.1079 + /// \ref BellmanFordWizard.
1.1080 + /// The following examples show how to use these parameters.
1.1081 + /// \code
1.1082 + /// // Compute shortest path from node s to each node
1.1083 + /// bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1.1084 + ///
1.1085 + /// // Compute shortest path from s to t
1.1086 + /// bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1.1087 + /// \endcode
1.1088 + /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1.1089 + /// to the end of the parameter list.
1.1090 + /// \sa BellmanFordWizard
1.1091 + /// \sa BellmanFord
1.1092 + template<typename GR, typename LEN>
1.1093 + BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1.1094 + bellmanFord(const GR& digraph,
1.1095 + const LEN& length)
1.1096 + {
1.1097 + return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1.1098 + }
1.1099 +
1.1100 +} //END OF NAMESPACE LEMON
1.1101 +
1.1102 +#endif
1.1103 +