3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
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_CYCLE_CANCELING_H
20 #define LEMON_CYCLE_CANCELING_H
22 /// \ingroup min_cost_flow_algs
24 /// \brief Cycle-canceling algorithms for finding a minimum cost flow.
29 #include <lemon/core.h>
30 #include <lemon/maps.h>
31 #include <lemon/path.h>
32 #include <lemon/math.h>
33 #include <lemon/static_graph.h>
34 #include <lemon/adaptors.h>
35 #include <lemon/circulation.h>
36 #include <lemon/bellman_ford.h>
37 #include <lemon/howard.h>
41 /// \addtogroup min_cost_flow_algs
44 /// \brief Implementation of cycle-canceling algorithms for
45 /// finding a \ref min_cost_flow "minimum cost flow".
47 /// \ref CycleCanceling implements three different cycle-canceling
48 /// algorithms for finding a \ref min_cost_flow "minimum cost flow"
49 /// \ref amo93networkflows, \ref klein67primal,
50 /// \ref goldberg89cyclecanceling.
51 /// The most efficent one (both theoretically and practically)
52 /// is the \ref CANCEL_AND_TIGHTEN "Cancel and Tighten" algorithm,
53 /// thus it is the default method.
54 /// It is strongly polynomial, but in practice, it is typically much
55 /// slower than the scaling algorithms and NetworkSimplex.
57 /// Most of the parameters of the problem (except for the digraph)
58 /// can be given using separate functions, and the algorithm can be
59 /// executed using the \ref run() function. If some parameters are not
60 /// specified, then default values will be used.
62 /// \tparam GR The digraph type the algorithm runs on.
63 /// \tparam V The number type used for flow amounts, capacity bounds
64 /// and supply values in the algorithm. By default, it is \c int.
65 /// \tparam C The number type used for costs and potentials in the
66 /// algorithm. By default, it is the same as \c V.
68 /// \warning Both number types must be signed and all input data must
70 /// \warning This algorithm does not support negative costs for such
71 /// arcs that have infinite upper bound.
73 /// \note For more information about the three available methods,
76 template <typename GR, typename V, typename C>
78 template <typename GR, typename V = int, typename C = V>
84 /// The type of the digraph
86 /// The type of the flow amounts, capacity bounds and supply values
88 /// The type of the arc costs
93 /// \brief Problem type constants for the \c run() function.
95 /// Enum type containing the problem type constants that can be
96 /// returned by the \ref run() function of the algorithm.
98 /// The problem has no feasible solution (flow).
100 /// The problem has optimal solution (i.e. it is feasible and
101 /// bounded), and the algorithm has found optimal flow and node
102 /// potentials (primal and dual solutions).
104 /// The digraph contains an arc of negative cost and infinite
105 /// upper bound. It means that the objective function is unbounded
106 /// on that arc, however, note that it could actually be bounded
107 /// over the feasible flows, but this algroithm cannot handle
112 /// \brief Constants for selecting the used method.
114 /// Enum type containing constants for selecting the used method
115 /// for the \ref run() function.
117 /// \ref CycleCanceling provides three different cycle-canceling
118 /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel and Tighten"
119 /// is used, which proved to be the most efficient and the most robust
120 /// on various test inputs.
121 /// However, the other methods can be selected using the \ref run()
122 /// function with the proper parameter.
124 /// A simple cycle-canceling method, which uses the
125 /// \ref BellmanFord "Bellman-Ford" algorithm with limited iteration
126 /// number for detecting negative cycles in the residual network.
127 SIMPLE_CYCLE_CANCELING,
128 /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
129 /// well-known strongly polynomial method
130 /// \ref goldberg89cyclecanceling. It improves along a
131 /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
132 /// Its running time complexity is O(n<sup>2</sup>m<sup>3</sup>log(n)).
133 MINIMUM_MEAN_CYCLE_CANCELING,
134 /// The "Cancel And Tighten" algorithm, which can be viewed as an
135 /// improved version of the previous method
136 /// \ref goldberg89cyclecanceling.
137 /// It is faster both in theory and in practice, its running time
138 /// complexity is O(n<sup>2</sup>m<sup>2</sup>log(n)).
144 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
146 typedef std::vector<int> IntVector;
147 typedef std::vector<double> DoubleVector;
148 typedef std::vector<Value> ValueVector;
149 typedef std::vector<Cost> CostVector;
150 typedef std::vector<char> BoolVector;
151 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
155 template <typename KT, typename VT>
156 class StaticVectorMap {
161 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
163 const Value& operator[](const Key& key) const {
164 return _v[StaticDigraph::id(key)];
167 Value& operator[](const Key& key) {
168 return _v[StaticDigraph::id(key)];
171 void set(const Key& key, const Value& val) {
172 _v[StaticDigraph::id(key)] = val;
176 std::vector<Value>& _v;
179 typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
180 typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
185 // Data related to the underlying digraph
193 // Parameters of the problem
197 // Data structures for storing the digraph
201 IntVector _first_out;
213 ValueVector _res_cap;
216 // Data for a StaticDigraph structure
217 typedef std::pair<int, int> IntPair;
219 std::vector<IntPair> _arc_vec;
220 std::vector<Cost> _cost_vec;
222 CostArcMap _cost_map;
227 /// \brief Constant for infinite upper bounds (capacities).
229 /// Constant for infinite upper bounds (capacities).
230 /// It is \c std::numeric_limits<Value>::infinity() if available,
231 /// \c std::numeric_limits<Value>::max() otherwise.
236 /// \brief Constructor.
238 /// The constructor of the class.
240 /// \param graph The digraph the algorithm runs on.
241 CycleCanceling(const GR& graph) :
242 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
243 _cost_map(_cost_vec), _pi_map(_pi),
244 INF(std::numeric_limits<Value>::has_infinity ?
245 std::numeric_limits<Value>::infinity() :
246 std::numeric_limits<Value>::max())
248 // Check the number types
249 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
250 "The flow type of CycleCanceling must be signed");
251 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
252 "The cost type of CycleCanceling must be signed");
255 _node_num = countNodes(_graph);
256 _arc_num = countArcs(_graph);
257 _res_node_num = _node_num + 1;
258 _res_arc_num = 2 * (_arc_num + _node_num);
261 _first_out.resize(_res_node_num + 1);
262 _forward.resize(_res_arc_num);
263 _source.resize(_res_arc_num);
264 _target.resize(_res_arc_num);
265 _reverse.resize(_res_arc_num);
267 _lower.resize(_res_arc_num);
268 _upper.resize(_res_arc_num);
269 _cost.resize(_res_arc_num);
270 _supply.resize(_res_node_num);
272 _res_cap.resize(_res_arc_num);
273 _pi.resize(_res_node_num);
275 _arc_vec.reserve(_res_arc_num);
276 _cost_vec.reserve(_res_arc_num);
277 _id_vec.reserve(_res_arc_num);
280 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
281 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
285 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
287 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
291 _target[j] = _node_id[_graph.runningNode(a)];
293 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
297 _target[j] = _node_id[_graph.runningNode(a)];
310 _first_out[_res_node_num] = k;
311 for (ArcIt a(_graph); a != INVALID; ++a) {
312 int fi = _arc_idf[a];
313 int bi = _arc_idb[a];
323 /// The parameters of the algorithm can be specified using these
328 /// \brief Set the lower bounds on the arcs.
330 /// This function sets the lower bounds on the arcs.
331 /// If it is not used before calling \ref run(), the lower bounds
332 /// will be set to zero on all arcs.
334 /// \param map An arc map storing the lower bounds.
335 /// Its \c Value type must be convertible to the \c Value type
336 /// of the algorithm.
338 /// \return <tt>(*this)</tt>
339 template <typename LowerMap>
340 CycleCanceling& lowerMap(const LowerMap& map) {
342 for (ArcIt a(_graph); a != INVALID; ++a) {
343 _lower[_arc_idf[a]] = map[a];
344 _lower[_arc_idb[a]] = map[a];
349 /// \brief Set the upper bounds (capacities) on the arcs.
351 /// This function sets the upper bounds (capacities) on the arcs.
352 /// If it is not used before calling \ref run(), the upper bounds
353 /// will be set to \ref INF on all arcs (i.e. the flow value will be
354 /// unbounded from above).
356 /// \param map An arc map storing the upper bounds.
357 /// Its \c Value type must be convertible to the \c Value type
358 /// of the algorithm.
360 /// \return <tt>(*this)</tt>
361 template<typename UpperMap>
362 CycleCanceling& upperMap(const UpperMap& map) {
363 for (ArcIt a(_graph); a != INVALID; ++a) {
364 _upper[_arc_idf[a]] = map[a];
369 /// \brief Set the costs of the arcs.
371 /// This function sets the costs of the arcs.
372 /// If it is not used before calling \ref run(), the costs
373 /// will be set to \c 1 on all arcs.
375 /// \param map An arc map storing the costs.
376 /// Its \c Value type must be convertible to the \c Cost type
377 /// of the algorithm.
379 /// \return <tt>(*this)</tt>
380 template<typename CostMap>
381 CycleCanceling& costMap(const CostMap& map) {
382 for (ArcIt a(_graph); a != INVALID; ++a) {
383 _cost[_arc_idf[a]] = map[a];
384 _cost[_arc_idb[a]] = -map[a];
389 /// \brief Set the supply values of the nodes.
391 /// This function sets the supply values of the nodes.
392 /// If neither this function nor \ref stSupply() is used before
393 /// calling \ref run(), the supply of each node will be set to zero.
395 /// \param map A node map storing the supply values.
396 /// Its \c Value type must be convertible to the \c Value type
397 /// of the algorithm.
399 /// \return <tt>(*this)</tt>
400 template<typename SupplyMap>
401 CycleCanceling& supplyMap(const SupplyMap& map) {
402 for (NodeIt n(_graph); n != INVALID; ++n) {
403 _supply[_node_id[n]] = map[n];
408 /// \brief Set single source and target nodes and a supply value.
410 /// This function sets a single source node and a single target node
411 /// and the required flow value.
412 /// If neither this function nor \ref supplyMap() is used before
413 /// calling \ref run(), the supply of each node will be set to zero.
415 /// Using this function has the same effect as using \ref supplyMap()
416 /// with such a map in which \c k is assigned to \c s, \c -k is
417 /// assigned to \c t and all other nodes have zero supply value.
419 /// \param s The source node.
420 /// \param t The target node.
421 /// \param k The required amount of flow from node \c s to node \c t
422 /// (i.e. the supply of \c s and the demand of \c t).
424 /// \return <tt>(*this)</tt>
425 CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
426 for (int i = 0; i != _res_node_num; ++i) {
429 _supply[_node_id[s]] = k;
430 _supply[_node_id[t]] = -k;
436 /// \name Execution control
437 /// The algorithm can be executed using \ref run().
441 /// \brief Run the algorithm.
443 /// This function runs the algorithm.
444 /// The paramters can be specified using functions \ref lowerMap(),
445 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
448 /// CycleCanceling<ListDigraph> cc(graph);
449 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
450 /// .supplyMap(sup).run();
453 /// This function can be called more than once. All the parameters
454 /// that have been given are kept for the next call, unless
455 /// \ref reset() is called, thus only the modified parameters
456 /// have to be set again. See \ref reset() for examples.
457 /// However, the underlying digraph must not be modified after this
458 /// class have been constructed, since it copies and extends the graph.
460 /// \param method The cycle-canceling method that will be used.
461 /// For more information, see \ref Method.
463 /// \return \c INFEASIBLE if no feasible flow exists,
464 /// \n \c OPTIMAL if the problem has optimal solution
465 /// (i.e. it is feasible and bounded), and the algorithm has found
466 /// optimal flow and node potentials (primal and dual solutions),
467 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
468 /// and infinite upper bound. It means that the objective function
469 /// is unbounded on that arc, however, note that it could actually be
470 /// bounded over the feasible flows, but this algroithm cannot handle
473 /// \see ProblemType, Method
474 ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
475 ProblemType pt = init();
476 if (pt != OPTIMAL) return pt;
481 /// \brief Reset all the parameters that have been given before.
483 /// This function resets all the paramaters that have been given
484 /// before using functions \ref lowerMap(), \ref upperMap(),
485 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
487 /// It is useful for multiple run() calls. If this function is not
488 /// used, all the parameters given before are kept for the next
490 /// However, the underlying digraph must not be modified after this
491 /// class have been constructed, since it copies and extends the graph.
495 /// CycleCanceling<ListDigraph> cs(graph);
498 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
499 /// .supplyMap(sup).run();
501 /// // Run again with modified cost map (reset() is not called,
502 /// // so only the cost map have to be set again)
504 /// cc.costMap(cost).run();
506 /// // Run again from scratch using reset()
507 /// // (the lower bounds will be set to zero on all arcs)
509 /// cc.upperMap(capacity).costMap(cost)
510 /// .supplyMap(sup).run();
513 /// \return <tt>(*this)</tt>
514 CycleCanceling& reset() {
515 for (int i = 0; i != _res_node_num; ++i) {
518 int limit = _first_out[_root];
519 for (int j = 0; j != limit; ++j) {
522 _cost[j] = _forward[j] ? 1 : -1;
524 for (int j = limit; j != _res_arc_num; ++j) {
528 _cost[_reverse[j]] = 0;
536 /// \name Query Functions
537 /// The results of the algorithm can be obtained using these
539 /// The \ref run() function must be called before using them.
543 /// \brief Return the total cost of the found flow.
545 /// This function returns the total cost of the found flow.
546 /// Its complexity is O(e).
548 /// \note The return type of the function can be specified as a
549 /// template parameter. For example,
551 /// cc.totalCost<double>();
553 /// It is useful if the total cost cannot be stored in the \c Cost
554 /// type of the algorithm, which is the default return type of the
557 /// \pre \ref run() must be called before using this function.
558 template <typename Number>
559 Number totalCost() const {
561 for (ArcIt a(_graph); a != INVALID; ++a) {
563 c += static_cast<Number>(_res_cap[i]) *
564 (-static_cast<Number>(_cost[i]));
570 Cost totalCost() const {
571 return totalCost<Cost>();
575 /// \brief Return the flow on the given arc.
577 /// This function returns the flow on the given arc.
579 /// \pre \ref run() must be called before using this function.
580 Value flow(const Arc& a) const {
581 return _res_cap[_arc_idb[a]];
584 /// \brief Return the flow map (the primal solution).
586 /// This function copies the flow value on each arc into the given
587 /// map. The \c Value type of the algorithm must be convertible to
588 /// the \c Value type of the map.
590 /// \pre \ref run() must be called before using this function.
591 template <typename FlowMap>
592 void flowMap(FlowMap &map) const {
593 for (ArcIt a(_graph); a != INVALID; ++a) {
594 map.set(a, _res_cap[_arc_idb[a]]);
598 /// \brief Return the potential (dual value) of the given node.
600 /// This function returns the potential (dual value) of the
603 /// \pre \ref run() must be called before using this function.
604 Cost potential(const Node& n) const {
605 return static_cast<Cost>(_pi[_node_id[n]]);
608 /// \brief Return the potential map (the dual solution).
610 /// This function copies the potential (dual value) of each node
611 /// into the given map.
612 /// The \c Cost type of the algorithm must be convertible to the
613 /// \c Value type of the map.
615 /// \pre \ref run() must be called before using this function.
616 template <typename PotentialMap>
617 void potentialMap(PotentialMap &map) const {
618 for (NodeIt n(_graph); n != INVALID; ++n) {
619 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
627 // Initialize the algorithm
629 if (_res_node_num <= 1) return INFEASIBLE;
631 // Check the sum of supply values
633 for (int i = 0; i != _root; ++i) {
634 _sum_supply += _supply[i];
636 if (_sum_supply > 0) return INFEASIBLE;
639 // Initialize vectors
640 for (int i = 0; i != _res_node_num; ++i) {
643 ValueVector excess(_supply);
645 // Remove infinite upper bounds and check negative arcs
646 const Value MAX = std::numeric_limits<Value>::max();
649 for (int i = 0; i != _root; ++i) {
650 last_out = _first_out[i+1];
651 for (int j = _first_out[i]; j != last_out; ++j) {
653 Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
654 if (c >= MAX) return UNBOUNDED;
656 excess[_target[j]] += c;
661 for (int i = 0; i != _root; ++i) {
662 last_out = _first_out[i+1];
663 for (int j = _first_out[i]; j != last_out; ++j) {
664 if (_forward[j] && _cost[j] < 0) {
666 if (c >= MAX) return UNBOUNDED;
668 excess[_target[j]] += c;
673 Value ex, max_cap = 0;
674 for (int i = 0; i != _res_node_num; ++i) {
676 if (ex < 0) max_cap -= ex;
678 for (int j = 0; j != _res_arc_num; ++j) {
679 if (_upper[j] >= MAX) _upper[j] = max_cap;
682 // Initialize maps for Circulation and remove non-zero lower bounds
683 ConstMap<Arc, Value> low(0);
684 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
685 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
686 ValueArcMap cap(_graph), flow(_graph);
687 ValueNodeMap sup(_graph);
688 for (NodeIt n(_graph); n != INVALID; ++n) {
689 sup[n] = _supply[_node_id[n]];
692 for (ArcIt a(_graph); a != INVALID; ++a) {
695 cap[a] = _upper[j] - c;
696 sup[_graph.source(a)] -= c;
697 sup[_graph.target(a)] += c;
700 for (ArcIt a(_graph); a != INVALID; ++a) {
701 cap[a] = _upper[_arc_idf[a]];
705 // Find a feasible flow using Circulation
706 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
707 circ(_graph, low, cap, sup);
708 if (!circ.flowMap(flow).run()) return INFEASIBLE;
710 // Set residual capacities and handle GEQ supply type
711 if (_sum_supply < 0) {
712 for (ArcIt a(_graph); a != INVALID; ++a) {
714 _res_cap[_arc_idf[a]] = cap[a] - fa;
715 _res_cap[_arc_idb[a]] = fa;
716 sup[_graph.source(a)] -= fa;
717 sup[_graph.target(a)] += fa;
719 for (NodeIt n(_graph); n != INVALID; ++n) {
720 excess[_node_id[n]] = sup[n];
722 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
724 int ra = _reverse[a];
725 _res_cap[a] = -_sum_supply + 1;
726 _res_cap[ra] = -excess[u];
731 for (ArcIt a(_graph); a != INVALID; ++a) {
733 _res_cap[_arc_idf[a]] = cap[a] - fa;
734 _res_cap[_arc_idb[a]] = fa;
736 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
737 int ra = _reverse[a];
748 // Build a StaticDigraph structure containing the current
750 void buildResidualNetwork() {
754 for (int j = 0; j != _res_arc_num; ++j) {
755 if (_res_cap[j] > 0) {
756 _arc_vec.push_back(IntPair(_source[j], _target[j]));
757 _cost_vec.push_back(_cost[j]);
758 _id_vec.push_back(j);
761 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
764 // Execute the algorithm and transform the results
765 void start(Method method) {
766 // Execute the algorithm
768 case SIMPLE_CYCLE_CANCELING:
769 startSimpleCycleCanceling();
771 case MINIMUM_MEAN_CYCLE_CANCELING:
772 startMinMeanCycleCanceling();
774 case CANCEL_AND_TIGHTEN:
775 startCancelAndTighten();
779 // Compute node potentials
780 if (method != SIMPLE_CYCLE_CANCELING) {
781 buildResidualNetwork();
782 typename BellmanFord<StaticDigraph, CostArcMap>
783 ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
789 // Handle non-zero lower bounds
791 int limit = _first_out[_root];
792 for (int j = 0; j != limit; ++j) {
793 if (!_forward[j]) _res_cap[j] += _lower[j];
798 // Execute the "Simple Cycle Canceling" method
799 void startSimpleCycleCanceling() {
800 // Constants for computing the iteration limits
801 const int BF_FIRST_LIMIT = 2;
802 const double BF_LIMIT_FACTOR = 1.5;
804 typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
805 typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
806 typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
807 typedef typename BellmanFord<ResDigraph, CostArcMap>
808 ::template SetDistMap<CostNodeMap>
809 ::template SetPredMap<PredMap>::Create BF;
811 // Build the residual network
814 for (int j = 0; j != _res_arc_num; ++j) {
815 _arc_vec.push_back(IntPair(_source[j], _target[j]));
816 _cost_vec.push_back(_cost[j]);
818 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
820 FilterMap filter_map(_res_cap);
821 ResDigraph rgr(_sgr, filter_map);
822 std::vector<int> cycle;
823 std::vector<StaticDigraph::Arc> pred(_res_arc_num);
824 PredMap pred_map(pred);
825 BF bf(rgr, _cost_map);
826 bf.distMap(_pi_map).predMap(pred_map);
828 int length_bound = BF_FIRST_LIMIT;
829 bool optimal = false;
833 bool cycle_found = false;
834 while (!cycle_found) {
835 // Perform some iterations of the Bellman-Ford algorithm
836 int curr_iter_num = iter_num + length_bound <= _node_num ?
837 length_bound : _node_num - iter_num;
838 iter_num += curr_iter_num;
839 int real_iter_num = curr_iter_num;
840 for (int i = 0; i < curr_iter_num; ++i) {
841 if (bf.processNextWeakRound()) {
846 if (real_iter_num < curr_iter_num) {
847 // Optimal flow is found
851 // Search for node disjoint negative cycles
852 std::vector<int> state(_res_node_num, 0);
854 for (int u = 0; u != _res_node_num; ++u) {
855 if (state[u] != 0) continue;
858 for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
859 -1 : rgr.id(rgr.source(pred[v]))) {
862 if (v != -1 && state[v] == id) {
863 // A negative cycle is found
866 StaticDigraph::Arc a = pred[v];
867 Value d, delta = _res_cap[rgr.id(a)];
868 cycle.push_back(rgr.id(a));
869 while (rgr.id(rgr.source(a)) != v) {
870 a = pred_map[rgr.source(a)];
871 d = _res_cap[rgr.id(a)];
872 if (d < delta) delta = d;
873 cycle.push_back(rgr.id(a));
876 // Augment along the cycle
877 for (int i = 0; i < int(cycle.size()); ++i) {
879 _res_cap[j] -= delta;
880 _res_cap[_reverse[j]] += delta;
886 // Increase iteration limit if no cycle is found
888 length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
894 // Execute the "Minimum Mean Cycle Canceling" method
895 void startMinMeanCycleCanceling() {
896 typedef SimplePath<StaticDigraph> SPath;
897 typedef typename SPath::ArcIt SPathArcIt;
898 typedef typename Howard<StaticDigraph, CostArcMap>
899 ::template SetPath<SPath>::Create MMC;
902 MMC mmc(_sgr, _cost_map);
904 buildResidualNetwork();
905 while (mmc.findMinMean() && mmc.cycleLength() < 0) {
909 // Compute delta value
911 for (SPathArcIt a(cycle); a != INVALID; ++a) {
912 Value d = _res_cap[_id_vec[_sgr.id(a)]];
913 if (d < delta) delta = d;
916 // Augment along the cycle
917 for (SPathArcIt a(cycle); a != INVALID; ++a) {
918 int j = _id_vec[_sgr.id(a)];
919 _res_cap[j] -= delta;
920 _res_cap[_reverse[j]] += delta;
923 // Rebuild the residual network
924 buildResidualNetwork();
928 // Execute the "Cancel And Tighten" method
929 void startCancelAndTighten() {
930 // Constants for the min mean cycle computations
931 const double LIMIT_FACTOR = 1.0;
932 const int MIN_LIMIT = 5;
934 // Contruct auxiliary data vectors
935 DoubleVector pi(_res_node_num, 0.0);
936 IntVector level(_res_node_num);
937 BoolVector reached(_res_node_num);
938 BoolVector processed(_res_node_num);
939 IntVector pred_node(_res_node_num);
940 IntVector pred_arc(_res_node_num);
941 std::vector<int> stack(_res_node_num);
942 std::vector<int> proc_vector(_res_node_num);
944 // Initialize epsilon
946 for (int a = 0; a != _res_arc_num; ++a) {
947 if (_res_cap[a] > 0 && -_cost[a] > epsilon)
952 Tolerance<double> tol;
954 int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
955 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
957 while (epsilon * _res_node_num >= 1) {
958 // Find and cancel cycles in the admissible network using DFS
959 for (int u = 0; u != _res_node_num; ++u) {
961 processed[u] = false;
965 for (int start = 0; start != _res_node_num; ++start) {
966 if (reached[start]) continue;
969 reached[start] = true;
970 pred_arc[start] = -1;
971 pred_node[start] = -1;
973 // Find the first admissible outgoing arc
974 double p = pi[start];
975 int a = _first_out[start];
976 int last_out = _first_out[start+1];
977 for (; a != last_out && (_res_cap[a] == 0 ||
978 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
980 processed[start] = true;
981 proc_vector[++proc_head] = start;
984 stack[++stack_head] = a;
986 while (stack_head >= 0) {
987 int sa = stack[stack_head];
992 // A new node is reached
998 last_out = _first_out[v+1];
999 for (; a != last_out && (_res_cap[a] == 0 ||
1000 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1001 stack[++stack_head] = a == last_out ? -1 : a;
1003 if (!processed[v]) {
1006 Value d, delta = _res_cap[sa];
1007 for (n = u; n != v; n = pred_node[n]) {
1008 d = _res_cap[pred_arc[n]];
1015 // Augment along the cycle
1016 _res_cap[sa] -= delta;
1017 _res_cap[_reverse[sa]] += delta;
1018 for (n = u; n != v; n = pred_node[n]) {
1019 int pa = pred_arc[n];
1020 _res_cap[pa] -= delta;
1021 _res_cap[_reverse[pa]] += delta;
1023 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1031 // Find the next admissible outgoing arc
1033 a = stack[stack_head] + 1;
1034 last_out = _first_out[v+1];
1035 for (; a != last_out && (_res_cap[a] == 0 ||
1036 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1037 stack[stack_head] = a == last_out ? -1 : a;
1040 while (stack_head >= 0 && stack[stack_head] == -1) {
1041 processed[v] = true;
1042 proc_vector[++proc_head] = v;
1043 if (--stack_head >= 0) {
1044 // Find the next admissible outgoing arc
1045 v = _source[stack[stack_head]];
1047 a = stack[stack_head] + 1;
1048 last_out = _first_out[v+1];
1049 for (; a != last_out && (_res_cap[a] == 0 ||
1050 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1051 stack[stack_head] = a == last_out ? -1 : a;
1057 // Tighten potentials and epsilon
1059 for (int u = 0; u != _res_node_num; ++u) {
1062 for (int i = proc_head; i > 0; --i) {
1063 int u = proc_vector[i];
1065 int l = level[u] + 1;
1066 int last_out = _first_out[u+1];
1067 for (int a = _first_out[u]; a != last_out; ++a) {
1069 if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1070 l > level[v]) level[v] = l;
1074 // Modify potentials
1075 double q = std::numeric_limits<double>::max();
1076 for (int u = 0; u != _res_node_num; ++u) {
1078 double p, pu = pi[u];
1079 int last_out = _first_out[u+1];
1080 for (int a = _first_out[u]; a != last_out; ++a) {
1081 if (_res_cap[a] == 0) continue;
1083 int ld = lu - level[v];
1085 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1090 for (int u = 0; u != _res_node_num; ++u) {
1091 pi[u] -= q * level[u];
1096 for (int u = 0; u != _res_node_num; ++u) {
1097 double curr, pu = pi[u];
1098 int last_out = _first_out[u+1];
1099 for (int a = _first_out[u]; a != last_out; ++a) {
1100 if (_res_cap[a] == 0) continue;
1101 curr = _cost[a] + pu - pi[_target[a]];
1102 if (-curr > epsilon) epsilon = -curr;
1106 typedef Howard<StaticDigraph, CostArcMap> MMC;
1107 typedef typename BellmanFord<StaticDigraph, CostArcMap>
1108 ::template SetDistMap<CostNodeMap>::Create BF;
1110 // Set epsilon to the minimum cycle mean
1111 buildResidualNetwork();
1112 MMC mmc(_sgr, _cost_map);
1114 epsilon = -mmc.cycleMean();
1115 Cost cycle_cost = mmc.cycleLength();
1116 int cycle_size = mmc.cycleArcNum();
1118 // Compute feasible potentials for the current epsilon
1119 for (int i = 0; i != int(_cost_vec.size()); ++i) {
1120 _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1122 BF bf(_sgr, _cost_map);
1123 bf.distMap(_pi_map);
1126 for (int u = 0; u != _res_node_num; ++u) {
1127 pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1135 }; //class CycleCanceling
1141 #endif //LEMON_CYCLE_CANCELING_H