1.1 --- a/lemon/Makefile.am Thu Jun 11 23:13:24 2009 +0200
1.2 +++ b/lemon/Makefile.am Fri Jul 24 23:19:43 2009 +0200
1.3 @@ -57,6 +57,7 @@
1.4 lemon/adaptors.h \
1.5 lemon/arg_parser.h \
1.6 lemon/assert.h \
1.7 + lemon/bellman_ford.h \
1.8 lemon/bfs.h \
1.9 lemon/bin_heap.h \
1.10 lemon/bucket_heap.h \
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/lemon/bellman_ford.h Fri Jul 24 23:19:43 2009 +0200
2.3 @@ -0,0 +1,1042 @@
2.4 +/* -*- C++ -*-
2.5 + *
2.6 + * This file is a part of LEMON, a generic C++ optimization library
2.7 + *
2.8 + * Copyright (C) 2003-2008
2.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
2.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
2.11 + *
2.12 + * Permission to use, modify and distribute this software is granted
2.13 + * provided that this copyright notice appears in all copies. For
2.14 + * precise terms see the accompanying LICENSE file.
2.15 + *
2.16 + * This software is provided "AS IS" with no warranty of any kind,
2.17 + * express or implied, and with no claim as to its suitability for any
2.18 + * purpose.
2.19 + *
2.20 + */
2.21 +
2.22 +#ifndef LEMON_BELMANN_FORD_H
2.23 +#define LEMON_BELMANN_FORD_H
2.24 +
2.25 +/// \ingroup shortest_path
2.26 +/// \file
2.27 +/// \brief Bellman-Ford algorithm.
2.28 +///
2.29 +
2.30 +#include <lemon/bits/path_dump.h>
2.31 +#include <lemon/core.h>
2.32 +#include <lemon/error.h>
2.33 +#include <lemon/maps.h>
2.34 +
2.35 +#include <limits>
2.36 +
2.37 +namespace lemon {
2.38 +
2.39 + /// \brief Default OperationTraits for the BellmanFord algorithm class.
2.40 + ///
2.41 + /// It defines all computational operations and constants which are
2.42 + /// used in the Bellman-Ford algorithm. The default implementation
2.43 + /// is based on the numeric_limits class. If the numeric type does not
2.44 + /// have infinity value then the maximum value is used as extremal
2.45 + /// infinity value.
2.46 + template <
2.47 + typename Value,
2.48 + bool has_infinity = std::numeric_limits<Value>::has_infinity>
2.49 + struct BellmanFordDefaultOperationTraits {
2.50 + /// \brief Gives back the zero value of the type.
2.51 + static Value zero() {
2.52 + return static_cast<Value>(0);
2.53 + }
2.54 + /// \brief Gives back the positive infinity value of the type.
2.55 + static Value infinity() {
2.56 + return std::numeric_limits<Value>::infinity();
2.57 + }
2.58 + /// \brief Gives back the sum of the given two elements.
2.59 + static Value plus(const Value& left, const Value& right) {
2.60 + return left + right;
2.61 + }
2.62 + /// \brief Gives back true only if the first value less than the second.
2.63 + static bool less(const Value& left, const Value& right) {
2.64 + return left < right;
2.65 + }
2.66 + };
2.67 +
2.68 + template <typename Value>
2.69 + struct BellmanFordDefaultOperationTraits<Value, false> {
2.70 + static Value zero() {
2.71 + return static_cast<Value>(0);
2.72 + }
2.73 + static Value infinity() {
2.74 + return std::numeric_limits<Value>::max();
2.75 + }
2.76 + static Value plus(const Value& left, const Value& right) {
2.77 + if (left == infinity() || right == infinity()) return infinity();
2.78 + return left + right;
2.79 + }
2.80 + static bool less(const Value& left, const Value& right) {
2.81 + return left < right;
2.82 + }
2.83 + };
2.84 +
2.85 + /// \brief Default traits class of BellmanFord class.
2.86 + ///
2.87 + /// Default traits class of BellmanFord class.
2.88 + /// \param _Digraph Digraph type.
2.89 + /// \param _LegthMap Type of length map.
2.90 + template<class _Digraph, class _LengthMap>
2.91 + struct BellmanFordDefaultTraits {
2.92 + /// The digraph type the algorithm runs on.
2.93 + typedef _Digraph Digraph;
2.94 +
2.95 + /// \brief The type of the map that stores the arc lengths.
2.96 + ///
2.97 + /// The type of the map that stores the arc lengths.
2.98 + /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
2.99 + typedef _LengthMap LengthMap;
2.100 +
2.101 + // The type of the length of the arcs.
2.102 + typedef typename _LengthMap::Value Value;
2.103 +
2.104 + /// \brief Operation traits for Bellman-Ford algorithm.
2.105 + ///
2.106 + /// It defines the infinity type on the given Value type
2.107 + /// and the used operation.
2.108 + /// \see BellmanFordDefaultOperationTraits
2.109 + typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
2.110 +
2.111 + /// \brief The type of the map that stores the last arcs of the
2.112 + /// shortest paths.
2.113 + ///
2.114 + /// The type of the map that stores the last
2.115 + /// arcs of the shortest paths.
2.116 + /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
2.117 + ///
2.118 + typedef typename Digraph::template NodeMap<typename _Digraph::Arc> PredMap;
2.119 +
2.120 + /// \brief Instantiates a PredMap.
2.121 + ///
2.122 + /// This function instantiates a \ref PredMap.
2.123 + /// \param digraph is the digraph, to which we would like to define the PredMap.
2.124 + static PredMap *createPredMap(const _Digraph& digraph) {
2.125 + return new PredMap(digraph);
2.126 + }
2.127 +
2.128 + /// \brief The type of the map that stores the dists of the nodes.
2.129 + ///
2.130 + /// The type of the map that stores the dists of the nodes.
2.131 + /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
2.132 + ///
2.133 + typedef typename Digraph::template NodeMap<typename _LengthMap::Value>
2.134 + DistMap;
2.135 +
2.136 + /// \brief Instantiates a DistMap.
2.137 + ///
2.138 + /// This function instantiates a \ref DistMap.
2.139 + /// \param digraph is the digraph, to which we would like to define the
2.140 + /// \ref DistMap
2.141 + static DistMap *createDistMap(const _Digraph& digraph) {
2.142 + return new DistMap(digraph);
2.143 + }
2.144 +
2.145 + };
2.146 +
2.147 + /// \brief %BellmanFord algorithm class.
2.148 + ///
2.149 + /// \ingroup shortest_path
2.150 + /// This class provides an efficient implementation of \c Bellman-Ford
2.151 + /// algorithm. The arc lengths are passed to the algorithm using a
2.152 + /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
2.153 + /// kind of length.
2.154 + ///
2.155 + /// The Bellman-Ford algorithm solves the shortest path from one node
2.156 + /// problem when the arcs can have negative length but the digraph should
2.157 + /// not contain cycles with negative sum of length. If we can assume
2.158 + /// that all arc is non-negative in the digraph then the dijkstra algorithm
2.159 + /// should be used rather.
2.160 + ///
2.161 + /// The maximal time complexity of the algorithm is \f$ O(ne) \f$.
2.162 + ///
2.163 + /// The type of the length is determined by the
2.164 + /// \ref concepts::ReadMap::Value "Value" of the length map.
2.165 + ///
2.166 + /// \param _Digraph The digraph type the algorithm runs on. The default value
2.167 + /// is \ref ListDigraph. The value of _Digraph is not used directly by
2.168 + /// BellmanFord, it is only passed to \ref BellmanFordDefaultTraits.
2.169 + /// \param _LengthMap This read-only ArcMap determines the lengths of the
2.170 + /// arcs. The default map type is \ref concepts::Digraph::ArcMap
2.171 + /// "Digraph::ArcMap<int>". The value of _LengthMap is not used directly
2.172 + /// by BellmanFord, it is only passed to \ref BellmanFordDefaultTraits.
2.173 + /// \param _Traits Traits class to set various data types used by the
2.174 + /// algorithm. The default traits class is \ref BellmanFordDefaultTraits
2.175 + /// "BellmanFordDefaultTraits<_Digraph,_LengthMap>". See \ref
2.176 + /// BellmanFordDefaultTraits for the documentation of a BellmanFord traits
2.177 + /// class.
2.178 +#ifdef DOXYGEN
2.179 + template <typename _Digraph, typename _LengthMap, typename _Traits>
2.180 +#else
2.181 + template <typename _Digraph,
2.182 + typename _LengthMap=typename _Digraph::template ArcMap<int>,
2.183 + typename _Traits=BellmanFordDefaultTraits<_Digraph,_LengthMap> >
2.184 +#endif
2.185 + class BellmanFord {
2.186 + public:
2.187 +
2.188 + typedef _Traits Traits;
2.189 + ///The type of the underlying digraph.
2.190 + typedef typename _Traits::Digraph Digraph;
2.191 +
2.192 + typedef typename Digraph::Node Node;
2.193 + typedef typename Digraph::NodeIt NodeIt;
2.194 + typedef typename Digraph::Arc Arc;
2.195 + typedef typename Digraph::OutArcIt OutArcIt;
2.196 +
2.197 + /// \brief The type of the length of the arcs.
2.198 + typedef typename _Traits::LengthMap::Value Value;
2.199 + /// \brief The type of the map that stores the arc lengths.
2.200 + typedef typename _Traits::LengthMap LengthMap;
2.201 + /// \brief The type of the map that stores the last
2.202 + /// arcs of the shortest paths.
2.203 + typedef typename _Traits::PredMap PredMap;
2.204 + /// \brief The type of the map that stores the dists of the nodes.
2.205 + typedef typename _Traits::DistMap DistMap;
2.206 + /// \brief The operation traits.
2.207 + typedef typename _Traits::OperationTraits OperationTraits;
2.208 + private:
2.209 + /// Pointer to the underlying digraph.
2.210 + const Digraph *digraph;
2.211 + /// Pointer to the length map
2.212 + const LengthMap *length;
2.213 + ///Pointer to the map of predecessors arcs.
2.214 + PredMap *_pred;
2.215 + ///Indicates if \ref _pred is locally allocated (\c true) or not.
2.216 + bool local_pred;
2.217 + ///Pointer to the map of distances.
2.218 + DistMap *_dist;
2.219 + ///Indicates if \ref _dist is locally allocated (\c true) or not.
2.220 + bool local_dist;
2.221 +
2.222 + typedef typename Digraph::template NodeMap<bool> MaskMap;
2.223 + MaskMap *_mask;
2.224 +
2.225 + std::vector<Node> _process;
2.226 +
2.227 + /// Creates the maps if necessary.
2.228 + void create_maps() {
2.229 + if(!_pred) {
2.230 + local_pred = true;
2.231 + _pred = Traits::createPredMap(*digraph);
2.232 + }
2.233 + if(!_dist) {
2.234 + local_dist = true;
2.235 + _dist = Traits::createDistMap(*digraph);
2.236 + }
2.237 + _mask = new MaskMap(*digraph, false);
2.238 + }
2.239 +
2.240 + public :
2.241 +
2.242 + typedef BellmanFord Create;
2.243 +
2.244 + /// \name Named template parameters
2.245 +
2.246 + ///@{
2.247 +
2.248 + template <class T>
2.249 + struct DefPredMapTraits : public Traits {
2.250 + typedef T PredMap;
2.251 + static PredMap *createPredMap(const Digraph&) {
2.252 + LEMON_ASSERT(false, "PredMap is not initialized");
2.253 + return 0; // ignore warnings
2.254 + }
2.255 + };
2.256 +
2.257 + /// \brief \ref named-templ-param "Named parameter" for setting PredMap
2.258 + /// type
2.259 + /// \ref named-templ-param "Named parameter" for setting PredMap type
2.260 + ///
2.261 + template <class T>
2.262 + struct SetPredMap
2.263 + : public BellmanFord< Digraph, LengthMap, DefPredMapTraits<T> > {
2.264 + typedef BellmanFord< Digraph, LengthMap, DefPredMapTraits<T> > Create;
2.265 + };
2.266 +
2.267 + template <class T>
2.268 + struct DefDistMapTraits : public Traits {
2.269 + typedef T DistMap;
2.270 + static DistMap *createDistMap(const Digraph&) {
2.271 + LEMON_ASSERT(false, "DistMap is not initialized");
2.272 + return 0; // ignore warnings
2.273 + }
2.274 + };
2.275 +
2.276 + /// \brief \ref named-templ-param "Named parameter" for setting DistMap
2.277 + /// type
2.278 + ///
2.279 + /// \ref named-templ-param "Named parameter" for setting DistMap type
2.280 + ///
2.281 + template <class T>
2.282 + struct SetDistMap
2.283 + : public BellmanFord< Digraph, LengthMap, DefDistMapTraits<T> > {
2.284 + typedef BellmanFord< Digraph, LengthMap, DefDistMapTraits<T> > Create;
2.285 + };
2.286 +
2.287 + template <class T>
2.288 + struct DefOperationTraitsTraits : public Traits {
2.289 + typedef T OperationTraits;
2.290 + };
2.291 +
2.292 + /// \brief \ref named-templ-param "Named parameter" for setting
2.293 + /// OperationTraits type
2.294 + ///
2.295 + /// \ref named-templ-param "Named parameter" for setting OperationTraits
2.296 + /// type
2.297 + template <class T>
2.298 + struct SetOperationTraits
2.299 + : public BellmanFord< Digraph, LengthMap, DefOperationTraitsTraits<T> > {
2.300 + typedef BellmanFord< Digraph, LengthMap, DefOperationTraitsTraits<T> >
2.301 + Create;
2.302 + };
2.303 +
2.304 + ///@}
2.305 +
2.306 + protected:
2.307 +
2.308 + BellmanFord() {}
2.309 +
2.310 + public:
2.311 +
2.312 + /// \brief Constructor.
2.313 + ///
2.314 + /// \param _graph the digraph the algorithm will run on.
2.315 + /// \param _length the length map used by the algorithm.
2.316 + BellmanFord(const Digraph& _graph, const LengthMap& _length) :
2.317 + digraph(&_graph), length(&_length),
2.318 + _pred(0), local_pred(false),
2.319 + _dist(0), local_dist(false), _mask(0) {}
2.320 +
2.321 + ///Destructor.
2.322 + ~BellmanFord() {
2.323 + if(local_pred) delete _pred;
2.324 + if(local_dist) delete _dist;
2.325 + if(_mask) delete _mask;
2.326 + }
2.327 +
2.328 + /// \brief Sets the length map.
2.329 + ///
2.330 + /// Sets the length map.
2.331 + /// \return \c (*this)
2.332 + BellmanFord &lengthMap(const LengthMap &m) {
2.333 + length = &m;
2.334 + return *this;
2.335 + }
2.336 +
2.337 + /// \brief Sets the map storing the predecessor arcs.
2.338 + ///
2.339 + /// Sets the map storing the predecessor arcs.
2.340 + /// If you don't use this function before calling \ref run(),
2.341 + /// it will allocate one. The destuctor deallocates this
2.342 + /// automatically allocated map, of course.
2.343 + /// \return \c (*this)
2.344 + BellmanFord &predMap(PredMap &m) {
2.345 + if(local_pred) {
2.346 + delete _pred;
2.347 + local_pred=false;
2.348 + }
2.349 + _pred = &m;
2.350 + return *this;
2.351 + }
2.352 +
2.353 + /// \brief Sets the map storing the distances calculated by the algorithm.
2.354 + ///
2.355 + /// Sets the map storing the distances calculated by the algorithm.
2.356 + /// If you don't use this function before calling \ref run(),
2.357 + /// it will allocate one. The destuctor deallocates this
2.358 + /// automatically allocated map, of course.
2.359 + /// \return \c (*this)
2.360 + BellmanFord &distMap(DistMap &m) {
2.361 + if(local_dist) {
2.362 + delete _dist;
2.363 + local_dist=false;
2.364 + }
2.365 + _dist = &m;
2.366 + return *this;
2.367 + }
2.368 +
2.369 + /// \name Execution control
2.370 + /// The simplest way to execute the algorithm is to use
2.371 + /// one of the member functions called \c run(...).
2.372 + /// \n
2.373 + /// If you need more control on the execution,
2.374 + /// first you must call \ref init(), then you can add several source nodes
2.375 + /// with \ref addSource().
2.376 + /// Finally \ref start() will perform the actual path
2.377 + /// computation.
2.378 +
2.379 + ///@{
2.380 +
2.381 + /// \brief Initializes the internal data structures.
2.382 + ///
2.383 + /// Initializes the internal data structures.
2.384 + void init(const Value value = OperationTraits::infinity()) {
2.385 + create_maps();
2.386 + for (NodeIt it(*digraph); it != INVALID; ++it) {
2.387 + _pred->set(it, INVALID);
2.388 + _dist->set(it, value);
2.389 + }
2.390 + _process.clear();
2.391 + if (OperationTraits::less(value, OperationTraits::infinity())) {
2.392 + for (NodeIt it(*digraph); it != INVALID; ++it) {
2.393 + _process.push_back(it);
2.394 + _mask->set(it, true);
2.395 + }
2.396 + }
2.397 + }
2.398 +
2.399 + /// \brief Adds a new source node.
2.400 + ///
2.401 + /// Adds a new source node. The optional second parameter is the
2.402 + /// initial distance of the node. It just sets the distance of the
2.403 + /// node to the given value.
2.404 + void addSource(Node source, Value dst = OperationTraits::zero()) {
2.405 + _dist->set(source, dst);
2.406 + if (!(*_mask)[source]) {
2.407 + _process.push_back(source);
2.408 + _mask->set(source, true);
2.409 + }
2.410 + }
2.411 +
2.412 + /// \brief Executes one round from the Bellman-Ford algorithm.
2.413 + ///
2.414 + /// If the algoritm calculated the distances in the previous round
2.415 + /// exactly for all at most \f$ k \f$ length path lengths then it will
2.416 + /// calculate the distances exactly for all at most \f$ k + 1 \f$
2.417 + /// length path lengths. With \f$ k \f$ iteration this function
2.418 + /// calculates the at most \f$ k \f$ length path lengths.
2.419 + ///
2.420 + /// \warning The paths with limited arc number cannot be retrieved
2.421 + /// easily with \ref path() or \ref predArc() functions. If you
2.422 + /// need the shortest path and not just the distance you should store
2.423 + /// after each iteration the \ref predMap() map and manually build
2.424 + /// the path.
2.425 + ///
2.426 + /// \return \c true when the algorithm have not found more shorter
2.427 + /// paths.
2.428 + bool processNextRound() {
2.429 + for (int i = 0; i < int(_process.size()); ++i) {
2.430 + _mask->set(_process[i], false);
2.431 + }
2.432 + std::vector<Node> nextProcess;
2.433 + std::vector<Value> values(_process.size());
2.434 + for (int i = 0; i < int(_process.size()); ++i) {
2.435 + values[i] = (*_dist)[_process[i]];
2.436 + }
2.437 + for (int i = 0; i < int(_process.size()); ++i) {
2.438 + for (OutArcIt it(*digraph, _process[i]); it != INVALID; ++it) {
2.439 + Node target = digraph->target(it);
2.440 + Value relaxed = OperationTraits::plus(values[i], (*length)[it]);
2.441 + if (OperationTraits::less(relaxed, (*_dist)[target])) {
2.442 + _pred->set(target, it);
2.443 + _dist->set(target, relaxed);
2.444 + if (!(*_mask)[target]) {
2.445 + _mask->set(target, true);
2.446 + nextProcess.push_back(target);
2.447 + }
2.448 + }
2.449 + }
2.450 + }
2.451 + _process.swap(nextProcess);
2.452 + return _process.empty();
2.453 + }
2.454 +
2.455 + /// \brief Executes one weak round from the Bellman-Ford algorithm.
2.456 + ///
2.457 + /// If the algorithm calculated the distances in the
2.458 + /// previous round at least for all at most k length paths then it will
2.459 + /// calculate the distances at least for all at most k + 1 length paths.
2.460 + /// This function does not make it possible to calculate strictly the
2.461 + /// at most k length minimal paths, this is why it is
2.462 + /// called just weak round.
2.463 + /// \return \c true when the algorithm have not found more shorter paths.
2.464 + bool processNextWeakRound() {
2.465 + for (int i = 0; i < int(_process.size()); ++i) {
2.466 + _mask->set(_process[i], false);
2.467 + }
2.468 + std::vector<Node> nextProcess;
2.469 + for (int i = 0; i < int(_process.size()); ++i) {
2.470 + for (OutArcIt it(*digraph, _process[i]); it != INVALID; ++it) {
2.471 + Node target = digraph->target(it);
2.472 + Value relaxed =
2.473 + OperationTraits::plus((*_dist)[_process[i]], (*length)[it]);
2.474 + if (OperationTraits::less(relaxed, (*_dist)[target])) {
2.475 + _pred->set(target, it);
2.476 + _dist->set(target, relaxed);
2.477 + if (!(*_mask)[target]) {
2.478 + _mask->set(target, true);
2.479 + nextProcess.push_back(target);
2.480 + }
2.481 + }
2.482 + }
2.483 + }
2.484 + _process.swap(nextProcess);
2.485 + return _process.empty();
2.486 + }
2.487 +
2.488 + /// \brief Executes the algorithm.
2.489 + ///
2.490 + /// \pre init() must be called and at least one node should be added
2.491 + /// with addSource() before using this function.
2.492 + ///
2.493 + /// This method runs the %BellmanFord algorithm from the root node(s)
2.494 + /// in order to compute the shortest path to each node. The algorithm
2.495 + /// computes
2.496 + /// - The shortest path tree.
2.497 + /// - The distance of each node from the root(s).
2.498 + void start() {
2.499 + int num = countNodes(*digraph) - 1;
2.500 + for (int i = 0; i < num; ++i) {
2.501 + if (processNextWeakRound()) break;
2.502 + }
2.503 + }
2.504 +
2.505 + /// \brief Executes the algorithm and checks the negative cycles.
2.506 + ///
2.507 + /// \pre init() must be called and at least one node should be added
2.508 + /// with addSource() before using this function.
2.509 + ///
2.510 + /// This method runs the %BellmanFord algorithm from the root node(s)
2.511 + /// in order to compute the shortest path to each node. The algorithm
2.512 + /// computes
2.513 + /// - The shortest path tree.
2.514 + /// - The distance of each node from the root(s).
2.515 + ///
2.516 + /// \return \c false if there is a negative cycle in the digraph.
2.517 + bool checkedStart() {
2.518 + int num = countNodes(*digraph);
2.519 + for (int i = 0; i < num; ++i) {
2.520 + if (processNextWeakRound()) return true;
2.521 + }
2.522 + return _process.empty();
2.523 + }
2.524 +
2.525 + /// \brief Executes the algorithm with path length limit.
2.526 + ///
2.527 + /// \pre init() must be called and at least one node should be added
2.528 + /// with addSource() before using this function.
2.529 + ///
2.530 + /// This method runs the %BellmanFord algorithm from the root
2.531 + /// node(s) in order to compute the shortest path lengths with at
2.532 + /// most \c num arc.
2.533 + ///
2.534 + /// \warning The paths with limited arc number cannot be retrieved
2.535 + /// easily with \ref path() or \ref predArc() functions. If you
2.536 + /// need the shortest path and not just the distance you should store
2.537 + /// after each iteration the \ref predMap() map and manually build
2.538 + /// the path.
2.539 + ///
2.540 + /// The algorithm computes
2.541 + /// - The predecessor arc from each node.
2.542 + /// - The limited distance of each node from the root(s).
2.543 + void limitedStart(int num) {
2.544 + for (int i = 0; i < num; ++i) {
2.545 + if (processNextRound()) break;
2.546 + }
2.547 + }
2.548 +
2.549 + /// \brief Runs %BellmanFord algorithm from node \c s.
2.550 + ///
2.551 + /// This method runs the %BellmanFord algorithm from a root node \c s
2.552 + /// in order to compute the shortest path to each node. The algorithm
2.553 + /// computes
2.554 + /// - The shortest path tree.
2.555 + /// - The distance of each node from the root.
2.556 + ///
2.557 + /// \note d.run(s) is just a shortcut of the following code.
2.558 + ///\code
2.559 + /// d.init();
2.560 + /// d.addSource(s);
2.561 + /// d.start();
2.562 + ///\endcode
2.563 + void run(Node s) {
2.564 + init();
2.565 + addSource(s);
2.566 + start();
2.567 + }
2.568 +
2.569 + /// \brief Runs %BellmanFord algorithm with limited path length
2.570 + /// from node \c s.
2.571 + ///
2.572 + /// This method runs the %BellmanFord algorithm from a root node \c s
2.573 + /// in order to compute the shortest path with at most \c len arcs
2.574 + /// to each node. The algorithm computes
2.575 + /// - The shortest path tree.
2.576 + /// - The distance of each node from the root.
2.577 + ///
2.578 + /// \note d.run(s, num) is just a shortcut of the following code.
2.579 + ///\code
2.580 + /// d.init();
2.581 + /// d.addSource(s);
2.582 + /// d.limitedStart(num);
2.583 + ///\endcode
2.584 + void run(Node s, int num) {
2.585 + init();
2.586 + addSource(s);
2.587 + limitedStart(num);
2.588 + }
2.589 +
2.590 + ///@}
2.591 +
2.592 + /// \name Query Functions
2.593 + /// The result of the %BellmanFord algorithm can be obtained using these
2.594 + /// functions.\n
2.595 + /// Before the use of these functions,
2.596 + /// either run() or start() must be called.
2.597 +
2.598 + ///@{
2.599 +
2.600 + /// \brief Lemon iterator for get the active nodes.
2.601 + ///
2.602 + /// Lemon iterator for get the active nodes. This class provides a
2.603 + /// common style lemon iterator which gives back a subset of the
2.604 + /// nodes. The iterated nodes are active in the algorithm after
2.605 + /// the last phase so these should be checked in the next phase to
2.606 + /// find augmenting arcs from these.
2.607 + class ActiveIt {
2.608 + public:
2.609 +
2.610 + /// \brief Constructor.
2.611 + ///
2.612 + /// Constructor for get the nodeset of the variable.
2.613 + ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
2.614 + {
2.615 + _index = _algorithm->_process.size() - 1;
2.616 + }
2.617 +
2.618 + /// \brief Invalid constructor.
2.619 + ///
2.620 + /// Invalid constructor.
2.621 + ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
2.622 +
2.623 + /// \brief Conversion to node.
2.624 + ///
2.625 + /// Conversion to node.
2.626 + operator Node() const {
2.627 + return _index >= 0 ? _algorithm->_process[_index] : INVALID;
2.628 + }
2.629 +
2.630 + /// \brief Increment operator.
2.631 + ///
2.632 + /// Increment operator.
2.633 + ActiveIt& operator++() {
2.634 + --_index;
2.635 + return *this;
2.636 + }
2.637 +
2.638 + bool operator==(const ActiveIt& it) const {
2.639 + return static_cast<Node>(*this) == static_cast<Node>(it);
2.640 + }
2.641 + bool operator!=(const ActiveIt& it) const {
2.642 + return static_cast<Node>(*this) != static_cast<Node>(it);
2.643 + }
2.644 + bool operator<(const ActiveIt& it) const {
2.645 + return static_cast<Node>(*this) < static_cast<Node>(it);
2.646 + }
2.647 +
2.648 + private:
2.649 + const BellmanFord* _algorithm;
2.650 + int _index;
2.651 + };
2.652 +
2.653 + typedef PredMapPath<Digraph, PredMap> Path;
2.654 +
2.655 + /// \brief Gives back the shortest path.
2.656 + ///
2.657 + /// Gives back the shortest path.
2.658 + /// \pre The \c t should be reachable from the source.
2.659 + Path path(Node t)
2.660 + {
2.661 + return Path(*digraph, *_pred, t);
2.662 + }
2.663 +
2.664 +
2.665 + // TODO : implement negative cycle
2.666 +// /// \brief Gives back a negative cycle.
2.667 +// ///
2.668 +// /// This function gives back a negative cycle.
2.669 +// /// If the algorithm have not found yet negative cycle it will give back
2.670 +// /// an empty path.
2.671 +// Path negativeCycle() {
2.672 +// typename Digraph::template NodeMap<int> state(*digraph, 0);
2.673 +// for (ActiveIt it(*this); it != INVALID; ++it) {
2.674 +// if (state[it] == 0) {
2.675 +// for (Node t = it; predArc(t) != INVALID; t = predNode(t)) {
2.676 +// if (state[t] == 0) {
2.677 +// state[t] = 1;
2.678 +// } else if (state[t] == 2) {
2.679 +// break;
2.680 +// } else {
2.681 +// p.clear();
2.682 +// typename Path::Builder b(p);
2.683 +// b.setStartNode(t);
2.684 +// b.pushFront(predArc(t));
2.685 +// for(Node s = predNode(t); s != t; s = predNode(s)) {
2.686 +// b.pushFront(predArc(s));
2.687 +// }
2.688 +// b.commit();
2.689 +// return true;
2.690 +// }
2.691 +// }
2.692 +// for (Node t = it; predArc(t) != INVALID; t = predNode(t)) {
2.693 +// if (state[t] == 1) {
2.694 +// state[t] = 2;
2.695 +// } else {
2.696 +// break;
2.697 +// }
2.698 +// }
2.699 +// }
2.700 +// }
2.701 +// return false;
2.702 +// }
2.703 +
2.704 + /// \brief The distance of a node from the root.
2.705 + ///
2.706 + /// Returns the distance of a node from the root.
2.707 + /// \pre \ref run() must be called before using this function.
2.708 + /// \warning If node \c v in unreachable from the root the return value
2.709 + /// of this funcion is undefined.
2.710 + Value dist(Node v) const { return (*_dist)[v]; }
2.711 +
2.712 + /// \brief Returns the 'previous arc' of the shortest path tree.
2.713 + ///
2.714 + /// For a node \c v it returns the 'previous arc' of the shortest path
2.715 + /// tree, i.e. it returns the last arc of a shortest path from the root
2.716 + /// to \c v. It is \ref INVALID if \c v is unreachable from the root or
2.717 + /// if \c v=s. The shortest path tree used here is equal to the shortest
2.718 + /// path tree used in \ref predNode().
2.719 + /// \pre \ref run() must be called before using
2.720 + /// this function.
2.721 + Arc predArc(Node v) const { return (*_pred)[v]; }
2.722 +
2.723 + /// \brief Returns the 'previous node' of the shortest path tree.
2.724 + ///
2.725 + /// For a node \c v it returns the 'previous node' of the shortest path
2.726 + /// tree, i.e. it returns the last but one node from a shortest path from
2.727 + /// the root to \c /v. It is INVALID if \c v is unreachable from the root
2.728 + /// or if \c v=s. The shortest path tree used here is equal to the
2.729 + /// shortest path tree used in \ref predArc(). \pre \ref run() must be
2.730 + /// called before using this function.
2.731 + Node predNode(Node v) const {
2.732 + return (*_pred)[v] == INVALID ? INVALID : digraph->source((*_pred)[v]);
2.733 + }
2.734 +
2.735 + /// \brief Returns a reference to the NodeMap of distances.
2.736 + ///
2.737 + /// Returns a reference to the NodeMap of distances. \pre \ref run() must
2.738 + /// be called before using this function.
2.739 + const DistMap &distMap() const { return *_dist;}
2.740 +
2.741 + /// \brief Returns a reference to the shortest path tree map.
2.742 + ///
2.743 + /// Returns a reference to the NodeMap of the arcs of the
2.744 + /// shortest path tree.
2.745 + /// \pre \ref run() must be called before using this function.
2.746 + const PredMap &predMap() const { return *_pred; }
2.747 +
2.748 + /// \brief Checks if a node is reachable from the root.
2.749 + ///
2.750 + /// Returns \c true if \c v is reachable from the root.
2.751 + /// \pre \ref run() must be called before using this function.
2.752 + ///
2.753 + bool reached(Node v) { return (*_dist)[v] != OperationTraits::infinity(); }
2.754 +
2.755 + ///@}
2.756 + };
2.757 +
2.758 + /// \brief Default traits class of BellmanFord function.
2.759 + ///
2.760 + /// Default traits class of BellmanFord function.
2.761 + /// \param _Digraph Digraph type.
2.762 + /// \param _LengthMap Type of length map.
2.763 + template <typename _Digraph, typename _LengthMap>
2.764 + struct BellmanFordWizardDefaultTraits {
2.765 + /// \brief The digraph type the algorithm runs on.
2.766 + typedef _Digraph Digraph;
2.767 +
2.768 + /// \brief The type of the map that stores the arc lengths.
2.769 + ///
2.770 + /// The type of the map that stores the arc lengths.
2.771 + /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
2.772 + typedef _LengthMap LengthMap;
2.773 +
2.774 + /// \brief The value type of the length map.
2.775 + typedef typename _LengthMap::Value Value;
2.776 +
2.777 + /// \brief Operation traits for Bellman-Ford algorithm.
2.778 + ///
2.779 + /// It defines the infinity type on the given Value type
2.780 + /// and the used operation.
2.781 + /// \see BellmanFordDefaultOperationTraits
2.782 + typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
2.783 +
2.784 + /// \brief The type of the map that stores the last
2.785 + /// arcs of the shortest paths.
2.786 + ///
2.787 + /// The type of the map that stores the last
2.788 + /// arcs of the shortest paths.
2.789 + /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
2.790 + typedef NullMap <typename _Digraph::Node,typename _Digraph::Arc> PredMap;
2.791 +
2.792 + /// \brief Instantiates a PredMap.
2.793 + ///
2.794 + /// This function instantiates a \ref PredMap.
2.795 + static PredMap *createPredMap(const _Digraph &) {
2.796 + return new PredMap();
2.797 + }
2.798 + /// \brief The type of the map that stores the dists of the nodes.
2.799 + ///
2.800 + /// The type of the map that stores the dists of the nodes.
2.801 + /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
2.802 + typedef NullMap<typename Digraph::Node, Value> DistMap;
2.803 + /// \brief Instantiates a DistMap.
2.804 + ///
2.805 + /// This function instantiates a \ref DistMap.
2.806 + static DistMap *createDistMap(const _Digraph &) {
2.807 + return new DistMap();
2.808 + }
2.809 + };
2.810 +
2.811 + /// \brief Default traits used by \ref BellmanFordWizard
2.812 + ///
2.813 + /// To make it easier to use BellmanFord algorithm
2.814 + /// we have created a wizard class.
2.815 + /// This \ref BellmanFordWizard class needs default traits,
2.816 + /// as well as the \ref BellmanFord class.
2.817 + /// The \ref BellmanFordWizardBase is a class to be the default traits of the
2.818 + /// \ref BellmanFordWizard class.
2.819 + /// \todo More named parameters are required...
2.820 + template<class _Digraph,class _LengthMap>
2.821 + class BellmanFordWizardBase
2.822 + : public BellmanFordWizardDefaultTraits<_Digraph,_LengthMap> {
2.823 +
2.824 + typedef BellmanFordWizardDefaultTraits<_Digraph,_LengthMap> Base;
2.825 + protected:
2.826 + /// Type of the nodes in the digraph.
2.827 + typedef typename Base::Digraph::Node Node;
2.828 +
2.829 + /// Pointer to the underlying digraph.
2.830 + void *_graph;
2.831 + /// Pointer to the length map
2.832 + void *_length;
2.833 + ///Pointer to the map of predecessors arcs.
2.834 + void *_pred;
2.835 + ///Pointer to the map of distances.
2.836 + void *_dist;
2.837 + ///Pointer to the source node.
2.838 + Node _source;
2.839 +
2.840 + public:
2.841 + /// Constructor.
2.842 +
2.843 + /// This constructor does not require parameters, therefore it initiates
2.844 + /// all of the attributes to default values (0, INVALID).
2.845 + BellmanFordWizardBase() : _graph(0), _length(0), _pred(0),
2.846 + _dist(0), _source(INVALID) {}
2.847 +
2.848 + /// Constructor.
2.849 +
2.850 + /// This constructor requires some parameters,
2.851 + /// listed in the parameters list.
2.852 + /// Others are initiated to 0.
2.853 + /// \param digraph is the initial value of \ref _graph
2.854 + /// \param length is the initial value of \ref _length
2.855 + /// \param source is the initial value of \ref _source
2.856 + BellmanFordWizardBase(const _Digraph& digraph,
2.857 + const _LengthMap& length,
2.858 + Node source = INVALID) :
2.859 + _graph(reinterpret_cast<void*>(const_cast<_Digraph*>(&digraph))),
2.860 + _length(reinterpret_cast<void*>(const_cast<_LengthMap*>(&length))),
2.861 + _pred(0), _dist(0), _source(source) {}
2.862 +
2.863 + };
2.864 +
2.865 + /// A class to make the usage of BellmanFord algorithm easier
2.866 +
2.867 + /// This class is created to make it easier to use BellmanFord algorithm.
2.868 + /// It uses the functions and features of the plain \ref BellmanFord,
2.869 + /// but it is much simpler to use it.
2.870 + ///
2.871 + /// Simplicity means that the way to change the types defined
2.872 + /// in the traits class is based on functions that returns the new class
2.873 + /// and not on templatable built-in classes.
2.874 + /// When using the plain \ref BellmanFord
2.875 + /// the new class with the modified type comes from
2.876 + /// the original class by using the ::
2.877 + /// operator. In the case of \ref BellmanFordWizard only
2.878 + /// a function have to be called and it will
2.879 + /// return the needed class.
2.880 + ///
2.881 + /// It does not have own \ref run method. When its \ref run method is called
2.882 + /// it initiates a plain \ref BellmanFord class, and calls the \ref
2.883 + /// BellmanFord::run method of it.
2.884 + template<class _Traits>
2.885 + class BellmanFordWizard : public _Traits {
2.886 + typedef _Traits Base;
2.887 +
2.888 + ///The type of the underlying digraph.
2.889 + typedef typename _Traits::Digraph Digraph;
2.890 +
2.891 + typedef typename Digraph::Node Node;
2.892 + typedef typename Digraph::NodeIt NodeIt;
2.893 + typedef typename Digraph::Arc Arc;
2.894 + typedef typename Digraph::OutArcIt ArcIt;
2.895 +
2.896 + ///The type of the map that stores the arc lengths.
2.897 + typedef typename _Traits::LengthMap LengthMap;
2.898 +
2.899 + ///The type of the length of the arcs.
2.900 + typedef typename LengthMap::Value Value;
2.901 +
2.902 + ///\brief The type of the map that stores the last
2.903 + ///arcs of the shortest paths.
2.904 + typedef typename _Traits::PredMap PredMap;
2.905 +
2.906 + ///The type of the map that stores the dists of the nodes.
2.907 + typedef typename _Traits::DistMap DistMap;
2.908 +
2.909 + public:
2.910 + /// Constructor.
2.911 + BellmanFordWizard() : _Traits() {}
2.912 +
2.913 + /// \brief Constructor that requires parameters.
2.914 + ///
2.915 + /// Constructor that requires parameters.
2.916 + /// These parameters will be the default values for the traits class.
2.917 + BellmanFordWizard(const Digraph& digraph, const LengthMap& length,
2.918 + Node src = INVALID)
2.919 + : _Traits(digraph, length, src) {}
2.920 +
2.921 + /// \brief Copy constructor
2.922 + BellmanFordWizard(const _Traits &b) : _Traits(b) {}
2.923 +
2.924 + ~BellmanFordWizard() {}
2.925 +
2.926 + /// \brief Runs BellmanFord algorithm from a given node.
2.927 + ///
2.928 + /// Runs BellmanFord algorithm from a given node.
2.929 + /// The node can be given by the \ref source function.
2.930 + void run() {
2.931 + LEMON_ASSERT(Base::_source != INVALID, "Source node is not given");
2.932 + BellmanFord<Digraph,LengthMap,_Traits>
2.933 + bf(*reinterpret_cast<const Digraph*>(Base::_graph),
2.934 + *reinterpret_cast<const LengthMap*>(Base::_length));
2.935 + if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
2.936 + if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
2.937 + bf.run(Base::_source);
2.938 + }
2.939 +
2.940 + /// \brief Runs BellmanFord algorithm from the given node.
2.941 + ///
2.942 + /// Runs BellmanFord algorithm from the given node.
2.943 + /// \param src is the given source.
2.944 + void run(Node src) {
2.945 + Base::_source = src;
2.946 + run();
2.947 + }
2.948 +
2.949 + template<class T>
2.950 + struct DefPredMapBase : public Base {
2.951 + typedef T PredMap;
2.952 + static PredMap *createPredMap(const Digraph &) { return 0; };
2.953 + DefPredMapBase(const _Traits &b) : _Traits(b) {}
2.954 + };
2.955 +
2.956 + ///\brief \ref named-templ-param "Named parameter"
2.957 + ///function for setting PredMap type
2.958 + ///
2.959 + /// \ref named-templ-param "Named parameter"
2.960 + ///function for setting PredMap type
2.961 + ///
2.962 + template<class T>
2.963 + BellmanFordWizard<DefPredMapBase<T> > predMap(const T &t)
2.964 + {
2.965 + Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
2.966 + return BellmanFordWizard<DefPredMapBase<T> >(*this);
2.967 + }
2.968 +
2.969 + template<class T>
2.970 + struct DefDistMapBase : public Base {
2.971 + typedef T DistMap;
2.972 + static DistMap *createDistMap(const Digraph &) { return 0; };
2.973 + DefDistMapBase(const _Traits &b) : _Traits(b) {}
2.974 + };
2.975 +
2.976 + ///\brief \ref named-templ-param "Named parameter"
2.977 + ///function for setting DistMap type
2.978 + ///
2.979 + /// \ref named-templ-param "Named parameter"
2.980 + ///function for setting DistMap type
2.981 + ///
2.982 + template<class T>
2.983 + BellmanFordWizard<DefDistMapBase<T> > distMap(const T &t) {
2.984 + Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
2.985 + return BellmanFordWizard<DefDistMapBase<T> >(*this);
2.986 + }
2.987 +
2.988 + template<class T>
2.989 + struct DefOperationTraitsBase : public Base {
2.990 + typedef T OperationTraits;
2.991 + DefOperationTraitsBase(const _Traits &b) : _Traits(b) {}
2.992 + };
2.993 +
2.994 + ///\brief \ref named-templ-param "Named parameter"
2.995 + ///function for setting OperationTraits type
2.996 + ///
2.997 + /// \ref named-templ-param "Named parameter"
2.998 + ///function for setting OperationTraits type
2.999 + ///
2.1000 + template<class T>
2.1001 + BellmanFordWizard<DefOperationTraitsBase<T> > distMap() {
2.1002 + return BellmanFordWizard<DefDistMapBase<T> >(*this);
2.1003 + }
2.1004 +
2.1005 + /// \brief Sets the source node, from which the BellmanFord algorithm runs.
2.1006 + ///
2.1007 + /// Sets the source node, from which the BellmanFord algorithm runs.
2.1008 + /// \param src is the source node.
2.1009 + BellmanFordWizard<_Traits>& source(Node src) {
2.1010 + Base::_source = src;
2.1011 + return *this;
2.1012 + }
2.1013 +
2.1014 + };
2.1015 +
2.1016 + /// \brief Function type interface for BellmanFord algorithm.
2.1017 + ///
2.1018 + /// \ingroup shortest_path
2.1019 + /// Function type interface for BellmanFord algorithm.
2.1020 + ///
2.1021 + /// This function also has several \ref named-templ-func-param
2.1022 + /// "named parameters", they are declared as the members of class
2.1023 + /// \ref BellmanFordWizard.
2.1024 + /// The following
2.1025 + /// example shows how to use these parameters.
2.1026 + ///\code
2.1027 + /// bellmanford(g,length,source).predMap(preds).run();
2.1028 + ///\endcode
2.1029 + /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
2.1030 + /// to the end of the parameter list.
2.1031 + /// \sa BellmanFordWizard
2.1032 + /// \sa BellmanFord
2.1033 + template<class _Digraph, class _LengthMap>
2.1034 + BellmanFordWizard<BellmanFordWizardBase<_Digraph,_LengthMap> >
2.1035 + bellmanFord(const _Digraph& digraph,
2.1036 + const _LengthMap& length,
2.1037 + typename _Digraph::Node source = INVALID) {
2.1038 + return BellmanFordWizard<BellmanFordWizardBase<_Digraph,_LengthMap> >
2.1039 + (digraph, length, source);
2.1040 + }
2.1041 +
2.1042 +} //END OF NAMESPACE LEMON
2.1043 +
2.1044 +#endif
2.1045 +