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.
106 /// The preflow algorithms are the fastest known maximum
107 /// flow algorithms. The current implementation uses a mixture of the
108 /// \e "highest label" and the \e "bound decrease" heuristics.
109 /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
111 /// The algorithm consists of two phases. After the first phase
112 /// the maximum flow value and the minimum cut is obtained. The
113 /// second phase constructs a feasible maximum flow on each arc.
115 /// \tparam GR The type of the digraph the algorithm runs on.
116 /// \tparam CAP The type of the capacity map. The default map
117 /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
119 template <typename GR, typename CAP, typename TR>
121 template <typename GR,
122 typename CAP = typename GR::template ArcMap<int>,
123 typename TR = PreflowDefaultTraits<GR, CAP> >
128 ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
130 ///The type of the digraph the algorithm runs on.
131 typedef typename Traits::Digraph Digraph;
132 ///The type of the capacity map.
133 typedef typename Traits::CapacityMap CapacityMap;
134 ///The type of the flow values.
135 typedef typename Traits::Value Value;
137 ///The type of the flow map.
138 typedef typename Traits::FlowMap FlowMap;
139 ///The type of the elevator.
140 typedef typename Traits::Elevator Elevator;
141 ///The type of the tolerance.
142 typedef typename Traits::Tolerance Tolerance;
146 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148 const Digraph& _graph;
149 const CapacityMap* _capacity;
153 Node _source, _target;
161 typedef typename Digraph::template NodeMap<Value> ExcessMap;
164 Tolerance _tolerance;
169 void createStructures() {
170 _node_num = countNodes(_graph);
173 _flow = Traits::createFlowMap(_graph);
177 _level = Traits::createElevator(_graph, _node_num);
181 _excess = new ExcessMap(_graph);
185 void destroyStructures() {
199 typedef Preflow Create;
201 ///\name Named Template Parameters
205 template <typename T>
206 struct SetFlowMapTraits : public Traits {
208 static FlowMap *createFlowMap(const Digraph&) {
209 LEMON_ASSERT(false, "FlowMap is not initialized");
210 return 0; // ignore warnings
214 /// \brief \ref named-templ-param "Named parameter" for setting
217 /// \ref named-templ-param "Named parameter" for setting FlowMap
219 template <typename T>
221 : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
222 typedef Preflow<Digraph, CapacityMap,
223 SetFlowMapTraits<T> > Create;
226 template <typename T>
227 struct SetElevatorTraits : public Traits {
229 static Elevator *createElevator(const Digraph&, int) {
230 LEMON_ASSERT(false, "Elevator is not initialized");
231 return 0; // ignore warnings
235 /// \brief \ref named-templ-param "Named parameter" for setting
238 /// \ref named-templ-param "Named parameter" for setting Elevator
239 /// type. If this named parameter is used, then an external
240 /// elevator object must be passed to the algorithm using the
241 /// \ref elevator(Elevator&) "elevator()" function before calling
242 /// \ref run() or \ref init().
243 /// \sa SetStandardElevator
244 template <typename T>
246 : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
247 typedef Preflow<Digraph, CapacityMap,
248 SetElevatorTraits<T> > Create;
251 template <typename T>
252 struct SetStandardElevatorTraits : public Traits {
254 static Elevator *createElevator(const Digraph& digraph, int max_level) {
255 return new Elevator(digraph, max_level);
259 /// \brief \ref named-templ-param "Named parameter" for setting
260 /// Elevator type with automatic allocation
262 /// \ref named-templ-param "Named parameter" for setting Elevator
263 /// type with automatic allocation.
264 /// The Elevator should have standard constructor interface to be
265 /// able to automatically created by the algorithm (i.e. the
266 /// digraph and the maximum level should be passed to it).
267 /// However an external elevator object could also be passed to the
268 /// algorithm with the \ref elevator(Elevator&) "elevator()" function
269 /// before calling \ref run() or \ref init().
271 template <typename T>
272 struct SetStandardElevator
273 : public Preflow<Digraph, CapacityMap,
274 SetStandardElevatorTraits<T> > {
275 typedef Preflow<Digraph, CapacityMap,
276 SetStandardElevatorTraits<T> > Create;
288 /// \brief The constructor of the class.
290 /// The constructor of the class.
291 /// \param digraph The digraph the algorithm runs on.
292 /// \param capacity The capacity of the arcs.
293 /// \param source The source node.
294 /// \param target The target node.
295 Preflow(const Digraph& digraph, const CapacityMap& capacity,
296 Node source, Node target)
297 : _graph(digraph), _capacity(&capacity),
298 _node_num(0), _source(source), _target(target),
299 _flow(0), _local_flow(false),
300 _level(0), _local_level(false),
301 _excess(0), _tolerance(), _phase() {}
303 /// \brief Destructor.
310 /// \brief Sets the capacity map.
312 /// Sets the capacity map.
313 /// \return <tt>(*this)</tt>
314 Preflow& capacityMap(const CapacityMap& map) {
319 /// \brief Sets the flow map.
321 /// Sets the flow map.
322 /// If you don't use this function before calling \ref run() or
323 /// \ref init(), an instance will be allocated automatically.
324 /// The destructor deallocates this automatically allocated map,
326 /// \return <tt>(*this)</tt>
327 Preflow& flowMap(FlowMap& map) {
336 /// \brief Sets the source node.
338 /// Sets the source node.
339 /// \return <tt>(*this)</tt>
340 Preflow& source(const Node& node) {
345 /// \brief Sets the target node.
347 /// Sets the target node.
348 /// \return <tt>(*this)</tt>
349 Preflow& target(const Node& node) {
354 /// \brief Sets the elevator used by algorithm.
356 /// Sets the elevator used by algorithm.
357 /// If you don't use this function before calling \ref run() or
358 /// \ref init(), an instance will be allocated automatically.
359 /// The destructor deallocates this automatically allocated elevator,
361 /// \return <tt>(*this)</tt>
362 Preflow& elevator(Elevator& elevator) {
365 _local_level = false;
371 /// \brief Returns a const reference to the elevator.
373 /// Returns a const reference to the elevator.
375 /// \pre Either \ref run() or \ref init() must be called before
376 /// using this function.
377 const Elevator& elevator() const {
381 /// \brief Sets the tolerance used by the algorithm.
383 /// Sets the tolerance object used by the algorithm.
384 /// \return <tt>(*this)</tt>
385 Preflow& tolerance(const Tolerance& tolerance) {
386 _tolerance = tolerance;
390 /// \brief Returns a const reference to the tolerance.
392 /// Returns a const reference to the tolerance object used by
394 const Tolerance& tolerance() const {
398 /// \name Execution Control
399 /// The simplest way to execute the preflow algorithm is to use
400 /// \ref run() or \ref runMinCut().\n
401 /// If you need better control on the initial solution or the execution,
402 /// you have to call one of the \ref init() functions first, then
403 /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
407 /// \brief Initializes the internal data structures.
409 /// Initializes the internal data structures and sets the initial
410 /// flow to zero on each arc.
415 for (NodeIt n(_graph); n != INVALID; ++n) {
419 for (ArcIt e(_graph); e != INVALID; ++e) {
423 typename Digraph::template NodeMap<bool> reached(_graph, false);
426 _level->initAddItem(_target);
428 std::vector<Node> queue;
429 reached[_source] = true;
431 queue.push_back(_target);
432 reached[_target] = true;
433 while (!queue.empty()) {
434 _level->initNewLevel();
435 std::vector<Node> nqueue;
436 for (int i = 0; i < int(queue.size()); ++i) {
438 for (InArcIt e(_graph, n); e != INVALID; ++e) {
439 Node u = _graph.source(e);
440 if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
442 _level->initAddItem(u);
449 _level->initFinish();
451 for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
452 if (_tolerance.positive((*_capacity)[e])) {
453 Node u = _graph.target(e);
454 if ((*_level)[u] == _level->maxLevel()) continue;
455 _flow->set(e, (*_capacity)[e]);
456 (*_excess)[u] += (*_capacity)[e];
457 if (u != _target && !_level->active(u)) {
464 /// \brief Initializes the internal data structures using the
467 /// Initializes the internal data structures and sets the initial
468 /// flow to the given \c flowMap. The \c flowMap should contain a
469 /// flow or at least a preflow, i.e. at each node excluding the
470 /// source node the incoming flow should greater or equal to the
472 /// \return \c false if the given \c flowMap is not a preflow.
473 template <typename FlowMap>
474 bool init(const FlowMap& flowMap) {
477 for (ArcIt e(_graph); e != INVALID; ++e) {
478 _flow->set(e, flowMap[e]);
481 for (NodeIt n(_graph); n != INVALID; ++n) {
483 for (InArcIt e(_graph, n); e != INVALID; ++e) {
484 excess += (*_flow)[e];
486 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
487 excess -= (*_flow)[e];
489 if (excess < 0 && n != _source) return false;
490 (*_excess)[n] = excess;
493 typename Digraph::template NodeMap<bool> reached(_graph, false);
496 _level->initAddItem(_target);
498 std::vector<Node> queue;
499 reached[_source] = true;
501 queue.push_back(_target);
502 reached[_target] = true;
503 while (!queue.empty()) {
504 _level->initNewLevel();
505 std::vector<Node> nqueue;
506 for (int i = 0; i < int(queue.size()); ++i) {
508 for (InArcIt e(_graph, n); e != INVALID; ++e) {
509 Node u = _graph.source(e);
511 _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
513 _level->initAddItem(u);
517 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
518 Node v = _graph.target(e);
519 if (!reached[v] && _tolerance.positive((*_flow)[e])) {
521 _level->initAddItem(v);
528 _level->initFinish();
530 for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
531 Value rem = (*_capacity)[e] - (*_flow)[e];
532 if (_tolerance.positive(rem)) {
533 Node u = _graph.target(e);
534 if ((*_level)[u] == _level->maxLevel()) continue;
535 _flow->set(e, (*_capacity)[e]);
536 (*_excess)[u] += rem;
537 if (u != _target && !_level->active(u)) {
542 for (InArcIt e(_graph, _source); e != INVALID; ++e) {
543 Value rem = (*_flow)[e];
544 if (_tolerance.positive(rem)) {
545 Node v = _graph.source(e);
546 if ((*_level)[v] == _level->maxLevel()) continue;
548 (*_excess)[v] += rem;
549 if (v != _target && !_level->active(v)) {
557 /// \brief Starts the first phase of the preflow algorithm.
559 /// The preflow algorithm consists of two phases, this method runs
560 /// the first phase. After the first phase the maximum flow value
561 /// and a minimum value cut can already be computed, although a
562 /// maximum flow is not yet obtained. So after calling this method
563 /// \ref flowValue() returns the value of a maximum flow and \ref
564 /// minCut() returns a minimum cut.
565 /// \pre One of the \ref init() functions must be called before
566 /// using this function.
567 void startFirstPhase() {
570 Node n = _level->highestActive();
571 int level = _level->highestActiveLevel();
572 while (n != INVALID) {
575 while (num > 0 && n != INVALID) {
576 Value excess = (*_excess)[n];
577 int new_level = _level->maxLevel();
579 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
580 Value rem = (*_capacity)[e] - (*_flow)[e];
581 if (!_tolerance.positive(rem)) continue;
582 Node v = _graph.target(e);
583 if ((*_level)[v] < level) {
584 if (!_level->active(v) && v != _target) {
587 if (!_tolerance.less(rem, excess)) {
588 _flow->set(e, (*_flow)[e] + excess);
589 (*_excess)[v] += excess;
594 (*_excess)[v] += rem;
595 _flow->set(e, (*_capacity)[e]);
597 } else if (new_level > (*_level)[v]) {
598 new_level = (*_level)[v];
602 for (InArcIt e(_graph, n); e != INVALID; ++e) {
603 Value rem = (*_flow)[e];
604 if (!_tolerance.positive(rem)) continue;
605 Node v = _graph.source(e);
606 if ((*_level)[v] < level) {
607 if (!_level->active(v) && v != _target) {
610 if (!_tolerance.less(rem, excess)) {
611 _flow->set(e, (*_flow)[e] - excess);
612 (*_excess)[v] += excess;
617 (*_excess)[v] += rem;
620 } else if (new_level > (*_level)[v]) {
621 new_level = (*_level)[v];
627 (*_excess)[n] = excess;
630 if (new_level + 1 < _level->maxLevel()) {
631 _level->liftHighestActive(new_level + 1);
633 _level->liftHighestActiveToTop();
635 if (_level->emptyLevel(level)) {
636 _level->liftToTop(level);
639 _level->deactivate(n);
642 n = _level->highestActive();
643 level = _level->highestActiveLevel();
647 num = _node_num * 20;
648 while (num > 0 && n != INVALID) {
649 Value excess = (*_excess)[n];
650 int new_level = _level->maxLevel();
652 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
653 Value rem = (*_capacity)[e] - (*_flow)[e];
654 if (!_tolerance.positive(rem)) continue;
655 Node v = _graph.target(e);
656 if ((*_level)[v] < level) {
657 if (!_level->active(v) && v != _target) {
660 if (!_tolerance.less(rem, excess)) {
661 _flow->set(e, (*_flow)[e] + excess);
662 (*_excess)[v] += excess;
667 (*_excess)[v] += rem;
668 _flow->set(e, (*_capacity)[e]);
670 } else if (new_level > (*_level)[v]) {
671 new_level = (*_level)[v];
675 for (InArcIt e(_graph, n); e != INVALID; ++e) {
676 Value rem = (*_flow)[e];
677 if (!_tolerance.positive(rem)) continue;
678 Node v = _graph.source(e);
679 if ((*_level)[v] < level) {
680 if (!_level->active(v) && v != _target) {
683 if (!_tolerance.less(rem, excess)) {
684 _flow->set(e, (*_flow)[e] - excess);
685 (*_excess)[v] += excess;
690 (*_excess)[v] += rem;
693 } else if (new_level > (*_level)[v]) {
694 new_level = (*_level)[v];
700 (*_excess)[n] = excess;
703 if (new_level + 1 < _level->maxLevel()) {
704 _level->liftActiveOn(level, new_level + 1);
706 _level->liftActiveToTop(level);
708 if (_level->emptyLevel(level)) {
709 _level->liftToTop(level);
712 _level->deactivate(n);
715 while (level >= 0 && _level->activeFree(level)) {
719 n = _level->highestActive();
720 level = _level->highestActiveLevel();
722 n = _level->activeOn(level);
729 /// \brief Starts the second phase of the preflow algorithm.
731 /// The preflow algorithm consists of two phases, this method runs
732 /// the second phase. After calling one of the \ref init() functions
733 /// and \ref startFirstPhase() and then \ref startSecondPhase(),
734 /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
735 /// value of a maximum flow, \ref minCut() returns a minimum cut
736 /// \pre One of the \ref init() functions and \ref startFirstPhase()
737 /// must be called before using this function.
738 void startSecondPhase() {
741 typename Digraph::template NodeMap<bool> reached(_graph);
742 for (NodeIt n(_graph); n != INVALID; ++n) {
743 reached[n] = (*_level)[n] < _level->maxLevel();
747 _level->initAddItem(_source);
749 std::vector<Node> queue;
750 queue.push_back(_source);
751 reached[_source] = true;
753 while (!queue.empty()) {
754 _level->initNewLevel();
755 std::vector<Node> nqueue;
756 for (int i = 0; i < int(queue.size()); ++i) {
758 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
759 Node v = _graph.target(e);
760 if (!reached[v] && _tolerance.positive((*_flow)[e])) {
762 _level->initAddItem(v);
766 for (InArcIt e(_graph, n); e != INVALID; ++e) {
767 Node u = _graph.source(e);
769 _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
771 _level->initAddItem(u);
778 _level->initFinish();
780 for (NodeIt n(_graph); n != INVALID; ++n) {
782 _level->dirtyTopButOne(n);
783 } else if ((*_excess)[n] > 0 && _target != n) {
789 while ((n = _level->highestActive()) != INVALID) {
790 Value excess = (*_excess)[n];
791 int level = _level->highestActiveLevel();
792 int new_level = _level->maxLevel();
794 for (OutArcIt e(_graph, n); e != INVALID; ++e) {
795 Value rem = (*_capacity)[e] - (*_flow)[e];
796 if (!_tolerance.positive(rem)) continue;
797 Node v = _graph.target(e);
798 if ((*_level)[v] < level) {
799 if (!_level->active(v) && v != _source) {
802 if (!_tolerance.less(rem, excess)) {
803 _flow->set(e, (*_flow)[e] + excess);
804 (*_excess)[v] += excess;
809 (*_excess)[v] += rem;
810 _flow->set(e, (*_capacity)[e]);
812 } else if (new_level > (*_level)[v]) {
813 new_level = (*_level)[v];
817 for (InArcIt e(_graph, n); e != INVALID; ++e) {
818 Value rem = (*_flow)[e];
819 if (!_tolerance.positive(rem)) continue;
820 Node v = _graph.source(e);
821 if ((*_level)[v] < level) {
822 if (!_level->active(v) && v != _source) {
825 if (!_tolerance.less(rem, excess)) {
826 _flow->set(e, (*_flow)[e] - excess);
827 (*_excess)[v] += excess;
832 (*_excess)[v] += rem;
835 } else if (new_level > (*_level)[v]) {
836 new_level = (*_level)[v];
842 (*_excess)[n] = excess;
845 if (new_level + 1 < _level->maxLevel()) {
846 _level->liftHighestActive(new_level + 1);
849 _level->liftHighestActiveToTop();
851 if (_level->emptyLevel(level)) {
853 _level->liftToTop(level);
856 _level->deactivate(n);
862 /// \brief Runs the preflow algorithm.
864 /// Runs the preflow algorithm.
865 /// \note pf.run() is just a shortcut of the following code.
868 /// pf.startFirstPhase();
869 /// pf.startSecondPhase();
877 /// \brief Runs the preflow algorithm to compute the minimum cut.
879 /// Runs the preflow algorithm to compute the minimum cut.
880 /// \note pf.runMinCut() is just a shortcut of the following code.
883 /// pf.startFirstPhase();
892 /// \name Query Functions
893 /// The results of the preflow algorithm can be obtained using these
895 /// Either one of the \ref run() "run*()" functions or one of the
896 /// \ref startFirstPhase() "start*()" functions should be called
897 /// before using them.
901 /// \brief Returns the value of the maximum flow.
903 /// Returns the value of the maximum flow by returning the excess
904 /// of the target node. This value equals to the value of
905 /// the maximum flow already after the first phase of the algorithm.
907 /// \pre Either \ref run() or \ref init() must be called before
908 /// using this function.
909 Value flowValue() const {
910 return (*_excess)[_target];
913 /// \brief Returns the flow value on the given arc.
915 /// Returns the flow value on the given arc. This method can
916 /// be called after the second phase of the algorithm.
918 /// \pre Either \ref run() or \ref init() must be called before
919 /// using this function.
920 Value flow(const Arc& arc) const {
921 return (*_flow)[arc];
924 /// \brief Returns a const reference to the flow map.
926 /// Returns a const reference to the arc map storing the found flow.
927 /// This method can be called after the second phase of the algorithm.
929 /// \pre Either \ref run() or \ref init() must be called before
930 /// using this function.
931 const FlowMap& flowMap() const {
935 /// \brief Returns \c true when the node is on the source side of the
938 /// Returns true when the node is on the source side of the found
939 /// minimum cut. This method can be called both after running \ref
940 /// startFirstPhase() and \ref startSecondPhase().
942 /// \pre Either \ref run() or \ref init() must be called before
943 /// using this function.
944 bool minCut(const Node& node) const {
945 return ((*_level)[node] == _level->maxLevel()) == _phase;
948 /// \brief Gives back a minimum value cut.
950 /// Sets \c cutMap to the characteristic vector of a minimum value
951 /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
952 /// node map with \c bool (or convertible) value type.
954 /// This method can be called both after running \ref startFirstPhase()
955 /// and \ref startSecondPhase(). The result after the second phase
956 /// could be slightly different if inexact computation is used.
958 /// \note This function calls \ref minCut() for each node, so it runs in
961 /// \pre Either \ref run() or \ref init() must be called before
962 /// using this function.
963 template <typename CutMap>
964 void minCutMap(CutMap& cutMap) const {
965 for (NodeIt n(_graph); n != INVALID; ++n) {
966 cutMap.set(n, minCut(n));