1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_EDMONDS_KARP_H
20 #define LEMON_EDMONDS_KARP_H
24 /// \brief Implementation of the Edmonds-Karp algorithm.
26 #include <lemon/tolerance.h>
31 /// \brief Default traits class of EdmondsKarp class.
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 {
39 /// \brief The digraph type the algorithm runs on.
42 /// \brief The type of the map that stores the arc capacities.
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;
48 /// \brief The type of the flow values.
49 typedef typename CapacityMap::Value Value;
51 /// \brief The type of the map that stores the flow values.
53 /// The type of the map that stores the flow values.
54 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
56 typedef GR::ArcMap<Value> FlowMap;
58 typedef typename Digraph::template ArcMap<Value> FlowMap;
61 /// \brief Instantiates a FlowMap.
63 /// This function instantiates a \ref FlowMap.
64 /// \param digraph The digraph for which we would like to define
66 static FlowMap* createFlowMap(const Digraph& digraph) {
67 return new FlowMap(digraph);
70 /// \brief The tolerance used by the algorithm
72 /// The tolerance used by the algorithm to handle inexact computation.
73 typedef lemon::Tolerance<Value> Tolerance;
79 /// \brief Edmonds-Karp algorithms class.
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 \cite clrs01algorithms, \cite amo93networkflows,
84 /// \cite 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.
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.
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.
106 template <typename GR, typename CAP, typename TR>
108 template <typename GR,
109 typename CAP = typename GR::template ArcMap<int>,
110 typename TR = EdmondsKarpDefaultTraits<GR, CAP> >
115 /// \brief The \ref lemon::EdmondsKarpDefaultTraits "traits class"
116 /// of the algorithm.
118 /// The type of the digraph the algorithm runs on.
119 typedef typename Traits::Digraph Digraph;
120 /// The type of the capacity map.
121 typedef typename Traits::CapacityMap CapacityMap;
122 /// The type of the flow values.
123 typedef typename Traits::Value Value;
125 /// The type of the flow map.
126 typedef typename Traits::FlowMap FlowMap;
127 /// The type of the tolerance.
128 typedef typename Traits::Tolerance Tolerance;
132 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
133 typedef typename Digraph::template NodeMap<Arc> PredMap;
135 const Digraph& _graph;
136 const CapacityMap* _capacity;
138 Node _source, _target;
144 std::vector<Node> _queue;
146 Tolerance _tolerance;
149 void createStructures() {
151 _flow = Traits::createFlowMap(_graph);
155 _pred = new PredMap(_graph);
157 _queue.resize(countNodes(_graph));
160 void destroyStructures() {
171 typedef EdmondsKarp Create;
173 ///\name Named template parameters
177 template <typename T>
178 struct SetFlowMapTraits : public Traits {
180 static FlowMap *createFlowMap(const Digraph&) {
181 LEMON_ASSERT(false, "FlowMap is not initialized");
186 /// \brief \ref named-templ-param "Named parameter" for setting
189 /// \ref named-templ-param "Named parameter" for setting FlowMap
191 template <typename T>
193 : public EdmondsKarp<Digraph, CapacityMap, SetFlowMapTraits<T> > {
194 typedef EdmondsKarp<Digraph, CapacityMap, SetFlowMapTraits<T> > Create;
205 /// \brief The constructor of the class.
207 /// The constructor of the class.
208 /// \param digraph The digraph the algorithm runs on.
209 /// \param capacity The capacity of the arcs.
210 /// \param source The source node.
211 /// \param target The target node.
212 EdmondsKarp(const Digraph& digraph, const CapacityMap& capacity,
213 Node source, Node target)
214 : _graph(digraph), _capacity(&capacity), _source(source), _target(target),
215 _flow(0), _local_flow(false), _pred(0), _tolerance(), _flow_value()
217 LEMON_ASSERT(_source != _target,
218 "Flow source and target are the same nodes.");
221 /// \brief Destructor.
228 /// \brief Sets the capacity map.
230 /// Sets the capacity map.
231 /// \return <tt>(*this)</tt>
232 EdmondsKarp& capacityMap(const CapacityMap& map) {
237 /// \brief Sets the flow map.
239 /// Sets the flow map.
240 /// If you don't use this function before calling \ref run() or
241 /// \ref init(), an instance will be allocated automatically.
242 /// The destructor deallocates this automatically allocated map,
244 /// \return <tt>(*this)</tt>
245 EdmondsKarp& flowMap(FlowMap& map) {
254 /// \brief Sets the source node.
256 /// Sets the source node.
257 /// \return <tt>(*this)</tt>
258 EdmondsKarp& source(const Node& node) {
263 /// \brief Sets the target node.
265 /// Sets the target node.
266 /// \return <tt>(*this)</tt>
267 EdmondsKarp& target(const Node& node) {
272 /// \brief Sets the tolerance used by algorithm.
274 /// Sets the tolerance used by algorithm.
275 /// \return <tt>(*this)</tt>
276 EdmondsKarp& tolerance(const Tolerance& tolerance) {
277 _tolerance = tolerance;
281 /// \brief Returns a const reference to the tolerance.
283 /// Returns a const reference to the tolerance object used by
285 const Tolerance& tolerance() const {
289 /// \name Execution control
290 /// The simplest way to execute the algorithm is to use \ref run().\n
291 /// If you need better control on the initial solution or the execution,
292 /// you have to call one of the \ref init() functions first, then
293 /// \ref start() or multiple times the \ref augment() function.
297 /// \brief Initializes the algorithm.
299 /// Initializes the internal data structures and sets the initial
300 /// flow to zero on each arc.
303 for (ArcIt it(_graph); it != INVALID; ++it) {
309 /// \brief Initializes the algorithm using the given flow map.
311 /// Initializes the internal data structures and sets the initial
312 /// flow to the given \c flowMap. The \c flowMap should
313 /// contain a feasible flow, i.e. at each node excluding the source
314 /// and the target, the incoming flow should be equal to the
316 template <typename FlowMap>
317 void init(const FlowMap& flowMap) {
319 for (ArcIt e(_graph); e != INVALID; ++e) {
320 _flow->set(e, flowMap[e]);
323 for (OutArcIt jt(_graph, _source); jt != INVALID; ++jt) {
324 _flow_value += (*_flow)[jt];
326 for (InArcIt jt(_graph, _source); jt != INVALID; ++jt) {
327 _flow_value -= (*_flow)[jt];
331 /// \brief Initializes the algorithm using the given flow map.
333 /// Initializes the internal data structures and sets the initial
334 /// flow to the given \c flowMap. The \c flowMap should
335 /// contain a feasible flow, i.e. at each node excluding the source
336 /// and the target, the incoming flow should be equal to the
338 /// \return \c false when the given \c flowMap does not contain a
340 template <typename FlowMap>
341 bool checkedInit(const FlowMap& flowMap) {
343 for (ArcIt e(_graph); e != INVALID; ++e) {
344 _flow->set(e, flowMap[e]);
346 for (NodeIt it(_graph); it != INVALID; ++it) {
347 if (it == _source || it == _target) continue;
349 for (OutArcIt jt(_graph, it); jt != INVALID; ++jt) {
350 outFlow += (*_flow)[jt];
353 for (InArcIt jt(_graph, it); jt != INVALID; ++jt) {
354 inFlow += (*_flow)[jt];
356 if (_tolerance.different(outFlow, inFlow)) {
360 for (ArcIt it(_graph); it != INVALID; ++it) {
361 if (_tolerance.less((*_flow)[it], 0)) return false;
362 if (_tolerance.less((*_capacity)[it], (*_flow)[it])) return false;
365 for (OutArcIt jt(_graph, _source); jt != INVALID; ++jt) {
366 _flow_value += (*_flow)[jt];
368 for (InArcIt jt(_graph, _source); jt != INVALID; ++jt) {
369 _flow_value -= (*_flow)[jt];
374 /// \brief Augments the solution along a shortest path.
376 /// Augments the solution along a shortest path. This function searches a
377 /// shortest path between the source and the target
378 /// in the residual digraph by the Bfs algoritm.
379 /// Then it increases the flow on this path with the minimal residual
380 /// capacity on the path. If there is no such path, it gives back
382 /// \return \c false when the augmenting did not success, i.e. the
383 /// current flow is a feasible and optimal solution.
385 for (NodeIt n(_graph); n != INVALID; ++n) {
386 _pred->set(n, INVALID);
389 int first = 0, last = 1;
392 _pred->set(_source, OutArcIt(_graph, _source));
394 while (first != last && (*_pred)[_target] == INVALID) {
395 Node n = _queue[first++];
397 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
398 Value rem = (*_capacity)[e] - (*_flow)[e];
399 Node t = _graph.target(e);
400 if (_tolerance.positive(rem) && (*_pred)[t] == INVALID) {
405 for (InArcIt e(_graph, n); e != INVALID; ++e) {
406 Value rem = (*_flow)[e];
407 Node t = _graph.source(e);
408 if (_tolerance.positive(rem) && (*_pred)[t] == INVALID) {
415 if ((*_pred)[_target] != INVALID) {
419 Value prem = (*_capacity)[e] - (*_flow)[e];
420 n = _graph.source(e);
421 while (n != _source) {
423 if (_graph.target(e) == n) {
424 Value rem = (*_capacity)[e] - (*_flow)[e];
425 if (rem < prem) prem = rem;
426 n = _graph.source(e);
428 Value rem = (*_flow)[e];
429 if (rem < prem) prem = rem;
430 n = _graph.target(e);
437 _flow->set(e, (*_flow)[e] + prem);
438 n = _graph.source(e);
439 while (n != _source) {
441 if (_graph.target(e) == n) {
442 _flow->set(e, (*_flow)[e] + prem);
443 n = _graph.source(e);
445 _flow->set(e, (*_flow)[e] - prem);
446 n = _graph.target(e);
457 /// \brief Executes the algorithm
459 /// Executes the algorithm by performing augmenting phases until the
460 /// optimal solution is reached.
461 /// \pre One of the \ref init() functions must be called before
462 /// using this function.
467 /// \brief Runs the algorithm.
469 /// Runs the Edmonds-Karp algorithm.
470 /// \note ek.run() is just a shortcut of the following code.
482 /// \name Query Functions
483 /// The result of the Edmonds-Karp algorithm can be obtained using these
485 /// Either \ref run() or \ref start() should be called before using them.
489 /// \brief Returns the value of the maximum flow.
491 /// Returns the value of the maximum flow found by the algorithm.
493 /// \pre Either \ref run() or \ref init() must be called before
494 /// using this function.
495 Value flowValue() const {
499 /// \brief Returns the flow value on the given arc.
501 /// Returns the flow value on the given arc.
503 /// \pre Either \ref run() or \ref init() must be called before
504 /// using this function.
505 Value flow(const Arc& arc) const {
506 return (*_flow)[arc];
509 /// \brief Returns a const reference to the flow map.
511 /// Returns a const reference to the arc map storing the found flow.
513 /// \pre Either \ref run() or \ref init() must be called before
514 /// using this function.
515 const FlowMap& flowMap() const {
519 /// \brief Returns \c true when the node is on the source side of the
522 /// Returns true when the node is on the source side of the found
525 /// \pre Either \ref run() or \ref init() must be called before
526 /// using this function.
527 bool minCut(const Node& node) const {
528 return ((*_pred)[node] != INVALID) || node == _source;
531 /// \brief Gives back a minimum value cut.
533 /// Sets \c cutMap to the characteristic vector of a minimum value
534 /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
535 /// node map with \c bool (or convertible) value type.
537 /// \note This function calls \ref minCut() for each node, so it runs in
540 /// \pre Either \ref run() or \ref init() must be called before
541 /// using this function.
542 template <typename CutMap>
543 void minCutMap(CutMap& cutMap) const {
544 for (NodeIt n(_graph); n != INVALID; ++n) {
545 cutMap.set(n, (*_pred)[n] != INVALID);
547 cutMap.set(_source, true);