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