lemon/edmonds_karp.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 28 Feb 2013 23:45:39 +0100
changeset 1229 473c71baff72
parent 1228 45befc97b1bc
child 1250 97d978243703
permissions -rw-r--r--
Avoid usage of alternative operator (#177)
     1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library.
     4  *
     5  * Copyright (C) 2003-2010
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     9  * Permission to use, modify and distribute this software is granted
    10  * provided that this copyright notice appears in all copies. For
    11  * precise terms see the accompanying LICENSE file.
    12  *
    13  * This software is provided "AS IS" with no warranty of any kind,
    14  * express or implied, and with no claim as to its suitability for any
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_EDMONDS_KARP_H
    20 #define LEMON_EDMONDS_KARP_H
    21 
    22 /// \file
    23 /// \ingroup max_flow
    24 /// \brief Implementation of the Edmonds-Karp algorithm.
    25 
    26 #include <lemon/tolerance.h>
    27 #include <vector>
    28 
    29 namespace lemon {
    30 
    31   /// \brief Default traits class of EdmondsKarp class.
    32   ///
    33   /// Default traits class of EdmondsKarp class.
    34   /// \param GR Digraph type.
    35   /// \param CAP Type of capacity map.
    36   template <typename GR, typename CAP>
    37   struct EdmondsKarpDefaultTraits {
    38 
    39     /// \brief The digraph type the algorithm runs on. 
    40     typedef GR Digraph;
    41 
    42     /// \brief The type of the map that stores the arc capacities.
    43     ///
    44     /// The type of the map that stores the arc capacities.
    45     /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
    46     typedef CAP CapacityMap;
    47 
    48     /// \brief The type of the flow values.
    49     typedef typename CapacityMap::Value Value;
    50 
    51     /// \brief The type of the map that stores the flow values.
    52     ///
    53     /// The type of the map that stores the flow values.
    54     /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
    55 #ifdef DOXYGEN
    56     typedef GR::ArcMap<Value> FlowMap;
    57 #else
    58     typedef typename Digraph::template ArcMap<Value> FlowMap;
    59 #endif
    60 
    61     /// \brief Instantiates a FlowMap.
    62     ///
    63     /// This function instantiates a \ref FlowMap. 
    64     /// \param digraph The digraph for which we would like to define
    65     /// the flow map.
    66     static FlowMap* createFlowMap(const Digraph& digraph) {
    67       return new FlowMap(digraph);
    68     }
    69 
    70     /// \brief The tolerance used by the algorithm
    71     ///
    72     /// The tolerance used by the algorithm to handle inexact computation.
    73     typedef lemon::Tolerance<Value> Tolerance;
    74 
    75   };
    76 
    77   /// \ingroup max_flow
    78   ///
    79   /// \brief Edmonds-Karp algorithms class.
    80   ///
    81   /// This class provides an implementation of the \e Edmonds-Karp \e
    82   /// algorithm producing a \ref max_flow "flow of maximum value" in a
    83   /// digraph \ref clrs01algorithms, \ref amo93networkflows,
    84   /// \ref edmondskarp72theoretical.
    85   /// The Edmonds-Karp algorithm is slower than the Preflow
    86   /// algorithm, but it has an advantage of the step-by-step execution
    87   /// control with feasible flow solutions. The \e source node, the \e
    88   /// target node, the \e capacity of the arcs and the \e starting \e
    89   /// flow value of the arcs should be passed to the algorithm
    90   /// through the constructor.
    91   ///
    92   /// The time complexity of the algorithm is \f$ O(nm^2) \f$ in
    93   /// worst case. Always try the Preflow algorithm instead of this if
    94   /// you just want to compute the optimal flow.
    95   ///
    96   /// \tparam GR The type of the digraph the algorithm runs on.
    97   /// \tparam CAP The type of the capacity map. The default map
    98   /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>". 
    99   /// \tparam TR The traits class that defines various types used by the
   100   /// algorithm. By default, it is \ref EdmondsKarpDefaultTraits
   101   /// "EdmondsKarpDefaultTraits<GR, CAP>".
   102   /// In most cases, this parameter should not be set directly,
   103   /// consider to use the named template parameters instead.
   104 
   105 #ifdef DOXYGEN
   106   template <typename GR, typename CAP, typename TR>
   107 #else 
   108   template <typename GR,
   109 	    typename CAP = typename GR::template ArcMap<int>,
   110             typename TR = EdmondsKarpDefaultTraits<GR, CAP> >
   111 #endif
   112   class EdmondsKarp {
   113   public:
   114 
   115     /// The \ref EdmondsKarpDefaultTraits "traits class" of the algorithm.
   116     typedef TR Traits;
   117     /// The type of the digraph the algorithm runs on.
   118     typedef typename Traits::Digraph Digraph;
   119     /// The type of the capacity map.
   120     typedef typename Traits::CapacityMap CapacityMap;
   121     /// The type of the flow values.
   122     typedef typename Traits::Value Value; 
   123 
   124     /// The type of the flow map.
   125     typedef typename Traits::FlowMap FlowMap;
   126     /// The type of the tolerance.
   127     typedef typename Traits::Tolerance Tolerance;
   128 
   129   private:
   130 
   131     TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
   132     typedef typename Digraph::template NodeMap<Arc> PredMap;
   133     
   134     const Digraph& _graph;
   135     const CapacityMap* _capacity;
   136 
   137     Node _source, _target;
   138 
   139     FlowMap* _flow;
   140     bool _local_flow;
   141 
   142     PredMap* _pred;
   143     std::vector<Node> _queue;
   144     
   145     Tolerance _tolerance;
   146     Value _flow_value;
   147 
   148     void createStructures() {
   149       if (!_flow) {
   150 	_flow = Traits::createFlowMap(_graph);
   151 	_local_flow = true;
   152       }
   153       if (!_pred) {
   154 	_pred = new PredMap(_graph);
   155       }
   156       _queue.resize(countNodes(_graph));
   157     }
   158 
   159     void destroyStructures() {
   160       if (_local_flow) {
   161 	delete _flow;
   162       }
   163       if (_pred) {
   164 	delete _pred;
   165       }
   166     }
   167     
   168   public:
   169 
   170     typedef EdmondsKarp Create;
   171 
   172     ///\name Named template parameters
   173 
   174     ///@{
   175 
   176     template <typename T>
   177     struct SetFlowMapTraits : public Traits {
   178       typedef T FlowMap;
   179       static FlowMap *createFlowMap(const Digraph&) {
   180 	LEMON_ASSERT(false, "FlowMap is not initialized");
   181         return 0;
   182       }
   183     };
   184 
   185     /// \brief \ref named-templ-param "Named parameter" for setting
   186     /// FlowMap type
   187     ///
   188     /// \ref named-templ-param "Named parameter" for setting FlowMap
   189     /// type
   190     template <typename T>
   191     struct SetFlowMap 
   192       : public EdmondsKarp<Digraph, CapacityMap, SetFlowMapTraits<T> > {
   193       typedef EdmondsKarp<Digraph, CapacityMap, SetFlowMapTraits<T> > Create;
   194     };
   195 
   196     /// @}
   197 
   198   protected:
   199     
   200     EdmondsKarp() {}
   201 
   202   public:
   203 
   204     /// \brief The constructor of the class.
   205     ///
   206     /// The constructor of the class. 
   207     /// \param digraph The digraph the algorithm runs on. 
   208     /// \param capacity The capacity of the arcs. 
   209     /// \param source The source node.
   210     /// \param target The target node.
   211     EdmondsKarp(const Digraph& digraph, const CapacityMap& capacity,
   212 		Node source, Node target)
   213       : _graph(digraph), _capacity(&capacity), _source(source), _target(target),
   214 	_flow(0), _local_flow(false), _pred(0), _tolerance(), _flow_value()
   215     {
   216       LEMON_ASSERT(_source != _target,
   217                    "Flow source and target are the same nodes.");
   218     }
   219 
   220     /// \brief Destructor.
   221     ///
   222     /// Destructor.
   223     ~EdmondsKarp() {
   224       destroyStructures();
   225     }
   226 
   227     /// \brief Sets the capacity map.
   228     ///
   229     /// Sets the capacity map.
   230     /// \return <tt>(*this)</tt>
   231     EdmondsKarp& capacityMap(const CapacityMap& map) {
   232       _capacity = &map;
   233       return *this;
   234     }
   235 
   236     /// \brief Sets the flow map.
   237     ///
   238     /// Sets the flow map.
   239     /// If you don't use this function before calling \ref run() or
   240     /// \ref init(), an instance will be allocated automatically.
   241     /// The destructor deallocates this automatically allocated map,
   242     /// of course.
   243     /// \return <tt>(*this)</tt>
   244     EdmondsKarp& flowMap(FlowMap& map) {
   245       if (_local_flow) {
   246 	delete _flow;
   247 	_local_flow = false;
   248       }
   249       _flow = &map;
   250       return *this;
   251     }
   252 
   253     /// \brief Sets the source node.
   254     ///
   255     /// Sets the source node.
   256     /// \return <tt>(*this)</tt>
   257     EdmondsKarp& source(const Node& node) {
   258       _source = node;
   259       return *this;
   260     }
   261 
   262     /// \brief Sets the target node.
   263     ///
   264     /// Sets the target node.
   265     /// \return <tt>(*this)</tt>
   266     EdmondsKarp& target(const Node& node) {
   267       _target = node;
   268       return *this;
   269     }
   270 
   271     /// \brief Sets the tolerance used by algorithm.
   272     ///
   273     /// Sets the tolerance used by algorithm.
   274     /// \return <tt>(*this)</tt>
   275     EdmondsKarp& tolerance(const Tolerance& tolerance) {
   276       _tolerance = tolerance;
   277       return *this;
   278     } 
   279 
   280     /// \brief Returns a const reference to the tolerance.
   281     ///
   282     /// Returns a const reference to the tolerance object used by
   283     /// the algorithm.
   284     const Tolerance& tolerance() const {
   285       return _tolerance;
   286     } 
   287 
   288     /// \name Execution control
   289     /// The simplest way to execute the algorithm is to use \ref run().\n
   290     /// If you need better control on the initial solution or the execution,
   291     /// you have to call one of the \ref init() functions first, then
   292     /// \ref start() or multiple times the \ref augment() function.
   293     
   294     ///@{
   295 
   296     /// \brief Initializes the algorithm.
   297     ///
   298     /// Initializes the internal data structures and sets the initial
   299     /// flow to zero on each arc.
   300     void init() {
   301       createStructures();
   302       for (ArcIt it(_graph); it != INVALID; ++it) {
   303         _flow->set(it, 0);
   304       }
   305       _flow_value = 0;
   306     }
   307     
   308     /// \brief Initializes the algorithm using the given flow map.
   309     ///
   310     /// Initializes the internal data structures and sets the initial
   311     /// flow to the given \c flowMap. The \c flowMap should
   312     /// contain a feasible flow, i.e. at each node excluding the source
   313     /// and the target, the incoming flow should be equal to the
   314     /// outgoing flow.
   315     template <typename FlowMap>
   316     void init(const FlowMap& flowMap) {
   317       createStructures();
   318       for (ArcIt e(_graph); e != INVALID; ++e) {
   319 	_flow->set(e, flowMap[e]);
   320       }
   321       _flow_value = 0;
   322       for (OutArcIt jt(_graph, _source); jt != INVALID; ++jt) {
   323         _flow_value += (*_flow)[jt];
   324       }
   325       for (InArcIt jt(_graph, _source); jt != INVALID; ++jt) {
   326         _flow_value -= (*_flow)[jt];
   327       }
   328     }
   329 
   330     /// \brief Initializes the algorithm using the given flow map.
   331     ///
   332     /// Initializes the internal data structures and sets the initial
   333     /// flow to the given \c flowMap. The \c flowMap should
   334     /// contain a feasible flow, i.e. at each node excluding the source
   335     /// and the target, the incoming flow should be equal to the
   336     /// outgoing flow. 
   337     /// \return \c false when the given \c flowMap does not contain a
   338     /// feasible flow.
   339     template <typename FlowMap>
   340     bool checkedInit(const FlowMap& flowMap) {
   341       createStructures();
   342       for (ArcIt e(_graph); e != INVALID; ++e) {
   343 	_flow->set(e, flowMap[e]);
   344       }
   345       for (NodeIt it(_graph); it != INVALID; ++it) {
   346         if (it == _source || it == _target) continue;
   347         Value outFlow = 0;
   348         for (OutArcIt jt(_graph, it); jt != INVALID; ++jt) {
   349           outFlow += (*_flow)[jt];
   350         }
   351         Value inFlow = 0;
   352         for (InArcIt jt(_graph, it); jt != INVALID; ++jt) {
   353           inFlow += (*_flow)[jt];
   354         }
   355         if (_tolerance.different(outFlow, inFlow)) {
   356           return false;
   357         }
   358       }
   359       for (ArcIt it(_graph); it != INVALID; ++it) {
   360         if (_tolerance.less((*_flow)[it], 0)) return false;
   361         if (_tolerance.less((*_capacity)[it], (*_flow)[it])) return false;
   362       }
   363       _flow_value = 0;
   364       for (OutArcIt jt(_graph, _source); jt != INVALID; ++jt) {
   365         _flow_value += (*_flow)[jt];
   366       }
   367       for (InArcIt jt(_graph, _source); jt != INVALID; ++jt) {
   368         _flow_value -= (*_flow)[jt];
   369       }
   370       return true;
   371     }
   372 
   373     /// \brief Augments the solution along a shortest path.
   374     /// 
   375     /// Augments the solution along a shortest path. This function searches a
   376     /// shortest path between the source and the target
   377     /// in the residual digraph by the Bfs algoritm.
   378     /// Then it increases the flow on this path with the minimal residual
   379     /// capacity on the path. If there is no such path, it gives back
   380     /// false.
   381     /// \return \c false when the augmenting did not success, i.e. the
   382     /// current flow is a feasible and optimal solution.
   383     bool augment() {
   384       for (NodeIt n(_graph); n != INVALID; ++n) {
   385 	_pred->set(n, INVALID);
   386       }
   387       
   388       int first = 0, last = 1;
   389       
   390       _queue[0] = _source;
   391       _pred->set(_source, OutArcIt(_graph, _source));
   392 
   393       while (first != last && (*_pred)[_target] == INVALID) {
   394 	Node n = _queue[first++];
   395 	
   396 	for (OutArcIt e(_graph, n); e != INVALID; ++e) {
   397 	  Value rem = (*_capacity)[e] - (*_flow)[e];
   398 	  Node t = _graph.target(e);
   399 	  if (_tolerance.positive(rem) && (*_pred)[t] == INVALID) {
   400 	    _pred->set(t, e);
   401 	    _queue[last++] = t;
   402 	  }
   403 	}
   404 	for (InArcIt e(_graph, n); e != INVALID; ++e) {
   405 	  Value rem = (*_flow)[e];
   406 	  Node t = _graph.source(e);
   407 	  if (_tolerance.positive(rem) && (*_pred)[t] == INVALID) {
   408 	    _pred->set(t, e);
   409 	    _queue[last++] = t;
   410 	  }
   411 	}
   412       }
   413 
   414       if ((*_pred)[_target] != INVALID) {
   415 	Node n = _target;
   416 	Arc e = (*_pred)[n];
   417 
   418 	Value prem = (*_capacity)[e] - (*_flow)[e];
   419 	n = _graph.source(e);
   420 	while (n != _source) {
   421 	  e = (*_pred)[n];
   422 	  if (_graph.target(e) == n) {
   423 	    Value rem = (*_capacity)[e] - (*_flow)[e];
   424 	    if (rem < prem) prem = rem;
   425 	    n = _graph.source(e);
   426 	  } else {
   427 	    Value rem = (*_flow)[e];
   428 	    if (rem < prem) prem = rem;
   429 	    n = _graph.target(e);   
   430 	  } 
   431 	}
   432 
   433 	n = _target;
   434 	e = (*_pred)[n];
   435 
   436 	_flow->set(e, (*_flow)[e] + prem);
   437 	n = _graph.source(e);
   438 	while (n != _source) {
   439 	  e = (*_pred)[n];
   440 	  if (_graph.target(e) == n) {
   441 	    _flow->set(e, (*_flow)[e] + prem);
   442 	    n = _graph.source(e);
   443 	  } else {
   444 	    _flow->set(e, (*_flow)[e] - prem);
   445 	    n = _graph.target(e);   
   446 	  } 
   447 	}
   448 
   449 	_flow_value += prem;	
   450 	return true;
   451       } else {
   452 	return false;
   453       }
   454     }
   455 
   456     /// \brief Executes the algorithm
   457     ///
   458     /// Executes the algorithm by performing augmenting phases until the
   459     /// optimal solution is reached. 
   460     /// \pre One of the \ref init() functions must be called before
   461     /// using this function.
   462     void start() {
   463       while (augment()) {}
   464     }
   465 
   466     /// \brief Runs the algorithm.
   467     /// 
   468     /// Runs the Edmonds-Karp algorithm.
   469     /// \note ek.run() is just a shortcut of the following code.
   470     ///\code 
   471     /// ek.init();
   472     /// ek.start();
   473     ///\endcode
   474     void run() {
   475       init();
   476       start();
   477     }
   478 
   479     /// @}
   480 
   481     /// \name Query Functions
   482     /// The result of the Edmonds-Karp algorithm can be obtained using these
   483     /// functions.\n
   484     /// Either \ref run() or \ref start() should be called before using them.
   485     
   486     ///@{
   487 
   488     /// \brief Returns the value of the maximum flow.
   489     ///
   490     /// Returns the value of the maximum flow found by the algorithm.
   491     ///
   492     /// \pre Either \ref run() or \ref init() must be called before
   493     /// using this function.
   494     Value flowValue() const {
   495       return _flow_value;
   496     }
   497 
   498     /// \brief Returns the flow value on the given arc.
   499     ///
   500     /// Returns the flow value on the given arc.
   501     ///
   502     /// \pre Either \ref run() or \ref init() must be called before
   503     /// using this function.
   504     Value flow(const Arc& arc) const {
   505       return (*_flow)[arc];
   506     }
   507 
   508     /// \brief Returns a const reference to the flow map.
   509     ///
   510     /// Returns a const reference to the arc map storing the found flow.
   511     ///
   512     /// \pre Either \ref run() or \ref init() must be called before
   513     /// using this function.
   514     const FlowMap& flowMap() const {
   515       return *_flow;
   516     }
   517 
   518     /// \brief Returns \c true when the node is on the source side of the
   519     /// minimum cut.
   520     ///
   521     /// Returns true when the node is on the source side of the found
   522     /// minimum cut.
   523     ///
   524     /// \pre Either \ref run() or \ref init() must be called before
   525     /// using this function.
   526     bool minCut(const Node& node) const {
   527       return ((*_pred)[node] != INVALID) || node == _source;
   528     }
   529 
   530     /// \brief Gives back a minimum value cut.
   531     ///
   532     /// Sets \c cutMap to the characteristic vector of a minimum value
   533     /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
   534     /// node map with \c bool (or convertible) value type.
   535     ///
   536     /// \note This function calls \ref minCut() for each node, so it runs in
   537     /// O(n) time.
   538     ///
   539     /// \pre Either \ref run() or \ref init() must be called before
   540     /// using this function.
   541     template <typename CutMap>
   542     void minCutMap(CutMap& cutMap) const {
   543       for (NodeIt n(_graph); n != INVALID; ++n) {
   544 	cutMap.set(n, (*_pred)[n] != INVALID);
   545       }
   546       cutMap.set(_source, true);
   547     }    
   548 
   549     /// @}
   550 
   551   };
   552 
   553 }
   554 
   555 #endif