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<char> CharVector;
148 typedef std::vector<double> DoubleVector;
149 typedef std::vector<Value> ValueVector;
150 typedef std::vector<Cost> CostVector;
154 template <typename KT, typename VT>
155 class StaticVectorMap {
160 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
162 const Value& operator[](const Key& key) const {
163 return _v[StaticDigraph::id(key)];
166 Value& operator[](const Key& key) {
167 return _v[StaticDigraph::id(key)];
170 void set(const Key& key, const Value& val) {
171 _v[StaticDigraph::id(key)] = val;
175 std::vector<Value>& _v;
178 typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
179 typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
184 // Data related to the underlying digraph
192 // Parameters of the problem
196 // Data structures for storing the digraph
200 IntVector _first_out;
212 ValueVector _res_cap;
215 // Data for a StaticDigraph structure
216 typedef std::pair<int, int> IntPair;
218 std::vector<IntPair> _arc_vec;
219 std::vector<Cost> _cost_vec;
221 CostArcMap _cost_map;
226 /// \brief Constant for infinite upper bounds (capacities).
228 /// Constant for infinite upper bounds (capacities).
229 /// It is \c std::numeric_limits<Value>::infinity() if available,
230 /// \c std::numeric_limits<Value>::max() otherwise.
235 /// \brief Constructor.
237 /// The constructor of the class.
239 /// \param graph The digraph the algorithm runs on.
240 CycleCanceling(const GR& graph) :
241 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
242 _cost_map(_cost_vec), _pi_map(_pi),
243 INF(std::numeric_limits<Value>::has_infinity ?
244 std::numeric_limits<Value>::infinity() :
245 std::numeric_limits<Value>::max())
247 // Check the number types
248 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
249 "The flow type of CycleCanceling must be signed");
250 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
251 "The cost type of CycleCanceling must be signed");
254 _node_num = countNodes(_graph);
255 _arc_num = countArcs(_graph);
256 _res_node_num = _node_num + 1;
257 _res_arc_num = 2 * (_arc_num + _node_num);
260 _first_out.resize(_res_node_num + 1);
261 _forward.resize(_res_arc_num);
262 _source.resize(_res_arc_num);
263 _target.resize(_res_arc_num);
264 _reverse.resize(_res_arc_num);
266 _lower.resize(_res_arc_num);
267 _upper.resize(_res_arc_num);
268 _cost.resize(_res_arc_num);
269 _supply.resize(_res_node_num);
271 _res_cap.resize(_res_arc_num);
272 _pi.resize(_res_node_num);
274 _arc_vec.reserve(_res_arc_num);
275 _cost_vec.reserve(_res_arc_num);
276 _id_vec.reserve(_res_arc_num);
279 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
280 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
284 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
286 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
290 _target[j] = _node_id[_graph.runningNode(a)];
292 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
296 _target[j] = _node_id[_graph.runningNode(a)];
309 _first_out[_res_node_num] = k;
310 for (ArcIt a(_graph); a != INVALID; ++a) {
311 int fi = _arc_idf[a];
312 int bi = _arc_idb[a];
322 /// The parameters of the algorithm can be specified using these
327 /// \brief Set the lower bounds on the arcs.
329 /// This function sets the lower bounds on the arcs.
330 /// If it is not used before calling \ref run(), the lower bounds
331 /// will be set to zero on all arcs.
333 /// \param map An arc map storing the lower bounds.
334 /// Its \c Value type must be convertible to the \c Value type
335 /// of the algorithm.
337 /// \return <tt>(*this)</tt>
338 template <typename LowerMap>
339 CycleCanceling& lowerMap(const LowerMap& map) {
341 for (ArcIt a(_graph); a != INVALID; ++a) {
342 _lower[_arc_idf[a]] = map[a];
343 _lower[_arc_idb[a]] = map[a];
348 /// \brief Set the upper bounds (capacities) on the arcs.
350 /// This function sets the upper bounds (capacities) on the arcs.
351 /// If it is not used before calling \ref run(), the upper bounds
352 /// will be set to \ref INF on all arcs (i.e. the flow value will be
353 /// unbounded from above).
355 /// \param map An arc map storing the upper bounds.
356 /// Its \c Value type must be convertible to the \c Value type
357 /// of the algorithm.
359 /// \return <tt>(*this)</tt>
360 template<typename UpperMap>
361 CycleCanceling& upperMap(const UpperMap& map) {
362 for (ArcIt a(_graph); a != INVALID; ++a) {
363 _upper[_arc_idf[a]] = map[a];
368 /// \brief Set the costs of the arcs.
370 /// This function sets the costs of the arcs.
371 /// If it is not used before calling \ref run(), the costs
372 /// will be set to \c 1 on all arcs.
374 /// \param map An arc map storing the costs.
375 /// Its \c Value type must be convertible to the \c Cost type
376 /// of the algorithm.
378 /// \return <tt>(*this)</tt>
379 template<typename CostMap>
380 CycleCanceling& costMap(const CostMap& map) {
381 for (ArcIt a(_graph); a != INVALID; ++a) {
382 _cost[_arc_idf[a]] = map[a];
383 _cost[_arc_idb[a]] = -map[a];
388 /// \brief Set the supply values of the nodes.
390 /// This function sets the supply values of the nodes.
391 /// If neither this function nor \ref stSupply() is used before
392 /// calling \ref run(), the supply of each node will be set to zero.
394 /// \param map A node map storing the supply values.
395 /// Its \c Value type must be convertible to the \c Value type
396 /// of the algorithm.
398 /// \return <tt>(*this)</tt>
399 template<typename SupplyMap>
400 CycleCanceling& supplyMap(const SupplyMap& map) {
401 for (NodeIt n(_graph); n != INVALID; ++n) {
402 _supply[_node_id[n]] = map[n];
407 /// \brief Set single source and target nodes and a supply value.
409 /// This function sets a single source node and a single target node
410 /// and the required flow value.
411 /// If neither this function nor \ref supplyMap() is used before
412 /// calling \ref run(), the supply of each node will be set to zero.
414 /// Using this function has the same effect as using \ref supplyMap()
415 /// with such a map in which \c k is assigned to \c s, \c -k is
416 /// assigned to \c t and all other nodes have zero supply value.
418 /// \param s The source node.
419 /// \param t The target node.
420 /// \param k The required amount of flow from node \c s to node \c t
421 /// (i.e. the supply of \c s and the demand of \c t).
423 /// \return <tt>(*this)</tt>
424 CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
425 for (int i = 0; i != _res_node_num; ++i) {
428 _supply[_node_id[s]] = k;
429 _supply[_node_id[t]] = -k;
435 /// \name Execution control
436 /// The algorithm can be executed using \ref run().
440 /// \brief Run the algorithm.
442 /// This function runs the algorithm.
443 /// The paramters can be specified using functions \ref lowerMap(),
444 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
447 /// CycleCanceling<ListDigraph> cc(graph);
448 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
449 /// .supplyMap(sup).run();
452 /// This function can be called more than once. All the parameters
453 /// that have been given are kept for the next call, unless
454 /// \ref reset() is called, thus only the modified parameters
455 /// have to be set again. See \ref reset() for examples.
456 /// However, the underlying digraph must not be modified after this
457 /// class have been constructed, since it copies and extends the graph.
459 /// \param method The cycle-canceling method that will be used.
460 /// For more information, see \ref Method.
462 /// \return \c INFEASIBLE if no feasible flow exists,
463 /// \n \c OPTIMAL if the problem has optimal solution
464 /// (i.e. it is feasible and bounded), and the algorithm has found
465 /// optimal flow and node potentials (primal and dual solutions),
466 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
467 /// and infinite upper bound. It means that the objective function
468 /// is unbounded on that arc, however, note that it could actually be
469 /// bounded over the feasible flows, but this algroithm cannot handle
472 /// \see ProblemType, Method
473 ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
474 ProblemType pt = init();
475 if (pt != OPTIMAL) return pt;
480 /// \brief Reset all the parameters that have been given before.
482 /// This function resets all the paramaters that have been given
483 /// before using functions \ref lowerMap(), \ref upperMap(),
484 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
486 /// It is useful for multiple run() calls. If this function is not
487 /// used, all the parameters given before are kept for the next
489 /// However, the underlying digraph must not be modified after this
490 /// class have been constructed, since it copies and extends the graph.
494 /// CycleCanceling<ListDigraph> cs(graph);
497 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
498 /// .supplyMap(sup).run();
500 /// // Run again with modified cost map (reset() is not called,
501 /// // so only the cost map have to be set again)
503 /// cc.costMap(cost).run();
505 /// // Run again from scratch using reset()
506 /// // (the lower bounds will be set to zero on all arcs)
508 /// cc.upperMap(capacity).costMap(cost)
509 /// .supplyMap(sup).run();
512 /// \return <tt>(*this)</tt>
513 CycleCanceling& reset() {
514 for (int i = 0; i != _res_node_num; ++i) {
517 int limit = _first_out[_root];
518 for (int j = 0; j != limit; ++j) {
521 _cost[j] = _forward[j] ? 1 : -1;
523 for (int j = limit; j != _res_arc_num; ++j) {
527 _cost[_reverse[j]] = 0;
535 /// \name Query Functions
536 /// The results of the algorithm can be obtained using these
538 /// The \ref run() function must be called before using them.
542 /// \brief Return the total cost of the found flow.
544 /// This function returns the total cost of the found flow.
545 /// Its complexity is O(e).
547 /// \note The return type of the function can be specified as a
548 /// template parameter. For example,
550 /// cc.totalCost<double>();
552 /// It is useful if the total cost cannot be stored in the \c Cost
553 /// type of the algorithm, which is the default return type of the
556 /// \pre \ref run() must be called before using this function.
557 template <typename Number>
558 Number totalCost() const {
560 for (ArcIt a(_graph); a != INVALID; ++a) {
562 c += static_cast<Number>(_res_cap[i]) *
563 (-static_cast<Number>(_cost[i]));
569 Cost totalCost() const {
570 return totalCost<Cost>();
574 /// \brief Return the flow on the given arc.
576 /// This function returns the flow on the given arc.
578 /// \pre \ref run() must be called before using this function.
579 Value flow(const Arc& a) const {
580 return _res_cap[_arc_idb[a]];
583 /// \brief Return the flow map (the primal solution).
585 /// This function copies the flow value on each arc into the given
586 /// map. The \c Value type of the algorithm must be convertible to
587 /// the \c Value type of the map.
589 /// \pre \ref run() must be called before using this function.
590 template <typename FlowMap>
591 void flowMap(FlowMap &map) const {
592 for (ArcIt a(_graph); a != INVALID; ++a) {
593 map.set(a, _res_cap[_arc_idb[a]]);
597 /// \brief Return the potential (dual value) of the given node.
599 /// This function returns the potential (dual value) of the
602 /// \pre \ref run() must be called before using this function.
603 Cost potential(const Node& n) const {
604 return static_cast<Cost>(_pi[_node_id[n]]);
607 /// \brief Return the potential map (the dual solution).
609 /// This function copies the potential (dual value) of each node
610 /// into the given map.
611 /// The \c Cost type of the algorithm must be convertible to the
612 /// \c Value type of the map.
614 /// \pre \ref run() must be called before using this function.
615 template <typename PotentialMap>
616 void potentialMap(PotentialMap &map) const {
617 for (NodeIt n(_graph); n != INVALID; ++n) {
618 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
626 // Initialize the algorithm
628 if (_res_node_num <= 1) return INFEASIBLE;
630 // Check the sum of supply values
632 for (int i = 0; i != _root; ++i) {
633 _sum_supply += _supply[i];
635 if (_sum_supply > 0) return INFEASIBLE;
638 // Initialize vectors
639 for (int i = 0; i != _res_node_num; ++i) {
642 ValueVector excess(_supply);
644 // Remove infinite upper bounds and check negative arcs
645 const Value MAX = std::numeric_limits<Value>::max();
648 for (int i = 0; i != _root; ++i) {
649 last_out = _first_out[i+1];
650 for (int j = _first_out[i]; j != last_out; ++j) {
652 Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
653 if (c >= MAX) return UNBOUNDED;
655 excess[_target[j]] += c;
660 for (int i = 0; i != _root; ++i) {
661 last_out = _first_out[i+1];
662 for (int j = _first_out[i]; j != last_out; ++j) {
663 if (_forward[j] && _cost[j] < 0) {
665 if (c >= MAX) return UNBOUNDED;
667 excess[_target[j]] += c;
672 Value ex, max_cap = 0;
673 for (int i = 0; i != _res_node_num; ++i) {
675 if (ex < 0) max_cap -= ex;
677 for (int j = 0; j != _res_arc_num; ++j) {
678 if (_upper[j] >= MAX) _upper[j] = max_cap;
681 // Initialize maps for Circulation and remove non-zero lower bounds
682 ConstMap<Arc, Value> low(0);
683 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
684 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
685 ValueArcMap cap(_graph), flow(_graph);
686 ValueNodeMap sup(_graph);
687 for (NodeIt n(_graph); n != INVALID; ++n) {
688 sup[n] = _supply[_node_id[n]];
691 for (ArcIt a(_graph); a != INVALID; ++a) {
694 cap[a] = _upper[j] - c;
695 sup[_graph.source(a)] -= c;
696 sup[_graph.target(a)] += c;
699 for (ArcIt a(_graph); a != INVALID; ++a) {
700 cap[a] = _upper[_arc_idf[a]];
704 // Find a feasible flow using Circulation
705 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
706 circ(_graph, low, cap, sup);
707 if (!circ.flowMap(flow).run()) return INFEASIBLE;
709 // Set residual capacities and handle GEQ supply type
710 if (_sum_supply < 0) {
711 for (ArcIt a(_graph); a != INVALID; ++a) {
713 _res_cap[_arc_idf[a]] = cap[a] - fa;
714 _res_cap[_arc_idb[a]] = fa;
715 sup[_graph.source(a)] -= fa;
716 sup[_graph.target(a)] += fa;
718 for (NodeIt n(_graph); n != INVALID; ++n) {
719 excess[_node_id[n]] = sup[n];
721 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
723 int ra = _reverse[a];
724 _res_cap[a] = -_sum_supply + 1;
725 _res_cap[ra] = -excess[u];
730 for (ArcIt a(_graph); a != INVALID; ++a) {
732 _res_cap[_arc_idf[a]] = cap[a] - fa;
733 _res_cap[_arc_idb[a]] = fa;
735 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
736 int ra = _reverse[a];
747 // Build a StaticDigraph structure containing the current
749 void buildResidualNetwork() {
753 for (int j = 0; j != _res_arc_num; ++j) {
754 if (_res_cap[j] > 0) {
755 _arc_vec.push_back(IntPair(_source[j], _target[j]));
756 _cost_vec.push_back(_cost[j]);
757 _id_vec.push_back(j);
760 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
763 // Execute the algorithm and transform the results
764 void start(Method method) {
765 // Execute the algorithm
767 case SIMPLE_CYCLE_CANCELING:
768 startSimpleCycleCanceling();
770 case MINIMUM_MEAN_CYCLE_CANCELING:
771 startMinMeanCycleCanceling();
773 case CANCEL_AND_TIGHTEN:
774 startCancelAndTighten();
778 // Compute node potentials
779 if (method != SIMPLE_CYCLE_CANCELING) {
780 buildResidualNetwork();
781 typename BellmanFord<StaticDigraph, CostArcMap>
782 ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
788 // Handle non-zero lower bounds
790 int limit = _first_out[_root];
791 for (int j = 0; j != limit; ++j) {
792 if (!_forward[j]) _res_cap[j] += _lower[j];
797 // Execute the "Simple Cycle Canceling" method
798 void startSimpleCycleCanceling() {
799 // Constants for computing the iteration limits
800 const int BF_FIRST_LIMIT = 2;
801 const double BF_LIMIT_FACTOR = 1.5;
803 typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
804 typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
805 typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
806 typedef typename BellmanFord<ResDigraph, CostArcMap>
807 ::template SetDistMap<CostNodeMap>
808 ::template SetPredMap<PredMap>::Create BF;
810 // Build the residual network
813 for (int j = 0; j != _res_arc_num; ++j) {
814 _arc_vec.push_back(IntPair(_source[j], _target[j]));
815 _cost_vec.push_back(_cost[j]);
817 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
819 FilterMap filter_map(_res_cap);
820 ResDigraph rgr(_sgr, filter_map);
821 std::vector<int> cycle;
822 std::vector<StaticDigraph::Arc> pred(_res_arc_num);
823 PredMap pred_map(pred);
824 BF bf(rgr, _cost_map);
825 bf.distMap(_pi_map).predMap(pred_map);
827 int length_bound = BF_FIRST_LIMIT;
828 bool optimal = false;
832 bool cycle_found = false;
833 while (!cycle_found) {
834 // Perform some iterations of the Bellman-Ford algorithm
835 int curr_iter_num = iter_num + length_bound <= _node_num ?
836 length_bound : _node_num - iter_num;
837 iter_num += curr_iter_num;
838 int real_iter_num = curr_iter_num;
839 for (int i = 0; i < curr_iter_num; ++i) {
840 if (bf.processNextWeakRound()) {
845 if (real_iter_num < curr_iter_num) {
846 // Optimal flow is found
850 // Search for node disjoint negative cycles
851 std::vector<int> state(_res_node_num, 0);
853 for (int u = 0; u != _res_node_num; ++u) {
854 if (state[u] != 0) continue;
857 for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
858 -1 : rgr.id(rgr.source(pred[v]))) {
861 if (v != -1 && state[v] == id) {
862 // A negative cycle is found
865 StaticDigraph::Arc a = pred[v];
866 Value d, delta = _res_cap[rgr.id(a)];
867 cycle.push_back(rgr.id(a));
868 while (rgr.id(rgr.source(a)) != v) {
869 a = pred_map[rgr.source(a)];
870 d = _res_cap[rgr.id(a)];
871 if (d < delta) delta = d;
872 cycle.push_back(rgr.id(a));
875 // Augment along the cycle
876 for (int i = 0; i < int(cycle.size()); ++i) {
878 _res_cap[j] -= delta;
879 _res_cap[_reverse[j]] += delta;
885 // Increase iteration limit if no cycle is found
887 length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
893 // Execute the "Minimum Mean Cycle Canceling" method
894 void startMinMeanCycleCanceling() {
895 typedef SimplePath<StaticDigraph> SPath;
896 typedef typename SPath::ArcIt SPathArcIt;
897 typedef typename Howard<StaticDigraph, CostArcMap>
898 ::template SetPath<SPath>::Create MMC;
901 MMC mmc(_sgr, _cost_map);
903 buildResidualNetwork();
904 while (mmc.findMinMean() && mmc.cycleLength() < 0) {
908 // Compute delta value
910 for (SPathArcIt a(cycle); a != INVALID; ++a) {
911 Value d = _res_cap[_id_vec[_sgr.id(a)]];
912 if (d < delta) delta = d;
915 // Augment along the cycle
916 for (SPathArcIt a(cycle); a != INVALID; ++a) {
917 int j = _id_vec[_sgr.id(a)];
918 _res_cap[j] -= delta;
919 _res_cap[_reverse[j]] += delta;
922 // Rebuild the residual network
923 buildResidualNetwork();
927 // Execute the "Cancel And Tighten" method
928 void startCancelAndTighten() {
929 // Constants for the min mean cycle computations
930 const double LIMIT_FACTOR = 1.0;
931 const int MIN_LIMIT = 5;
933 // Contruct auxiliary data vectors
934 DoubleVector pi(_res_node_num, 0.0);
935 IntVector level(_res_node_num);
936 CharVector reached(_res_node_num);
937 CharVector processed(_res_node_num);
938 IntVector pred_node(_res_node_num);
939 IntVector pred_arc(_res_node_num);
940 std::vector<int> stack(_res_node_num);
941 std::vector<int> proc_vector(_res_node_num);
943 // Initialize epsilon
945 for (int a = 0; a != _res_arc_num; ++a) {
946 if (_res_cap[a] > 0 && -_cost[a] > epsilon)
951 Tolerance<double> tol;
953 int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
954 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
956 while (epsilon * _res_node_num >= 1) {
957 // Find and cancel cycles in the admissible network using DFS
958 for (int u = 0; u != _res_node_num; ++u) {
960 processed[u] = false;
964 for (int start = 0; start != _res_node_num; ++start) {
965 if (reached[start]) continue;
968 reached[start] = true;
969 pred_arc[start] = -1;
970 pred_node[start] = -1;
972 // Find the first admissible outgoing arc
973 double p = pi[start];
974 int a = _first_out[start];
975 int last_out = _first_out[start+1];
976 for (; a != last_out && (_res_cap[a] == 0 ||
977 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
979 processed[start] = true;
980 proc_vector[++proc_head] = start;
983 stack[++stack_head] = a;
985 while (stack_head >= 0) {
986 int sa = stack[stack_head];
991 // A new node is reached
997 last_out = _first_out[v+1];
998 for (; a != last_out && (_res_cap[a] == 0 ||
999 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1000 stack[++stack_head] = a == last_out ? -1 : a;
1002 if (!processed[v]) {
1005 Value d, delta = _res_cap[sa];
1006 for (n = u; n != v; n = pred_node[n]) {
1007 d = _res_cap[pred_arc[n]];
1014 // Augment along the cycle
1015 _res_cap[sa] -= delta;
1016 _res_cap[_reverse[sa]] += delta;
1017 for (n = u; n != v; n = pred_node[n]) {
1018 int pa = pred_arc[n];
1019 _res_cap[pa] -= delta;
1020 _res_cap[_reverse[pa]] += delta;
1022 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1030 // Find the next admissible outgoing arc
1032 a = stack[stack_head] + 1;
1033 last_out = _first_out[v+1];
1034 for (; a != last_out && (_res_cap[a] == 0 ||
1035 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1036 stack[stack_head] = a == last_out ? -1 : a;
1039 while (stack_head >= 0 && stack[stack_head] == -1) {
1040 processed[v] = true;
1041 proc_vector[++proc_head] = v;
1042 if (--stack_head >= 0) {
1043 // Find the next admissible outgoing arc
1044 v = _source[stack[stack_head]];
1046 a = stack[stack_head] + 1;
1047 last_out = _first_out[v+1];
1048 for (; a != last_out && (_res_cap[a] == 0 ||
1049 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1050 stack[stack_head] = a == last_out ? -1 : a;
1056 // Tighten potentials and epsilon
1058 for (int u = 0; u != _res_node_num; ++u) {
1061 for (int i = proc_head; i > 0; --i) {
1062 int u = proc_vector[i];
1064 int l = level[u] + 1;
1065 int last_out = _first_out[u+1];
1066 for (int a = _first_out[u]; a != last_out; ++a) {
1068 if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1069 l > level[v]) level[v] = l;
1073 // Modify potentials
1074 double q = std::numeric_limits<double>::max();
1075 for (int u = 0; u != _res_node_num; ++u) {
1077 double p, pu = pi[u];
1078 int last_out = _first_out[u+1];
1079 for (int a = _first_out[u]; a != last_out; ++a) {
1080 if (_res_cap[a] == 0) continue;
1082 int ld = lu - level[v];
1084 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1089 for (int u = 0; u != _res_node_num; ++u) {
1090 pi[u] -= q * level[u];
1095 for (int u = 0; u != _res_node_num; ++u) {
1096 double curr, pu = pi[u];
1097 int last_out = _first_out[u+1];
1098 for (int a = _first_out[u]; a != last_out; ++a) {
1099 if (_res_cap[a] == 0) continue;
1100 curr = _cost[a] + pu - pi[_target[a]];
1101 if (-curr > epsilon) epsilon = -curr;
1105 typedef Howard<StaticDigraph, CostArcMap> MMC;
1106 typedef typename BellmanFord<StaticDigraph, CostArcMap>
1107 ::template SetDistMap<CostNodeMap>::Create BF;
1109 // Set epsilon to the minimum cycle mean
1110 buildResidualNetwork();
1111 MMC mmc(_sgr, _cost_map);
1113 epsilon = -mmc.cycleMean();
1114 Cost cycle_cost = mmc.cycleLength();
1115 int cycle_size = mmc.cycleArcNum();
1117 // Compute feasible potentials for the current epsilon
1118 for (int i = 0; i != int(_cost_vec.size()); ++i) {
1119 _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1121 BF bf(_sgr, _cost_map);
1122 bf.distMap(_pi_map);
1125 for (int u = 0; u != _res_node_num; ++u) {
1126 pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1134 }; //class CycleCanceling
1140 #endif //LEMON_CYCLE_CANCELING_H