3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2007
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_PREFLOW_H
20 #define LEMON_PREFLOW_H
22 #include <lemon/error.h>
23 #include <lemon/bits/invalid.h>
24 #include <lemon/tolerance.h>
25 #include <lemon/maps.h>
26 #include <lemon/graph_utils.h>
27 #include <lemon/elevator.h>
31 /// \brief Implementation of the preflow algorithm.
35 /// \brief Default traits class of Preflow class.
37 /// Default traits class of Preflow class.
38 /// \param _Graph Graph type.
39 /// \param _CapacityMap Type of capacity map.
40 template <typename _Graph, typename _CapacityMap>
41 struct PreflowDefaultTraits {
43 /// \brief The graph type the algorithm runs on.
46 /// \brief The type of the map that stores the edge capacities.
48 /// The type of the map that stores the edge capacities.
49 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
50 typedef _CapacityMap CapacityMap;
52 /// \brief The type of the length of the edges.
53 typedef typename CapacityMap::Value Value;
55 /// \brief The map type that stores the flow values.
57 /// The map type that stores the flow values.
58 /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
59 typedef typename Graph::template EdgeMap<Value> FlowMap;
61 /// \brief Instantiates a FlowMap.
63 /// This function instantiates a \ref FlowMap.
64 /// \param graph The graph, to which we would like to define the flow map.
65 static FlowMap* createFlowMap(const Graph& graph) {
66 return new FlowMap(graph);
69 /// \brief The eleavator type used by Preflow algorithm.
71 /// The elevator type used by Preflow algorithm.
74 /// \sa LinkedElevator
75 typedef LinkedElevator<Graph, typename Graph::Node> Elevator;
77 /// \brief Instantiates an Elevator.
79 /// This function instantiates a \ref Elevator.
80 /// \param graph The graph, to which we would like to define the elevator.
81 /// \param max_level The maximum level of the elevator.
82 static Elevator* createElevator(const Graph& graph, int max_level) {
83 return new Elevator(graph, max_level);
86 /// \brief The tolerance used by the algorithm
88 /// The tolerance used by the algorithm to handle inexact computation.
89 typedef Tolerance<Value> Tolerance;
96 /// \brief %Preflow algorithms class.
98 /// This class provides an implementation of the Goldberg's \e
99 /// preflow \e algorithm producing a flow of maximum value in a
100 /// directed graph. The preflow algorithms are the fastest known max
101 /// flow algorithms. The current implementation use a mixture of the
102 /// \e "highest label" and the \e "bound decrease" heuristics.
103 /// The worst case time complexity of the algorithm is \f$O(n^3)\f$.
105 /// The algorithm consists from two phases. After the first phase
106 /// the maximal flow value and the minimum cut can be obtained. The
107 /// second phase constructs the feasible maximum flow on each edge.
109 /// \param _Graph The directed graph type the algorithm runs on.
110 /// \param _CapacityMap The flow map type.
111 /// \param _Traits Traits class to set various data types used by
112 /// the algorithm. The default traits class is \ref
113 /// PreflowDefaultTraits. See \ref PreflowDefaultTraits for the
114 /// documentation of a %Preflow traits class.
116 ///\author Jacint Szabo and Balazs Dezso
118 template <typename _Graph, typename _CapacityMap, typename _Traits>
120 template <typename _Graph,
121 typename _CapacityMap = typename _Graph::template EdgeMap<int>,
122 typename _Traits = PreflowDefaultTraits<_Graph, _CapacityMap> >
127 typedef _Traits Traits;
128 typedef typename Traits::Graph Graph;
129 typedef typename Traits::CapacityMap CapacityMap;
130 typedef typename Traits::Value Value;
132 typedef typename Traits::FlowMap FlowMap;
133 typedef typename Traits::Elevator Elevator;
134 typedef typename Traits::Tolerance Tolerance;
136 /// \brief \ref Exception for uninitialized parameters.
138 /// This error represents problems in the initialization
139 /// of the parameters of the algorithms.
140 class UninitializedParameter : public lemon::UninitializedParameter {
142 virtual const char* what() const throw() {
143 return "lemon::Preflow::UninitializedParameter";
149 GRAPH_TYPEDEFS(typename Graph);
152 const CapacityMap* _capacity;
156 Node _source, _target;
164 typedef typename Graph::template NodeMap<Value> ExcessMap;
167 Tolerance _tolerance;
171 void createStructures() {
172 _node_num = countNodes(_graph);
175 _flow = Traits::createFlowMap(_graph);
179 _level = Traits::createElevator(_graph, _node_num);
183 _excess = new ExcessMap(_graph);
187 void destroyStructures() {
201 typedef Preflow Create;
203 ///\name Named template parameters
207 template <typename _FlowMap>
208 struct DefFlowMapTraits : public Traits {
209 typedef _FlowMap FlowMap;
210 static FlowMap *createFlowMap(const Graph&) {
211 throw UninitializedParameter();
215 /// \brief \ref named-templ-param "Named parameter" for setting
218 /// \ref named-templ-param "Named parameter" for setting FlowMap
220 template <typename _FlowMap>
222 : public Preflow<Graph, CapacityMap, DefFlowMapTraits<_FlowMap> > {
223 typedef Preflow<Graph, CapacityMap, DefFlowMapTraits<_FlowMap> > Create;
226 template <typename _Elevator>
227 struct DefElevatorTraits : public Traits {
228 typedef _Elevator Elevator;
229 static Elevator *createElevator(const Graph&, int) {
230 throw UninitializedParameter();
234 /// \brief \ref named-templ-param "Named parameter" for setting
237 /// \ref named-templ-param "Named parameter" for setting Elevator
239 template <typename _Elevator>
241 : public Preflow<Graph, CapacityMap, DefElevatorTraits<_Elevator> > {
242 typedef Preflow<Graph, CapacityMap, DefElevatorTraits<_Elevator> > Create;
245 template <typename _Elevator>
246 struct DefStandardElevatorTraits : public Traits {
247 typedef _Elevator Elevator;
248 static Elevator *createElevator(const Graph& graph, int max_level) {
249 return new Elevator(graph, max_level);
253 /// \brief \ref named-templ-param "Named parameter" for setting
256 /// \ref named-templ-param "Named parameter" for setting Elevator
257 /// type. The Elevator should be standard constructor interface, ie.
258 /// the graph and the maximum level should be passed to it.
259 template <typename _Elevator>
260 struct DefStandardElevator
261 : public Preflow<Graph, CapacityMap,
262 DefStandardElevatorTraits<_Elevator> > {
263 typedef Preflow<Graph, CapacityMap,
264 DefStandardElevatorTraits<_Elevator> > Create;
269 /// \brief The constructor of the class.
271 /// The constructor of the class.
272 /// \param graph The directed graph the algorithm runs on.
273 /// \param capacity The capacity of the edges.
274 /// \param source The source node.
275 /// \param target The target node.
276 Preflow(const Graph& graph, const CapacityMap& capacity,
277 Node source, Node target)
278 : _graph(graph), _capacity(&capacity),
279 _node_num(0), _source(source), _target(target),
280 _flow(0), _local_flow(false),
281 _level(0), _local_level(false),
282 _excess(0), _tolerance(), _phase() {}
284 /// \brief Destrcutor.
291 /// \brief Sets the capacity map.
293 /// Sets the capacity map.
294 /// \return \c (*this)
295 Preflow& capacityMap(const CapacityMap& map) {
300 /// \brief Sets the flow map.
302 /// Sets the flow map.
303 /// \return \c (*this)
304 Preflow& flowMap(FlowMap& map) {
313 /// \brief Returns the flow map.
315 /// \return The flow map.
316 const FlowMap& flowMap() {
320 /// \brief Sets the elevator.
322 /// Sets the elevator.
323 /// \return \c (*this)
324 Preflow& elevator(Elevator& elevator) {
327 _local_level = false;
333 /// \brief Returns the elevator.
335 /// \return The elevator.
336 const Elevator& elevator() {
340 /// \brief Sets the source node.
342 /// Sets the source node.
343 /// \return \c (*this)
344 Preflow& source(const Node& node) {
349 /// \brief Sets the target node.
351 /// Sets the target node.
352 /// \return \c (*this)
353 Preflow& target(const Node& node) {
358 /// \brief Sets the tolerance used by algorithm.
360 /// Sets the tolerance used by algorithm.
361 Preflow& tolerance(const Tolerance& tolerance) const {
362 _tolerance = tolerance;
366 /// \brief Returns the tolerance used by algorithm.
368 /// Returns the tolerance used by algorithm.
369 const Tolerance& tolerance() const {
373 /// \name Execution control The simplest way to execute the
374 /// algorithm is to use one of the member functions called \c
377 /// If you need more control on initial solution or
378 /// execution then you have to call one \ref init() function and then
379 /// the startFirstPhase() and if you need the startSecondPhase().
383 /// \brief Initializes the internal data structures.
385 /// Initializes the internal data structures.
391 for (NodeIt n(_graph); n != INVALID; ++n) {
395 for (EdgeIt e(_graph); e != INVALID; ++e) {
399 typename Graph::template NodeMap<bool> reached(_graph, false);
402 _level->initAddItem(_target);
404 std::vector<Node> queue;
405 reached.set(_source, true);
407 queue.push_back(_target);
408 reached.set(_target, true);
409 while (!queue.empty()) {
410 std::vector<Node> nqueue;
411 for (int i = 0; i < int(queue.size()); ++i) {
413 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
414 Node u = _graph.source(e);
415 if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
416 reached.set(u, true);
417 _level->initAddItem(u);
424 _level->initFinish();
426 for (OutEdgeIt e(_graph, _source); e != INVALID; ++e) {
427 if (_tolerance.positive((*_capacity)[e])) {
428 Node u = _graph.target(e);
429 if ((*_level)[u] == _level->maxLevel()) continue;
430 _flow->set(e, (*_capacity)[e]);
431 _excess->set(u, (*_excess)[u] + (*_capacity)[e]);
432 if (u != _target && !_level->active(u)) {
439 /// \brief Initializes the internal data structures.
441 /// Initializes the internal data structures and sets the initial
442 /// flow to the given \c flowMap. The \c flowMap should contain a
443 /// flow or at least a preflow, ie. in each node excluding the
444 /// target the incoming flow should greater or equal to the
446 /// \return %False when the given \c flowMap is not a preflow.
447 template <typename FlowMap>
448 bool flowInit(const FlowMap& flowMap) {
451 for (EdgeIt e(_graph); e != INVALID; ++e) {
452 _flow->set(e, flowMap[e]);
455 for (NodeIt n(_graph); n != INVALID; ++n) {
457 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
458 excess += (*_flow)[e];
460 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
461 excess -= (*_flow)[e];
463 if (excess < 0 && n != _source) return false;
464 _excess->set(n, excess);
467 typename Graph::template NodeMap<bool> reached(_graph, false);
470 _level->initAddItem(_target);
472 std::vector<Node> queue;
473 reached.set(_source, true);
475 queue.push_back(_target);
476 reached.set(_target, true);
477 while (!queue.empty()) {
478 _level->initNewLevel();
479 std::vector<Node> nqueue;
480 for (int i = 0; i < int(queue.size()); ++i) {
482 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
483 Node u = _graph.source(e);
485 _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
486 reached.set(u, true);
487 _level->initAddItem(u);
491 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
492 Node v = _graph.target(e);
493 if (!reached[v] && _tolerance.positive((*_flow)[e])) {
494 reached.set(v, true);
495 _level->initAddItem(v);
502 _level->initFinish();
504 for (OutEdgeIt e(_graph, _source); e != INVALID; ++e) {
505 Value rem = (*_capacity)[e] - (*_flow)[e];
506 if (_tolerance.positive(rem)) {
507 Node u = _graph.target(e);
508 if ((*_level)[u] == _level->maxLevel()) continue;
509 _flow->set(e, (*_capacity)[e]);
510 _excess->set(u, (*_excess)[u] + rem);
511 if (u != _target && !_level->active(u)) {
516 for (InEdgeIt e(_graph, _source); e != INVALID; ++e) {
517 Value rem = (*_flow)[e];
518 if (_tolerance.positive(rem)) {
519 Node v = _graph.source(e);
520 if ((*_level)[v] == _level->maxLevel()) continue;
522 _excess->set(v, (*_excess)[v] + rem);
523 if (v != _target && !_level->active(v)) {
531 /// \brief Starts the first phase of the preflow algorithm.
533 /// The preflow algorithm consists of two phases, this method runs
534 /// the first phase. After the first phase the maximum flow value
535 /// and a minimum value cut can already be computed, although a
536 /// maximum flow is not yet obtained. So after calling this method
537 /// \ref flowValue() returns the value of a maximum flow and \ref
538 /// minCut() returns a minimum cut.
539 /// \pre One of the \ref init() functions should be called.
540 void startFirstPhase() {
543 Node n = _level->highestActive();
544 int level = _level->highestActiveLevel();
545 while (n != INVALID) {
548 while (num > 0 && n != INVALID) {
549 Value excess = (*_excess)[n];
550 int new_level = _level->maxLevel();
552 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
553 Value rem = (*_capacity)[e] - (*_flow)[e];
554 if (!_tolerance.positive(rem)) continue;
555 Node v = _graph.target(e);
556 if ((*_level)[v] < level) {
557 if (!_level->active(v) && v != _target) {
560 if (!_tolerance.less(rem, excess)) {
561 _flow->set(e, (*_flow)[e] + excess);
562 _excess->set(v, (*_excess)[v] + excess);
567 _excess->set(v, (*_excess)[v] + rem);
568 _flow->set(e, (*_capacity)[e]);
570 } else if (new_level > (*_level)[v]) {
571 new_level = (*_level)[v];
575 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
576 Value rem = (*_flow)[e];
577 if (!_tolerance.positive(rem)) continue;
578 Node v = _graph.source(e);
579 if ((*_level)[v] < level) {
580 if (!_level->active(v) && v != _target) {
583 if (!_tolerance.less(rem, excess)) {
584 _flow->set(e, (*_flow)[e] - excess);
585 _excess->set(v, (*_excess)[v] + excess);
590 _excess->set(v, (*_excess)[v] + rem);
593 } else if (new_level > (*_level)[v]) {
594 new_level = (*_level)[v];
600 _excess->set(n, excess);
603 if (new_level + 1 < _level->maxLevel()) {
604 _level->liftHighestActive(new_level + 1);
606 _level->liftHighestActiveToTop();
608 if (_level->emptyLevel(level)) {
609 _level->liftToTop(level);
612 _level->deactivate(n);
615 n = _level->highestActive();
616 level = _level->highestActiveLevel();
620 num = _node_num * 20;
621 while (num > 0 && n != INVALID) {
622 Value excess = (*_excess)[n];
623 int new_level = _level->maxLevel();
625 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
626 Value rem = (*_capacity)[e] - (*_flow)[e];
627 if (!_tolerance.positive(rem)) continue;
628 Node v = _graph.target(e);
629 if ((*_level)[v] < level) {
630 if (!_level->active(v) && v != _target) {
633 if (!_tolerance.less(rem, excess)) {
634 _flow->set(e, (*_flow)[e] + excess);
635 _excess->set(v, (*_excess)[v] + excess);
640 _excess->set(v, (*_excess)[v] + rem);
641 _flow->set(e, (*_capacity)[e]);
643 } else if (new_level > (*_level)[v]) {
644 new_level = (*_level)[v];
648 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
649 Value rem = (*_flow)[e];
650 if (!_tolerance.positive(rem)) continue;
651 Node v = _graph.source(e);
652 if ((*_level)[v] < level) {
653 if (!_level->active(v) && v != _target) {
656 if (!_tolerance.less(rem, excess)) {
657 _flow->set(e, (*_flow)[e] - excess);
658 _excess->set(v, (*_excess)[v] + excess);
663 _excess->set(v, (*_excess)[v] + rem);
666 } else if (new_level > (*_level)[v]) {
667 new_level = (*_level)[v];
673 _excess->set(n, excess);
676 if (new_level + 1 < _level->maxLevel()) {
677 _level->liftActiveOn(level, new_level + 1);
679 _level->liftActiveToTop(level);
681 if (_level->emptyLevel(level)) {
682 _level->liftToTop(level);
685 _level->deactivate(n);
688 while (level >= 0 && _level->activeFree(level)) {
692 n = _level->highestActive();
693 level = _level->highestActiveLevel();
695 n = _level->activeOn(level);
702 /// \brief Starts the second phase of the preflow algorithm.
704 /// The preflow algorithm consists of two phases, this method runs
705 /// the second phase. After calling \ref init() and \ref
706 /// startFirstPhase() and then \ref startSecondPhase(), \ref
707 /// flowMap() return a maximum flow, \ref flowValue() returns the
708 /// value of a maximum flow, \ref minCut() returns a minimum cut
709 /// \pre The \ref init() and startFirstPhase() functions should be
711 void startSecondPhase() {
714 typename Graph::template NodeMap<bool> reached(_graph);
715 for (NodeIt n(_graph); n != INVALID; ++n) {
716 reached.set(n, (*_level)[n] < _level->maxLevel());
720 _level->initAddItem(_source);
722 std::vector<Node> queue;
723 queue.push_back(_source);
724 reached.set(_source, true);
726 while (!queue.empty()) {
727 _level->initNewLevel();
728 std::vector<Node> nqueue;
729 for (int i = 0; i < int(queue.size()); ++i) {
731 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
732 Node v = _graph.target(e);
733 if (!reached[v] && _tolerance.positive((*_flow)[e])) {
734 reached.set(v, true);
735 _level->initAddItem(v);
739 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
740 Node u = _graph.source(e);
742 _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
743 reached.set(u, true);
744 _level->initAddItem(u);
751 _level->initFinish();
753 for (NodeIt n(_graph); n != INVALID; ++n) {
755 _level->markToBottom(n);
756 } else if ((*_excess)[n] > 0 && _target != n) {
762 while ((n = _level->highestActive()) != INVALID) {
763 Value excess = (*_excess)[n];
764 int level = _level->highestActiveLevel();
765 int new_level = _level->maxLevel();
767 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
768 Value rem = (*_capacity)[e] - (*_flow)[e];
769 if (!_tolerance.positive(rem)) continue;
770 Node v = _graph.target(e);
771 if ((*_level)[v] < level) {
772 if (!_level->active(v) && v != _source) {
775 if (!_tolerance.less(rem, excess)) {
776 _flow->set(e, (*_flow)[e] + excess);
777 _excess->set(v, (*_excess)[v] + excess);
782 _excess->set(v, (*_excess)[v] + rem);
783 _flow->set(e, (*_capacity)[e]);
785 } else if (new_level > (*_level)[v]) {
786 new_level = (*_level)[v];
790 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
791 Value rem = (*_flow)[e];
792 if (!_tolerance.positive(rem)) continue;
793 Node v = _graph.source(e);
794 if ((*_level)[v] < level) {
795 if (!_level->active(v) && v != _source) {
798 if (!_tolerance.less(rem, excess)) {
799 _flow->set(e, (*_flow)[e] - excess);
800 _excess->set(v, (*_excess)[v] + excess);
805 _excess->set(v, (*_excess)[v] + rem);
808 } else if (new_level > (*_level)[v]) {
809 new_level = (*_level)[v];
815 _excess->set(n, excess);
818 if (new_level + 1 < _level->maxLevel()) {
819 _level->liftHighestActive(new_level + 1);
822 _level->liftHighestActiveToTop();
824 if (_level->emptyLevel(level)) {
826 _level->liftToTop(level);
829 _level->deactivate(n);
835 /// \brief Runs the preflow algorithm.
837 /// Runs the preflow algorithm.
838 /// \note pf.run() is just a shortcut of the following code.
841 /// pf.startFirstPhase();
842 /// pf.startSecondPhase();
850 /// \brief Runs the preflow algorithm to compute the minimum cut.
852 /// Runs the preflow algorithm to compute the minimum cut.
853 /// \note pf.runMinCut() is just a shortcut of the following code.
856 /// pf.startFirstPhase();
865 /// \name Query Functions
866 /// The result of the %Dijkstra algorithm can be obtained using these
868 /// Before the use of these functions,
869 /// either run() or start() must be called.
873 /// \brief Returns the value of the maximum flow.
875 /// Returns the value of the maximum flow by returning the excess
876 /// of the target node \c t. This value equals to the value of
877 /// the maximum flow already after the first phase.
878 Value flowValue() const {
879 return (*_excess)[_target];
882 /// \brief Returns true when the node is on the source side of minimum cut.
884 /// Returns true when the node is on the source side of minimum
885 /// cut. This method can be called both after running \ref
886 /// startFirstPhase() and \ref startSecondPhase().
887 bool minCut(const Node& node) const {
888 return ((*_level)[node] == _level->maxLevel()) == _phase;
891 /// \brief Returns a minimum value cut.
893 /// Sets the \c cutMap to the characteristic vector of a minimum value
894 /// cut. This method can be called both after running \ref
895 /// startFirstPhase() and \ref startSecondPhase(). The result after second
896 /// phase could be changed slightly if inexact computation is used.
897 /// \pre The \c cutMap should be a bool-valued node-map.
898 template <typename CutMap>
899 void minCutMap(CutMap& cutMap) const {
900 for (NodeIt n(_graph); n != INVALID; ++n) {
901 cutMap.set(n, minCut(n));
905 /// \brief Returns the flow on the edge.
907 /// Sets the \c flowMap to the flow on the edges. This method can
908 /// be called after the second phase of algorithm.
909 Value flow(const Edge& edge) const {
910 return (*_flow)[edge];