lemon/suurballe.h
changeset 784 1a7fe3bef514
parent 584 33c6b6e755cd
child 851 c67e235c832f
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/suurballe.h	Thu Nov 05 15:50:01 2009 +0100
     1.3 @@ -0,0 +1,535 @@
     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-2009
     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_SUURBALLE_H
    1.23 +#define LEMON_SUURBALLE_H
    1.24 +
    1.25 +///\ingroup shortest_path
    1.26 +///\file
    1.27 +///\brief An algorithm for finding arc-disjoint paths between two
    1.28 +/// nodes having minimum total length.
    1.29 +
    1.30 +#include <vector>
    1.31 +#include <limits>
    1.32 +#include <lemon/bin_heap.h>
    1.33 +#include <lemon/path.h>
    1.34 +#include <lemon/list_graph.h>
    1.35 +#include <lemon/maps.h>
    1.36 +
    1.37 +namespace lemon {
    1.38 +
    1.39 +  /// \addtogroup shortest_path
    1.40 +  /// @{
    1.41 +
    1.42 +  /// \brief Algorithm for finding arc-disjoint paths between two nodes
    1.43 +  /// having minimum total length.
    1.44 +  ///
    1.45 +  /// \ref lemon::Suurballe "Suurballe" implements an algorithm for
    1.46 +  /// finding arc-disjoint paths having minimum total length (cost)
    1.47 +  /// from a given source node to a given target node in a digraph.
    1.48 +  ///
    1.49 +  /// Note that this problem is a special case of the \ref min_cost_flow
    1.50 +  /// "minimum cost flow problem". This implementation is actually an
    1.51 +  /// efficient specialized version of the \ref CapacityScaling
    1.52 +  /// "Successive Shortest Path" algorithm directly for this problem.
    1.53 +  /// Therefore this class provides query functions for flow values and
    1.54 +  /// node potentials (the dual solution) just like the minimum cost flow
    1.55 +  /// algorithms.
    1.56 +  ///
    1.57 +  /// \tparam GR The digraph type the algorithm runs on.
    1.58 +  /// \tparam LEN The type of the length map.
    1.59 +  /// The default value is <tt>GR::ArcMap<int></tt>.
    1.60 +  ///
    1.61 +  /// \warning Length values should be \e non-negative \e integers.
    1.62 +  ///
    1.63 +  /// \note For finding node-disjoint paths this algorithm can be used
    1.64 +  /// along with the \ref SplitNodes adaptor.
    1.65 +#ifdef DOXYGEN
    1.66 +  template <typename GR, typename LEN>
    1.67 +#else
    1.68 +  template < typename GR,
    1.69 +             typename LEN = typename GR::template ArcMap<int> >
    1.70 +#endif
    1.71 +  class Suurballe
    1.72 +  {
    1.73 +    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
    1.74 +
    1.75 +    typedef ConstMap<Arc, int> ConstArcMap;
    1.76 +    typedef typename GR::template NodeMap<Arc> PredMap;
    1.77 +
    1.78 +  public:
    1.79 +
    1.80 +    /// The type of the digraph the algorithm runs on.
    1.81 +    typedef GR Digraph;
    1.82 +    /// The type of the length map.
    1.83 +    typedef LEN LengthMap;
    1.84 +    /// The type of the lengths.
    1.85 +    typedef typename LengthMap::Value Length;
    1.86 +#ifdef DOXYGEN
    1.87 +    /// The type of the flow map.
    1.88 +    typedef GR::ArcMap<int> FlowMap;
    1.89 +    /// The type of the potential map.
    1.90 +    typedef GR::NodeMap<Length> PotentialMap;
    1.91 +#else
    1.92 +    /// The type of the flow map.
    1.93 +    typedef typename Digraph::template ArcMap<int> FlowMap;
    1.94 +    /// The type of the potential map.
    1.95 +    typedef typename Digraph::template NodeMap<Length> PotentialMap;
    1.96 +#endif
    1.97 +
    1.98 +    /// The type of the path structures.
    1.99 +    typedef SimplePath<GR> Path;
   1.100 +
   1.101 +  private:
   1.102 +
   1.103 +    // ResidualDijkstra is a special implementation of the
   1.104 +    // Dijkstra algorithm for finding shortest paths in the
   1.105 +    // residual network with respect to the reduced arc lengths
   1.106 +    // and modifying the node potentials according to the
   1.107 +    // distance of the nodes.
   1.108 +    class ResidualDijkstra
   1.109 +    {
   1.110 +      typedef typename Digraph::template NodeMap<int> HeapCrossRef;
   1.111 +      typedef BinHeap<Length, HeapCrossRef> Heap;
   1.112 +
   1.113 +    private:
   1.114 +
   1.115 +      // The digraph the algorithm runs on
   1.116 +      const Digraph &_graph;
   1.117 +
   1.118 +      // The main maps
   1.119 +      const FlowMap &_flow;
   1.120 +      const LengthMap &_length;
   1.121 +      PotentialMap &_potential;
   1.122 +
   1.123 +      // The distance map
   1.124 +      PotentialMap _dist;
   1.125 +      // The pred arc map
   1.126 +      PredMap &_pred;
   1.127 +      // The processed (i.e. permanently labeled) nodes
   1.128 +      std::vector<Node> _proc_nodes;
   1.129 +
   1.130 +      Node _s;
   1.131 +      Node _t;
   1.132 +
   1.133 +    public:
   1.134 +
   1.135 +      /// Constructor.
   1.136 +      ResidualDijkstra( const Digraph &graph,
   1.137 +                        const FlowMap &flow,
   1.138 +                        const LengthMap &length,
   1.139 +                        PotentialMap &potential,
   1.140 +                        PredMap &pred,
   1.141 +                        Node s, Node t ) :
   1.142 +        _graph(graph), _flow(flow), _length(length), _potential(potential),
   1.143 +        _dist(graph), _pred(pred), _s(s), _t(t) {}
   1.144 +
   1.145 +      /// \brief Run the algorithm. It returns \c true if a path is found
   1.146 +      /// from the source node to the target node.
   1.147 +      bool run() {
   1.148 +        HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
   1.149 +        Heap heap(heap_cross_ref);
   1.150 +        heap.push(_s, 0);
   1.151 +        _pred[_s] = INVALID;
   1.152 +        _proc_nodes.clear();
   1.153 +
   1.154 +        // Process nodes
   1.155 +        while (!heap.empty() && heap.top() != _t) {
   1.156 +          Node u = heap.top(), v;
   1.157 +          Length d = heap.prio() + _potential[u], nd;
   1.158 +          _dist[u] = heap.prio();
   1.159 +          heap.pop();
   1.160 +          _proc_nodes.push_back(u);
   1.161 +
   1.162 +          // Traverse outgoing arcs
   1.163 +          for (OutArcIt e(_graph, u); e != INVALID; ++e) {
   1.164 +            if (_flow[e] == 0) {
   1.165 +              v = _graph.target(e);
   1.166 +              switch(heap.state(v)) {
   1.167 +              case Heap::PRE_HEAP:
   1.168 +                heap.push(v, d + _length[e] - _potential[v]);
   1.169 +                _pred[v] = e;
   1.170 +                break;
   1.171 +              case Heap::IN_HEAP:
   1.172 +                nd = d + _length[e] - _potential[v];
   1.173 +                if (nd < heap[v]) {
   1.174 +                  heap.decrease(v, nd);
   1.175 +                  _pred[v] = e;
   1.176 +                }
   1.177 +                break;
   1.178 +              case Heap::POST_HEAP:
   1.179 +                break;
   1.180 +              }
   1.181 +            }
   1.182 +          }
   1.183 +
   1.184 +          // Traverse incoming arcs
   1.185 +          for (InArcIt e(_graph, u); e != INVALID; ++e) {
   1.186 +            if (_flow[e] == 1) {
   1.187 +              v = _graph.source(e);
   1.188 +              switch(heap.state(v)) {
   1.189 +              case Heap::PRE_HEAP:
   1.190 +                heap.push(v, d - _length[e] - _potential[v]);
   1.191 +                _pred[v] = e;
   1.192 +                break;
   1.193 +              case Heap::IN_HEAP:
   1.194 +                nd = d - _length[e] - _potential[v];
   1.195 +                if (nd < heap[v]) {
   1.196 +                  heap.decrease(v, nd);
   1.197 +                  _pred[v] = e;
   1.198 +                }
   1.199 +                break;
   1.200 +              case Heap::POST_HEAP:
   1.201 +                break;
   1.202 +              }
   1.203 +            }
   1.204 +          }
   1.205 +        }
   1.206 +        if (heap.empty()) return false;
   1.207 +
   1.208 +        // Update potentials of processed nodes
   1.209 +        Length t_dist = heap.prio();
   1.210 +        for (int i = 0; i < int(_proc_nodes.size()); ++i)
   1.211 +          _potential[_proc_nodes[i]] += _dist[_proc_nodes[i]] - t_dist;
   1.212 +        return true;
   1.213 +      }
   1.214 +
   1.215 +    }; //class ResidualDijkstra
   1.216 +
   1.217 +  private:
   1.218 +
   1.219 +    // The digraph the algorithm runs on
   1.220 +    const Digraph &_graph;
   1.221 +    // The length map
   1.222 +    const LengthMap &_length;
   1.223 +
   1.224 +    // Arc map of the current flow
   1.225 +    FlowMap *_flow;
   1.226 +    bool _local_flow;
   1.227 +    // Node map of the current potentials
   1.228 +    PotentialMap *_potential;
   1.229 +    bool _local_potential;
   1.230 +
   1.231 +    // The source node
   1.232 +    Node _source;
   1.233 +    // The target node
   1.234 +    Node _target;
   1.235 +
   1.236 +    // Container to store the found paths
   1.237 +    std::vector< SimplePath<Digraph> > paths;
   1.238 +    int _path_num;
   1.239 +
   1.240 +    // The pred arc map
   1.241 +    PredMap _pred;
   1.242 +    // Implementation of the Dijkstra algorithm for finding augmenting
   1.243 +    // shortest paths in the residual network
   1.244 +    ResidualDijkstra *_dijkstra;
   1.245 +
   1.246 +  public:
   1.247 +
   1.248 +    /// \brief Constructor.
   1.249 +    ///
   1.250 +    /// Constructor.
   1.251 +    ///
   1.252 +    /// \param graph The digraph the algorithm runs on.
   1.253 +    /// \param length The length (cost) values of the arcs.
   1.254 +    Suurballe( const Digraph &graph,
   1.255 +               const LengthMap &length ) :
   1.256 +      _graph(graph), _length(length), _flow(0), _local_flow(false),
   1.257 +      _potential(0), _local_potential(false), _pred(graph)
   1.258 +    {
   1.259 +      LEMON_ASSERT(std::numeric_limits<Length>::is_integer,
   1.260 +        "The length type of Suurballe must be integer");
   1.261 +    }
   1.262 +
   1.263 +    /// Destructor.
   1.264 +    ~Suurballe() {
   1.265 +      if (_local_flow) delete _flow;
   1.266 +      if (_local_potential) delete _potential;
   1.267 +      delete _dijkstra;
   1.268 +    }
   1.269 +
   1.270 +    /// \brief Set the flow map.
   1.271 +    ///
   1.272 +    /// This function sets the flow map.
   1.273 +    /// If it is not used before calling \ref run() or \ref init(),
   1.274 +    /// an instance will be allocated automatically. The destructor
   1.275 +    /// deallocates this automatically allocated map, of course.
   1.276 +    ///
   1.277 +    /// The found flow contains only 0 and 1 values, since it is the
   1.278 +    /// union of the found arc-disjoint paths.
   1.279 +    ///
   1.280 +    /// \return <tt>(*this)</tt>
   1.281 +    Suurballe& flowMap(FlowMap &map) {
   1.282 +      if (_local_flow) {
   1.283 +        delete _flow;
   1.284 +        _local_flow = false;
   1.285 +      }
   1.286 +      _flow = &map;
   1.287 +      return *this;
   1.288 +    }
   1.289 +
   1.290 +    /// \brief Set the potential map.
   1.291 +    ///
   1.292 +    /// This function sets the potential map.
   1.293 +    /// If it is not used before calling \ref run() or \ref init(),
   1.294 +    /// an instance will be allocated automatically. The destructor
   1.295 +    /// deallocates this automatically allocated map, of course.
   1.296 +    ///
   1.297 +    /// The node potentials provide the dual solution of the underlying
   1.298 +    /// \ref min_cost_flow "minimum cost flow problem".
   1.299 +    ///
   1.300 +    /// \return <tt>(*this)</tt>
   1.301 +    Suurballe& potentialMap(PotentialMap &map) {
   1.302 +      if (_local_potential) {
   1.303 +        delete _potential;
   1.304 +        _local_potential = false;
   1.305 +      }
   1.306 +      _potential = &map;
   1.307 +      return *this;
   1.308 +    }
   1.309 +
   1.310 +    /// \name Execution Control
   1.311 +    /// The simplest way to execute the algorithm is to call the run()
   1.312 +    /// function.
   1.313 +    /// \n
   1.314 +    /// If you only need the flow that is the union of the found
   1.315 +    /// arc-disjoint paths, you may call init() and findFlow().
   1.316 +
   1.317 +    /// @{
   1.318 +
   1.319 +    /// \brief Run the algorithm.
   1.320 +    ///
   1.321 +    /// This function runs the algorithm.
   1.322 +    ///
   1.323 +    /// \param s The source node.
   1.324 +    /// \param t The target node.
   1.325 +    /// \param k The number of paths to be found.
   1.326 +    ///
   1.327 +    /// \return \c k if there are at least \c k arc-disjoint paths from
   1.328 +    /// \c s to \c t in the digraph. Otherwise it returns the number of
   1.329 +    /// arc-disjoint paths found.
   1.330 +    ///
   1.331 +    /// \note Apart from the return value, <tt>s.run(s, t, k)</tt> is
   1.332 +    /// just a shortcut of the following code.
   1.333 +    /// \code
   1.334 +    ///   s.init(s);
   1.335 +    ///   s.findFlow(t, k);
   1.336 +    ///   s.findPaths();
   1.337 +    /// \endcode
   1.338 +    int run(const Node& s, const Node& t, int k = 2) {
   1.339 +      init(s);
   1.340 +      findFlow(t, k);
   1.341 +      findPaths();
   1.342 +      return _path_num;
   1.343 +    }
   1.344 +
   1.345 +    /// \brief Initialize the algorithm.
   1.346 +    ///
   1.347 +    /// This function initializes the algorithm.
   1.348 +    ///
   1.349 +    /// \param s The source node.
   1.350 +    void init(const Node& s) {
   1.351 +      _source = s;
   1.352 +
   1.353 +      // Initialize maps
   1.354 +      if (!_flow) {
   1.355 +        _flow = new FlowMap(_graph);
   1.356 +        _local_flow = true;
   1.357 +      }
   1.358 +      if (!_potential) {
   1.359 +        _potential = new PotentialMap(_graph);
   1.360 +        _local_potential = true;
   1.361 +      }
   1.362 +      for (ArcIt e(_graph); e != INVALID; ++e) (*_flow)[e] = 0;
   1.363 +      for (NodeIt n(_graph); n != INVALID; ++n) (*_potential)[n] = 0;
   1.364 +    }
   1.365 +
   1.366 +    /// \brief Execute the algorithm to find an optimal flow.
   1.367 +    ///
   1.368 +    /// This function executes the successive shortest path algorithm to
   1.369 +    /// find a minimum cost flow, which is the union of \c k (or less)
   1.370 +    /// arc-disjoint paths.
   1.371 +    ///
   1.372 +    /// \param t The target node.
   1.373 +    /// \param k The number of paths to be found.
   1.374 +    ///
   1.375 +    /// \return \c k if there are at least \c k arc-disjoint paths from
   1.376 +    /// the source node to the given node \c t in the digraph.
   1.377 +    /// Otherwise it returns the number of arc-disjoint paths found.
   1.378 +    ///
   1.379 +    /// \pre \ref init() must be called before using this function.
   1.380 +    int findFlow(const Node& t, int k = 2) {
   1.381 +      _target = t;
   1.382 +      _dijkstra =
   1.383 +        new ResidualDijkstra( _graph, *_flow, _length, *_potential, _pred,
   1.384 +                              _source, _target );
   1.385 +
   1.386 +      // Find shortest paths
   1.387 +      _path_num = 0;
   1.388 +      while (_path_num < k) {
   1.389 +        // Run Dijkstra
   1.390 +        if (!_dijkstra->run()) break;
   1.391 +        ++_path_num;
   1.392 +
   1.393 +        // Set the flow along the found shortest path
   1.394 +        Node u = _target;
   1.395 +        Arc e;
   1.396 +        while ((e = _pred[u]) != INVALID) {
   1.397 +          if (u == _graph.target(e)) {
   1.398 +            (*_flow)[e] = 1;
   1.399 +            u = _graph.source(e);
   1.400 +          } else {
   1.401 +            (*_flow)[e] = 0;
   1.402 +            u = _graph.target(e);
   1.403 +          }
   1.404 +        }
   1.405 +      }
   1.406 +      return _path_num;
   1.407 +    }
   1.408 +
   1.409 +    /// \brief Compute the paths from the flow.
   1.410 +    ///
   1.411 +    /// This function computes the paths from the found minimum cost flow,
   1.412 +    /// which is the union of some arc-disjoint paths.
   1.413 +    ///
   1.414 +    /// \pre \ref init() and \ref findFlow() must be called before using
   1.415 +    /// this function.
   1.416 +    void findPaths() {
   1.417 +      FlowMap res_flow(_graph);
   1.418 +      for(ArcIt a(_graph); a != INVALID; ++a) res_flow[a] = (*_flow)[a];
   1.419 +
   1.420 +      paths.clear();
   1.421 +      paths.resize(_path_num);
   1.422 +      for (int i = 0; i < _path_num; ++i) {
   1.423 +        Node n = _source;
   1.424 +        while (n != _target) {
   1.425 +          OutArcIt e(_graph, n);
   1.426 +          for ( ; res_flow[e] == 0; ++e) ;
   1.427 +          n = _graph.target(e);
   1.428 +          paths[i].addBack(e);
   1.429 +          res_flow[e] = 0;
   1.430 +        }
   1.431 +      }
   1.432 +    }
   1.433 +
   1.434 +    /// @}
   1.435 +
   1.436 +    /// \name Query Functions
   1.437 +    /// The results of the algorithm can be obtained using these
   1.438 +    /// functions.
   1.439 +    /// \n The algorithm should be executed before using them.
   1.440 +
   1.441 +    /// @{
   1.442 +
   1.443 +    /// \brief Return the total length of the found paths.
   1.444 +    ///
   1.445 +    /// This function returns the total length of the found paths, i.e.
   1.446 +    /// the total cost of the found flow.
   1.447 +    /// The complexity of the function is O(e).
   1.448 +    ///
   1.449 +    /// \pre \ref run() or \ref findFlow() must be called before using
   1.450 +    /// this function.
   1.451 +    Length totalLength() const {
   1.452 +      Length c = 0;
   1.453 +      for (ArcIt e(_graph); e != INVALID; ++e)
   1.454 +        c += (*_flow)[e] * _length[e];
   1.455 +      return c;
   1.456 +    }
   1.457 +
   1.458 +    /// \brief Return the flow value on the given arc.
   1.459 +    ///
   1.460 +    /// This function returns the flow value on the given arc.
   1.461 +    /// It is \c 1 if the arc is involved in one of the found arc-disjoint
   1.462 +    /// paths, otherwise it is \c 0.
   1.463 +    ///
   1.464 +    /// \pre \ref run() or \ref findFlow() must be called before using
   1.465 +    /// this function.
   1.466 +    int flow(const Arc& arc) const {
   1.467 +      return (*_flow)[arc];
   1.468 +    }
   1.469 +
   1.470 +    /// \brief Return a const reference to an arc map storing the
   1.471 +    /// found flow.
   1.472 +    ///
   1.473 +    /// This function returns a const reference to an arc map storing
   1.474 +    /// the flow that is the union of the found arc-disjoint paths.
   1.475 +    ///
   1.476 +    /// \pre \ref run() or \ref findFlow() must be called before using
   1.477 +    /// this function.
   1.478 +    const FlowMap& flowMap() const {
   1.479 +      return *_flow;
   1.480 +    }
   1.481 +
   1.482 +    /// \brief Return the potential of the given node.
   1.483 +    ///
   1.484 +    /// This function returns the potential of the given node.
   1.485 +    /// The node potentials provide the dual solution of the
   1.486 +    /// underlying \ref min_cost_flow "minimum cost flow problem".
   1.487 +    ///
   1.488 +    /// \pre \ref run() or \ref findFlow() must be called before using
   1.489 +    /// this function.
   1.490 +    Length potential(const Node& node) const {
   1.491 +      return (*_potential)[node];
   1.492 +    }
   1.493 +
   1.494 +    /// \brief Return a const reference to a node map storing the
   1.495 +    /// found potentials (the dual solution).
   1.496 +    ///
   1.497 +    /// This function returns a const reference to a node map storing
   1.498 +    /// the found potentials that provide the dual solution of the
   1.499 +    /// underlying \ref min_cost_flow "minimum cost flow problem".
   1.500 +    ///
   1.501 +    /// \pre \ref run() or \ref findFlow() must be called before using
   1.502 +    /// this function.
   1.503 +    const PotentialMap& potentialMap() const {
   1.504 +      return *_potential;
   1.505 +    }
   1.506 +
   1.507 +    /// \brief Return the number of the found paths.
   1.508 +    ///
   1.509 +    /// This function returns the number of the found paths.
   1.510 +    ///
   1.511 +    /// \pre \ref run() or \ref findFlow() must be called before using
   1.512 +    /// this function.
   1.513 +    int pathNum() const {
   1.514 +      return _path_num;
   1.515 +    }
   1.516 +
   1.517 +    /// \brief Return a const reference to the specified path.
   1.518 +    ///
   1.519 +    /// This function returns a const reference to the specified path.
   1.520 +    ///
   1.521 +    /// \param i The function returns the <tt>i</tt>-th path.
   1.522 +    /// \c i must be between \c 0 and <tt>%pathNum()-1</tt>.
   1.523 +    ///
   1.524 +    /// \pre \ref run() or \ref findPaths() must be called before using
   1.525 +    /// this function.
   1.526 +    Path path(int i) const {
   1.527 +      return paths[i];
   1.528 +    }
   1.529 +
   1.530 +    /// @}
   1.531 +
   1.532 +  }; //class Suurballe
   1.533 +
   1.534 +  ///@}
   1.535 +
   1.536 +} //namespace lemon
   1.537 +
   1.538 +#endif //LEMON_SUURBALLE_H