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