1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
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/tolerance.h>
23 #include <lemon/elevator.h>
27 /// \brief Implementation of the preflow algorithm.
31 /// \brief Default traits class of Preflow class.
33 /// Default traits class of Preflow class.
34 /// \tparam GR Digraph type.
35 /// \tparam CAP Capacity map type.
36 template <typename GR, typename CAP>
37 struct PreflowDefaultTraits {
39 /// \brief The type of the digraph 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 elevator type used by Preflow algorithm.
72 /// The elevator type used by Preflow algorithm.
74 /// \sa Elevator, LinkedElevator
76 typedef lemon::Elevator<GR, GR::Node> Elevator;
78 typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
81 /// \brief Instantiates an Elevator.
83 /// This function instantiates an \ref Elevator.
84 /// \param digraph The digraph for which we would like to define
86 /// \param max_level The maximum level of the elevator.
87 static Elevator* createElevator(const Digraph& digraph, int max_level) {
88 return new Elevator(digraph, max_level);
91 /// \brief The tolerance used by the algorithm
93 /// The tolerance used by the algorithm to handle inexact computation.
94 typedef lemon::Tolerance<Value> Tolerance;
101 /// \brief %Preflow algorithm class.
103 /// This class provides an implementation of Goldberg-Tarjan's \e preflow
104 /// \e push-relabel algorithm producing a \ref max_flow
105 /// "flow of maximum value" in a digraph \ref clrs01algorithms,
106 /// \ref amo93networkflows, \ref goldberg88newapproach.
107 /// The preflow algorithms are the fastest known maximum
108 /// flow algorithms. The current implementation uses a mixture of the
109 /// \e "highest label" and the \e "bound decrease" heuristics.
110 /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
112 /// The algorithm consists of two phases. After the first phase
113 /// the maximum flow value and the minimum cut is obtained. The
114 /// second phase constructs a feasible maximum flow on each arc.
116 /// \tparam GR The type of the digraph the algorithm runs on.
117 /// \tparam CAP The type of the capacity map. The default map
118 /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
120 template <typename GR, typename CAP, typename TR>
122 template <typename GR,
123 typename CAP = typename GR::template ArcMap<int>,
124 typename TR = PreflowDefaultTraits<GR, CAP> >
129 ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
131 ///The type of the digraph the algorithm runs on.
132 typedef typename Traits::Digraph Digraph;
133 ///The type of the capacity map.
134 typedef typename Traits::CapacityMap CapacityMap;
135 ///The type of the flow values.
136 typedef typename Traits::Value Value;
138 ///The type of the flow map.
139 typedef typename Traits::FlowMap FlowMap;
140 ///The type of the elevator.
141 typedef typename Traits::Elevator Elevator;
142 ///The type of the tolerance.
143 typedef typename Traits::Tolerance Tolerance;
147 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
149 const Digraph& _graph;
150 const CapacityMap* _capacity;
154 Node _source, _target;
162 typedef typename Digraph::template NodeMap<Value> ExcessMap;
165 Tolerance _tolerance;
170 void createStructures() {
171 _node_num = countNodes(_graph);
174 _flow = Traits::createFlowMap(_graph);
178 _level = Traits::createElevator(_graph, _node_num);
182 _excess = new ExcessMap(_graph);
186 void destroyStructures() {
200 typedef Preflow Create;
202 ///\name Named Template Parameters
206 template <typename T>
207 struct SetFlowMapTraits : public Traits {
209 static FlowMap *createFlowMap(const Digraph&) {
210 LEMON_ASSERT(false, "FlowMap is not initialized");
211 return 0; // ignore warnings
215 /// \brief \ref named-templ-param "Named parameter" for setting
218 /// \ref named-templ-param "Named parameter" for setting FlowMap
220 template <typename T>
222 : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
223 typedef Preflow<Digraph, CapacityMap,
224 SetFlowMapTraits<T> > Create;
227 template <typename T>
228 struct SetElevatorTraits : public Traits {
230 static Elevator *createElevator(const Digraph&, int) {
231 LEMON_ASSERT(false, "Elevator is not initialized");
232 return 0; // ignore warnings
236 /// \brief \ref named-templ-param "Named parameter" for setting
239 /// \ref named-templ-param "Named parameter" for setting Elevator
240 /// type. If this named parameter is used, then an external
241 /// elevator object must be passed to the algorithm using the
242 /// \ref elevator(Elevator&) "elevator()" function before calling
243 /// \ref run() or \ref init().
244 /// \sa SetStandardElevator
245 template <typename T>
247 : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
248 typedef Preflow<Digraph, CapacityMap,
249 SetElevatorTraits<T> > Create;
252 template <typename T>
253 struct SetStandardElevatorTraits : public Traits {
255 static Elevator *createElevator(const Digraph& digraph, int max_level) {
256 return new Elevator(digraph, max_level);
260 /// \brief \ref named-templ-param "Named parameter" for setting
261 /// Elevator type with automatic allocation
263 /// \ref named-templ-param "Named parameter" for setting Elevator
264 /// type with automatic allocation.
265 /// The Elevator should have standard constructor interface to be
266 /// able to automatically created by the algorithm (i.e. the
267 /// digraph and the maximum level should be passed to it).
268 /// However, an external elevator object could also be passed to the
269 /// algorithm with the \ref elevator(Elevator&) "elevator()" function
270 /// before calling \ref run() or \ref init().
272 template <typename T>
273 struct SetStandardElevator
274 : public Preflow<Digraph, CapacityMap,
275 SetStandardElevatorTraits<T> > {
276 typedef Preflow<Digraph, CapacityMap,
277 SetStandardElevatorTraits<T> > Create;
289 /// \brief The constructor of the class.
291 /// The constructor of the class.
292 /// \param digraph The digraph the algorithm runs on.
293 /// \param capacity The capacity of the arcs.
294 /// \param source The source node.
295 /// \param target The target node.
296 Preflow(const Digraph& digraph, const CapacityMap& capacity,
297 Node source, Node target)
298 : _graph(digraph), _capacity(&capacity),
299 _node_num(0), _source(source), _target(target),
300 _flow(0), _local_flow(false),
301 _level(0), _local_level(false),
302 _excess(0), _tolerance(), _phase() {}
304 /// \brief Destructor.
311 /// \brief Sets the capacity map.
313 /// Sets the capacity map.
314 /// \return <tt>(*this)</tt>
315 Preflow& capacityMap(const CapacityMap& map) {
320 /// \brief Sets the flow map.
322 /// Sets the flow map.
323 /// If you don't use this function before calling \ref run() or
324 /// \ref init(), an instance will be allocated automatically.
325 /// The destructor deallocates this automatically allocated map,
327 /// \return <tt>(*this)</tt>
328 Preflow& flowMap(FlowMap& map) {
337 /// \brief Sets the source node.
339 /// Sets the source node.
340 /// \return <tt>(*this)</tt>
341 Preflow& source(const Node& node) {
346 /// \brief Sets the target node.
348 /// Sets the target node.
349 /// \return <tt>(*this)</tt>
350 Preflow& target(const Node& node) {
355 /// \brief Sets the elevator used by algorithm.
357 /// Sets the elevator used by algorithm.
358 /// If you don't use this function before calling \ref run() or
359 /// \ref init(), an instance will be allocated automatically.
360 /// The destructor deallocates this automatically allocated elevator,
362 /// \return <tt>(*this)</tt>
363 Preflow& elevator(Elevator& elevator) {
366 _local_level = false;
372 /// \brief Returns a const reference to the elevator.
374 /// Returns a const reference to the elevator.
376 /// \pre Either \ref run() or \ref init() must be called before
377 /// using this function.
378 const Elevator& elevator() const {
382 /// \brief Sets the tolerance used by the algorithm.
384 /// Sets the tolerance object used by the algorithm.
385 /// \return <tt>(*this)</tt>
386 Preflow& tolerance(const Tolerance& tolerance) {
387 _tolerance = tolerance;
391 /// \brief Returns a const reference to the tolerance.
393 /// Returns a const reference to the tolerance object used by
395 const Tolerance& tolerance() const {
399 /// \name Execution Control
400 /// The simplest way to execute the preflow algorithm is to use
401 /// \ref run() or \ref runMinCut().\n
402 /// If you need better control on the initial solution or the execution,
403 /// you have to call one of the \ref init() functions first, then
404 /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
408 /// \brief Initializes the internal data structures.
410 /// Initializes the internal data structures and sets the initial
411 /// flow to zero on each arc.
416 for (NodeIt n(_graph); n != INVALID; ++n) {
420 for (ArcIt e(_graph); e != INVALID; ++e) {
424 typename Digraph::template NodeMap<bool> reached(_graph, false);
427 _level->initAddItem(_target);
429 std::vector<Node> queue;
430 reached[_source] = true;
432 queue.push_back(_target);
433 reached[_target] = true;
434 while (!queue.empty()) {
435 _level->initNewLevel();
436 std::vector<Node> nqueue;
437 for (int i = 0; i < int(queue.size()); ++i) {
439 for (InArcIt e(_graph, n); e != INVALID; ++e) {
440 Node u = _graph.source(e);
441 if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
443 _level->initAddItem(u);
450 _level->initFinish();
452 for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
453 if (_tolerance.positive((*_capacity)[e])) {
454 Node u = _graph.target(e);
455 if ((*_level)[u] == _level->maxLevel()) continue;
456 _flow->set(e, (*_capacity)[e]);
457 (*_excess)[u] += (*_capacity)[e];
458 if (u != _target && !_level->active(u)) {
465 /// \brief Initializes the internal data structures using the
468 /// Initializes the internal data structures and sets the initial
469 /// flow to the given \c flowMap. The \c flowMap should contain a
470 /// flow or at least a preflow, i.e. at each node excluding the
471 /// source node the incoming flow should greater or equal to the
473 /// \return \c false if the given \c flowMap is not a preflow.
474 template <typename FlowMap>
475 bool init(const FlowMap& flowMap) {
478 for (ArcIt e(_graph); e != INVALID; ++e) {
479 _flow->set(e, flowMap[e]);
482 for (NodeIt n(_graph); n != INVALID; ++n) {
484 for (InArcIt e(_graph, n); e != INVALID; ++e) {
485 excess += (*_flow)[e];
487 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
488 excess -= (*_flow)[e];
490 if (excess < 0 && n != _source) return false;
491 (*_excess)[n] = excess;
494 typename Digraph::template NodeMap<bool> reached(_graph, false);
497 _level->initAddItem(_target);
499 std::vector<Node> queue;
500 reached[_source] = true;
502 queue.push_back(_target);
503 reached[_target] = true;
504 while (!queue.empty()) {
505 _level->initNewLevel();
506 std::vector<Node> nqueue;
507 for (int i = 0; i < int(queue.size()); ++i) {
509 for (InArcIt e(_graph, n); e != INVALID; ++e) {
510 Node u = _graph.source(e);
512 _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
514 _level->initAddItem(u);
518 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
519 Node v = _graph.target(e);
520 if (!reached[v] && _tolerance.positive((*_flow)[e])) {
522 _level->initAddItem(v);
529 _level->initFinish();
531 for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
532 Value rem = (*_capacity)[e] - (*_flow)[e];
533 if (_tolerance.positive(rem)) {
534 Node u = _graph.target(e);
535 if ((*_level)[u] == _level->maxLevel()) continue;
536 _flow->set(e, (*_capacity)[e]);
537 (*_excess)[u] += rem;
538 if (u != _target && !_level->active(u)) {
543 for (InArcIt e(_graph, _source); e != INVALID; ++e) {
544 Value rem = (*_flow)[e];
545 if (_tolerance.positive(rem)) {
546 Node v = _graph.source(e);
547 if ((*_level)[v] == _level->maxLevel()) continue;
549 (*_excess)[v] += rem;
550 if (v != _target && !_level->active(v)) {
558 /// \brief Starts the first phase of the preflow algorithm.
560 /// The preflow algorithm consists of two phases, this method runs
561 /// the first phase. After the first phase the maximum flow value
562 /// and a minimum value cut can already be computed, although a
563 /// maximum flow is not yet obtained. So after calling this method
564 /// \ref flowValue() returns the value of a maximum flow and \ref
565 /// minCut() returns a minimum cut.
566 /// \pre One of the \ref init() functions must be called before
567 /// using this function.
568 void startFirstPhase() {
571 Node n = _level->highestActive();
572 int level = _level->highestActiveLevel();
573 while (n != INVALID) {
576 while (num > 0 && n != INVALID) {
577 Value excess = (*_excess)[n];
578 int new_level = _level->maxLevel();
580 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
581 Value rem = (*_capacity)[e] - (*_flow)[e];
582 if (!_tolerance.positive(rem)) continue;
583 Node v = _graph.target(e);
584 if ((*_level)[v] < level) {
585 if (!_level->active(v) && v != _target) {
588 if (!_tolerance.less(rem, excess)) {
589 _flow->set(e, (*_flow)[e] + excess);
590 (*_excess)[v] += excess;
595 (*_excess)[v] += rem;
596 _flow->set(e, (*_capacity)[e]);
598 } else if (new_level > (*_level)[v]) {
599 new_level = (*_level)[v];
603 for (InArcIt e(_graph, n); e != INVALID; ++e) {
604 Value rem = (*_flow)[e];
605 if (!_tolerance.positive(rem)) continue;
606 Node v = _graph.source(e);
607 if ((*_level)[v] < level) {
608 if (!_level->active(v) && v != _target) {
611 if (!_tolerance.less(rem, excess)) {
612 _flow->set(e, (*_flow)[e] - excess);
613 (*_excess)[v] += excess;
618 (*_excess)[v] += rem;
621 } else if (new_level > (*_level)[v]) {
622 new_level = (*_level)[v];
628 (*_excess)[n] = excess;
631 if (new_level + 1 < _level->maxLevel()) {
632 _level->liftHighestActive(new_level + 1);
634 _level->liftHighestActiveToTop();
636 if (_level->emptyLevel(level)) {
637 _level->liftToTop(level);
640 _level->deactivate(n);
643 n = _level->highestActive();
644 level = _level->highestActiveLevel();
648 num = _node_num * 20;
649 while (num > 0 && n != INVALID) {
650 Value excess = (*_excess)[n];
651 int new_level = _level->maxLevel();
653 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
654 Value rem = (*_capacity)[e] - (*_flow)[e];
655 if (!_tolerance.positive(rem)) continue;
656 Node v = _graph.target(e);
657 if ((*_level)[v] < level) {
658 if (!_level->active(v) && v != _target) {
661 if (!_tolerance.less(rem, excess)) {
662 _flow->set(e, (*_flow)[e] + excess);
663 (*_excess)[v] += excess;
668 (*_excess)[v] += rem;
669 _flow->set(e, (*_capacity)[e]);
671 } else if (new_level > (*_level)[v]) {
672 new_level = (*_level)[v];
676 for (InArcIt e(_graph, n); e != INVALID; ++e) {
677 Value rem = (*_flow)[e];
678 if (!_tolerance.positive(rem)) continue;
679 Node v = _graph.source(e);
680 if ((*_level)[v] < level) {
681 if (!_level->active(v) && v != _target) {
684 if (!_tolerance.less(rem, excess)) {
685 _flow->set(e, (*_flow)[e] - excess);
686 (*_excess)[v] += excess;
691 (*_excess)[v] += rem;
694 } else if (new_level > (*_level)[v]) {
695 new_level = (*_level)[v];
701 (*_excess)[n] = excess;
704 if (new_level + 1 < _level->maxLevel()) {
705 _level->liftActiveOn(level, new_level + 1);
707 _level->liftActiveToTop(level);
709 if (_level->emptyLevel(level)) {
710 _level->liftToTop(level);
713 _level->deactivate(n);
716 while (level >= 0 && _level->activeFree(level)) {
720 n = _level->highestActive();
721 level = _level->highestActiveLevel();
723 n = _level->activeOn(level);
730 /// \brief Starts the second phase of the preflow algorithm.
732 /// The preflow algorithm consists of two phases, this method runs
733 /// the second phase. After calling one of the \ref init() functions
734 /// and \ref startFirstPhase() and then \ref startSecondPhase(),
735 /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
736 /// value of a maximum flow, \ref minCut() returns a minimum cut
737 /// \pre One of the \ref init() functions and \ref startFirstPhase()
738 /// must be called before using this function.
739 void startSecondPhase() {
742 typename Digraph::template NodeMap<bool> reached(_graph);
743 for (NodeIt n(_graph); n != INVALID; ++n) {
744 reached[n] = (*_level)[n] < _level->maxLevel();
748 _level->initAddItem(_source);
750 std::vector<Node> queue;
751 queue.push_back(_source);
752 reached[_source] = true;
754 while (!queue.empty()) {
755 _level->initNewLevel();
756 std::vector<Node> nqueue;
757 for (int i = 0; i < int(queue.size()); ++i) {
759 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
760 Node v = _graph.target(e);
761 if (!reached[v] && _tolerance.positive((*_flow)[e])) {
763 _level->initAddItem(v);
767 for (InArcIt e(_graph, n); e != INVALID; ++e) {
768 Node u = _graph.source(e);
770 _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
772 _level->initAddItem(u);
779 _level->initFinish();
781 for (NodeIt n(_graph); n != INVALID; ++n) {
783 _level->dirtyTopButOne(n);
784 } else if ((*_excess)[n] > 0 && _target != n) {
790 while ((n = _level->highestActive()) != INVALID) {
791 Value excess = (*_excess)[n];
792 int level = _level->highestActiveLevel();
793 int new_level = _level->maxLevel();
795 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
796 Value rem = (*_capacity)[e] - (*_flow)[e];
797 if (!_tolerance.positive(rem)) continue;
798 Node v = _graph.target(e);
799 if ((*_level)[v] < level) {
800 if (!_level->active(v) && v != _source) {
803 if (!_tolerance.less(rem, excess)) {
804 _flow->set(e, (*_flow)[e] + excess);
805 (*_excess)[v] += excess;
810 (*_excess)[v] += rem;
811 _flow->set(e, (*_capacity)[e]);
813 } else if (new_level > (*_level)[v]) {
814 new_level = (*_level)[v];
818 for (InArcIt e(_graph, n); e != INVALID; ++e) {
819 Value rem = (*_flow)[e];
820 if (!_tolerance.positive(rem)) continue;
821 Node v = _graph.source(e);
822 if ((*_level)[v] < level) {
823 if (!_level->active(v) && v != _source) {
826 if (!_tolerance.less(rem, excess)) {
827 _flow->set(e, (*_flow)[e] - excess);
828 (*_excess)[v] += excess;
833 (*_excess)[v] += rem;
836 } else if (new_level > (*_level)[v]) {
837 new_level = (*_level)[v];
843 (*_excess)[n] = excess;
846 if (new_level + 1 < _level->maxLevel()) {
847 _level->liftHighestActive(new_level + 1);
850 _level->liftHighestActiveToTop();
852 if (_level->emptyLevel(level)) {
854 _level->liftToTop(level);
857 _level->deactivate(n);
863 /// \brief Runs the preflow algorithm.
865 /// Runs the preflow algorithm.
866 /// \note pf.run() is just a shortcut of the following code.
869 /// pf.startFirstPhase();
870 /// pf.startSecondPhase();
878 /// \brief Runs the preflow algorithm to compute the minimum cut.
880 /// Runs the preflow algorithm to compute the minimum cut.
881 /// \note pf.runMinCut() is just a shortcut of the following code.
884 /// pf.startFirstPhase();
893 /// \name Query Functions
894 /// The results of the preflow algorithm can be obtained using these
896 /// Either one of the \ref run() "run*()" functions or one of the
897 /// \ref startFirstPhase() "start*()" functions should be called
898 /// before using them.
902 /// \brief Returns the value of the maximum flow.
904 /// Returns the value of the maximum flow by returning the excess
905 /// of the target node. This value equals to the value of
906 /// the maximum flow already after the first phase of the algorithm.
908 /// \pre Either \ref run() or \ref init() must be called before
909 /// using this function.
910 Value flowValue() const {
911 return (*_excess)[_target];
914 /// \brief Returns the flow value on the given arc.
916 /// Returns the flow value on the given arc. This method can
917 /// be called after the second phase of the algorithm.
919 /// \pre Either \ref run() or \ref init() must be called before
920 /// using this function.
921 Value flow(const Arc& arc) const {
922 return (*_flow)[arc];
925 /// \brief Returns a const reference to the flow map.
927 /// Returns a const reference to the arc map storing the found flow.
928 /// This method can be called after the second phase of the algorithm.
930 /// \pre Either \ref run() or \ref init() must be called before
931 /// using this function.
932 const FlowMap& flowMap() const {
936 /// \brief Returns \c true when the node is on the source side of the
939 /// Returns true when the node is on the source side of the found
940 /// minimum cut. This method can be called both after running \ref
941 /// startFirstPhase() and \ref startSecondPhase().
943 /// \pre Either \ref run() or \ref init() must be called before
944 /// using this function.
945 bool minCut(const Node& node) const {
946 return ((*_level)[node] == _level->maxLevel()) == _phase;
949 /// \brief Gives back a minimum value cut.
951 /// Sets \c cutMap to the characteristic vector of a minimum value
952 /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
953 /// node map with \c bool (or convertible) value type.
955 /// This method can be called both after running \ref startFirstPhase()
956 /// and \ref startSecondPhase(). The result after the second phase
957 /// could be slightly different if inexact computation is used.
959 /// \note This function calls \ref minCut() for each node, so it runs in
962 /// \pre Either \ref run() or \ref init() must be called before
963 /// using this function.
964 template <typename CutMap>
965 void minCutMap(CutMap& cutMap) const {
966 for (NodeIt n(_graph); n != INVALID; ++n) {
967 cutMap.set(n, minCut(n));