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 /// The most efficent one (both theoretically and practically)
50 /// is the \ref CANCEL_AND_TIGHTEN "Cancel and Tighten" algorithm,
51 /// thus it is the default method.
52 /// It is strongly polynomial, but in practice, it is typically much
53 /// slower than the scaling algorithms and NetworkSimplex.
55 /// Most of the parameters of the problem (except for the digraph)
56 /// can be given using separate functions, and the algorithm can be
57 /// executed using the \ref run() function. If some parameters are not
58 /// specified, then default values will be used.
60 /// \tparam GR The digraph type the algorithm runs on.
61 /// \tparam V The number type used for flow amounts, capacity bounds
62 /// and supply values in the algorithm. By default, it is \c int.
63 /// \tparam C The number type used for costs and potentials in the
64 /// algorithm. By default, it is the same as \c V.
66 /// \warning Both number types must be signed and all input data must
68 /// \warning This algorithm does not support negative costs for such
69 /// arcs that have infinite upper bound.
71 /// \note For more information about the three available methods,
74 template <typename GR, typename V, typename C>
76 template <typename GR, typename V = int, typename C = V>
82 /// The type of the digraph
84 /// The type of the flow amounts, capacity bounds and supply values
86 /// The type of the arc costs
91 /// \brief Problem type constants for the \c run() function.
93 /// Enum type containing the problem type constants that can be
94 /// returned by the \ref run() function of the algorithm.
96 /// The problem has no feasible solution (flow).
98 /// The problem has optimal solution (i.e. it is feasible and
99 /// bounded), and the algorithm has found optimal flow and node
100 /// potentials (primal and dual solutions).
102 /// The digraph contains an arc of negative cost and infinite
103 /// upper bound. It means that the objective function is unbounded
104 /// on that arc, however, note that it could actually be bounded
105 /// over the feasible flows, but this algroithm cannot handle
110 /// \brief Constants for selecting the used method.
112 /// Enum type containing constants for selecting the used method
113 /// for the \ref run() function.
115 /// \ref CycleCanceling provides three different cycle-canceling
116 /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel and Tighten"
117 /// is used, which proved to be the most efficient and the most robust
118 /// on various test inputs.
119 /// However, the other methods can be selected using the \ref run()
120 /// function with the proper parameter.
122 /// A simple cycle-canceling method, which uses the
123 /// \ref BellmanFord "Bellman-Ford" algorithm with limited iteration
124 /// number for detecting negative cycles in the residual network.
125 SIMPLE_CYCLE_CANCELING,
126 /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
127 /// well-known strongly polynomial method. It improves along a
128 /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
129 /// Its running time complexity is O(n<sup>2</sup>m<sup>3</sup>log(n)).
130 MINIMUM_MEAN_CYCLE_CANCELING,
131 /// The "Cancel And Tighten" algorithm, which can be viewed as an
132 /// improved version of the previous method.
133 /// It is faster both in theory and in practice, its running time
134 /// complexity is O(n<sup>2</sup>m<sup>2</sup>log(n)).
140 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
142 typedef std::vector<int> IntVector;
143 typedef std::vector<char> CharVector;
144 typedef std::vector<double> DoubleVector;
145 typedef std::vector<Value> ValueVector;
146 typedef std::vector<Cost> CostVector;
150 template <typename KT, typename VT>
156 VectorMap(std::vector<Value>& v) : _v(v) {}
158 const Value& operator[](const Key& key) const {
159 return _v[StaticDigraph::id(key)];
162 Value& operator[](const Key& key) {
163 return _v[StaticDigraph::id(key)];
166 void set(const Key& key, const Value& val) {
167 _v[StaticDigraph::id(key)] = val;
171 std::vector<Value>& _v;
174 typedef VectorMap<StaticDigraph::Node, Cost> CostNodeMap;
175 typedef VectorMap<StaticDigraph::Arc, Cost> CostArcMap;
180 // Data related to the underlying digraph
188 // Parameters of the problem
192 // Data structures for storing the digraph
196 IntVector _first_out;
208 ValueVector _res_cap;
211 // Data for a StaticDigraph structure
212 typedef std::pair<int, int> IntPair;
214 std::vector<IntPair> _arc_vec;
215 std::vector<Cost> _cost_vec;
217 CostArcMap _cost_map;
222 /// \brief Constant for infinite upper bounds (capacities).
224 /// Constant for infinite upper bounds (capacities).
225 /// It is \c std::numeric_limits<Value>::infinity() if available,
226 /// \c std::numeric_limits<Value>::max() otherwise.
231 /// \brief Constructor.
233 /// The constructor of the class.
235 /// \param graph The digraph the algorithm runs on.
236 CycleCanceling(const GR& graph) :
237 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
238 _cost_map(_cost_vec), _pi_map(_pi),
239 INF(std::numeric_limits<Value>::has_infinity ?
240 std::numeric_limits<Value>::infinity() :
241 std::numeric_limits<Value>::max())
243 // Check the number types
244 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
245 "The flow type of CycleCanceling must be signed");
246 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
247 "The cost type of CycleCanceling must be signed");
250 _node_num = countNodes(_graph);
251 _arc_num = countArcs(_graph);
252 _res_node_num = _node_num + 1;
253 _res_arc_num = 2 * (_arc_num + _node_num);
256 _first_out.resize(_res_node_num + 1);
257 _forward.resize(_res_arc_num);
258 _source.resize(_res_arc_num);
259 _target.resize(_res_arc_num);
260 _reverse.resize(_res_arc_num);
262 _lower.resize(_res_arc_num);
263 _upper.resize(_res_arc_num);
264 _cost.resize(_res_arc_num);
265 _supply.resize(_res_node_num);
267 _res_cap.resize(_res_arc_num);
268 _pi.resize(_res_node_num);
270 _arc_vec.reserve(_res_arc_num);
271 _cost_vec.reserve(_res_arc_num);
272 _id_vec.reserve(_res_arc_num);
275 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
276 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
280 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
282 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
286 _target[j] = _node_id[_graph.runningNode(a)];
288 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
292 _target[j] = _node_id[_graph.runningNode(a)];
305 _first_out[_res_node_num] = k;
306 for (ArcIt a(_graph); a != INVALID; ++a) {
307 int fi = _arc_idf[a];
308 int bi = _arc_idb[a];
318 /// The parameters of the algorithm can be specified using these
323 /// \brief Set the lower bounds on the arcs.
325 /// This function sets the lower bounds on the arcs.
326 /// If it is not used before calling \ref run(), the lower bounds
327 /// will be set to zero on all arcs.
329 /// \param map An arc map storing the lower bounds.
330 /// Its \c Value type must be convertible to the \c Value type
331 /// of the algorithm.
333 /// \return <tt>(*this)</tt>
334 template <typename LowerMap>
335 CycleCanceling& lowerMap(const LowerMap& map) {
337 for (ArcIt a(_graph); a != INVALID; ++a) {
338 _lower[_arc_idf[a]] = map[a];
339 _lower[_arc_idb[a]] = map[a];
344 /// \brief Set the upper bounds (capacities) on the arcs.
346 /// This function sets the upper bounds (capacities) on the arcs.
347 /// If it is not used before calling \ref run(), the upper bounds
348 /// will be set to \ref INF on all arcs (i.e. the flow value will be
349 /// unbounded from above).
351 /// \param map An arc map storing the upper bounds.
352 /// Its \c Value type must be convertible to the \c Value type
353 /// of the algorithm.
355 /// \return <tt>(*this)</tt>
356 template<typename UpperMap>
357 CycleCanceling& upperMap(const UpperMap& map) {
358 for (ArcIt a(_graph); a != INVALID; ++a) {
359 _upper[_arc_idf[a]] = map[a];
364 /// \brief Set the costs of the arcs.
366 /// This function sets the costs of the arcs.
367 /// If it is not used before calling \ref run(), the costs
368 /// will be set to \c 1 on all arcs.
370 /// \param map An arc map storing the costs.
371 /// Its \c Value type must be convertible to the \c Cost type
372 /// of the algorithm.
374 /// \return <tt>(*this)</tt>
375 template<typename CostMap>
376 CycleCanceling& costMap(const CostMap& map) {
377 for (ArcIt a(_graph); a != INVALID; ++a) {
378 _cost[_arc_idf[a]] = map[a];
379 _cost[_arc_idb[a]] = -map[a];
384 /// \brief Set the supply values of the nodes.
386 /// This function sets the supply values of the nodes.
387 /// If neither this function nor \ref stSupply() is used before
388 /// calling \ref run(), the supply of each node will be set to zero.
390 /// \param map A node map storing the supply values.
391 /// Its \c Value type must be convertible to the \c Value type
392 /// of the algorithm.
394 /// \return <tt>(*this)</tt>
395 template<typename SupplyMap>
396 CycleCanceling& supplyMap(const SupplyMap& map) {
397 for (NodeIt n(_graph); n != INVALID; ++n) {
398 _supply[_node_id[n]] = map[n];
403 /// \brief Set single source and target nodes and a supply value.
405 /// This function sets a single source node and a single target node
406 /// and the required flow value.
407 /// If neither this function nor \ref supplyMap() is used before
408 /// calling \ref run(), the supply of each node will be set to zero.
410 /// Using this function has the same effect as using \ref supplyMap()
411 /// with such a map in which \c k is assigned to \c s, \c -k is
412 /// assigned to \c t and all other nodes have zero supply value.
414 /// \param s The source node.
415 /// \param t The target node.
416 /// \param k The required amount of flow from node \c s to node \c t
417 /// (i.e. the supply of \c s and the demand of \c t).
419 /// \return <tt>(*this)</tt>
420 CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
421 for (int i = 0; i != _res_node_num; ++i) {
424 _supply[_node_id[s]] = k;
425 _supply[_node_id[t]] = -k;
431 /// \name Execution control
432 /// The algorithm can be executed using \ref run().
436 /// \brief Run the algorithm.
438 /// This function runs the algorithm.
439 /// The paramters can be specified using functions \ref lowerMap(),
440 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
443 /// CycleCanceling<ListDigraph> cc(graph);
444 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
445 /// .supplyMap(sup).run();
448 /// This function can be called more than once. All the parameters
449 /// that have been given are kept for the next call, unless
450 /// \ref reset() is called, thus only the modified parameters
451 /// have to be set again. See \ref reset() for examples.
452 /// However, the underlying digraph must not be modified after this
453 /// class have been constructed, since it copies and extends the graph.
455 /// \param method The cycle-canceling method that will be used.
456 /// For more information, see \ref Method.
458 /// \return \c INFEASIBLE if no feasible flow exists,
459 /// \n \c OPTIMAL if the problem has optimal solution
460 /// (i.e. it is feasible and bounded), and the algorithm has found
461 /// optimal flow and node potentials (primal and dual solutions),
462 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
463 /// and infinite upper bound. It means that the objective function
464 /// is unbounded on that arc, however, note that it could actually be
465 /// bounded over the feasible flows, but this algroithm cannot handle
468 /// \see ProblemType, Method
469 ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
470 ProblemType pt = init();
471 if (pt != OPTIMAL) return pt;
476 /// \brief Reset all the parameters that have been given before.
478 /// This function resets all the paramaters that have been given
479 /// before using functions \ref lowerMap(), \ref upperMap(),
480 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
482 /// It is useful for multiple run() calls. If this function is not
483 /// used, all the parameters given before are kept for the next
485 /// However, the underlying digraph must not be modified after this
486 /// class have been constructed, since it copies and extends the graph.
490 /// CycleCanceling<ListDigraph> cs(graph);
493 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
494 /// .supplyMap(sup).run();
496 /// // Run again with modified cost map (reset() is not called,
497 /// // so only the cost map have to be set again)
499 /// cc.costMap(cost).run();
501 /// // Run again from scratch using reset()
502 /// // (the lower bounds will be set to zero on all arcs)
504 /// cc.upperMap(capacity).costMap(cost)
505 /// .supplyMap(sup).run();
508 /// \return <tt>(*this)</tt>
509 CycleCanceling& reset() {
510 for (int i = 0; i != _res_node_num; ++i) {
513 int limit = _first_out[_root];
514 for (int j = 0; j != limit; ++j) {
517 _cost[j] = _forward[j] ? 1 : -1;
519 for (int j = limit; j != _res_arc_num; ++j) {
523 _cost[_reverse[j]] = 0;
531 /// \name Query Functions
532 /// The results of the algorithm can be obtained using these
534 /// The \ref run() function must be called before using them.
538 /// \brief Return the total cost of the found flow.
540 /// This function returns the total cost of the found flow.
541 /// Its complexity is O(e).
543 /// \note The return type of the function can be specified as a
544 /// template parameter. For example,
546 /// cc.totalCost<double>();
548 /// It is useful if the total cost cannot be stored in the \c Cost
549 /// type of the algorithm, which is the default return type of the
552 /// \pre \ref run() must be called before using this function.
553 template <typename Number>
554 Number totalCost() const {
556 for (ArcIt a(_graph); a != INVALID; ++a) {
558 c += static_cast<Number>(_res_cap[i]) *
559 (-static_cast<Number>(_cost[i]));
565 Cost totalCost() const {
566 return totalCost<Cost>();
570 /// \brief Return the flow on the given arc.
572 /// This function returns the flow on the given arc.
574 /// \pre \ref run() must be called before using this function.
575 Value flow(const Arc& a) const {
576 return _res_cap[_arc_idb[a]];
579 /// \brief Return the flow map (the primal solution).
581 /// This function copies the flow value on each arc into the given
582 /// map. The \c Value type of the algorithm must be convertible to
583 /// the \c Value type of the map.
585 /// \pre \ref run() must be called before using this function.
586 template <typename FlowMap>
587 void flowMap(FlowMap &map) const {
588 for (ArcIt a(_graph); a != INVALID; ++a) {
589 map.set(a, _res_cap[_arc_idb[a]]);
593 /// \brief Return the potential (dual value) of the given node.
595 /// This function returns the potential (dual value) of the
598 /// \pre \ref run() must be called before using this function.
599 Cost potential(const Node& n) const {
600 return static_cast<Cost>(_pi[_node_id[n]]);
603 /// \brief Return the potential map (the dual solution).
605 /// This function copies the potential (dual value) of each node
606 /// into the given map.
607 /// The \c Cost type of the algorithm must be convertible to the
608 /// \c Value type of the map.
610 /// \pre \ref run() must be called before using this function.
611 template <typename PotentialMap>
612 void potentialMap(PotentialMap &map) const {
613 for (NodeIt n(_graph); n != INVALID; ++n) {
614 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
622 // Initialize the algorithm
624 if (_res_node_num <= 1) return INFEASIBLE;
626 // Check the sum of supply values
628 for (int i = 0; i != _root; ++i) {
629 _sum_supply += _supply[i];
631 if (_sum_supply > 0) return INFEASIBLE;
634 // Initialize vectors
635 for (int i = 0; i != _res_node_num; ++i) {
638 ValueVector excess(_supply);
640 // Remove infinite upper bounds and check negative arcs
641 const Value MAX = std::numeric_limits<Value>::max();
644 for (int i = 0; i != _root; ++i) {
645 last_out = _first_out[i+1];
646 for (int j = _first_out[i]; j != last_out; ++j) {
648 Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
649 if (c >= MAX) return UNBOUNDED;
651 excess[_target[j]] += c;
656 for (int i = 0; i != _root; ++i) {
657 last_out = _first_out[i+1];
658 for (int j = _first_out[i]; j != last_out; ++j) {
659 if (_forward[j] && _cost[j] < 0) {
661 if (c >= MAX) return UNBOUNDED;
663 excess[_target[j]] += c;
668 Value ex, max_cap = 0;
669 for (int i = 0; i != _res_node_num; ++i) {
671 if (ex < 0) max_cap -= ex;
673 for (int j = 0; j != _res_arc_num; ++j) {
674 if (_upper[j] >= MAX) _upper[j] = max_cap;
677 // Initialize maps for Circulation and remove non-zero lower bounds
678 ConstMap<Arc, Value> low(0);
679 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
680 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
681 ValueArcMap cap(_graph), flow(_graph);
682 ValueNodeMap sup(_graph);
683 for (NodeIt n(_graph); n != INVALID; ++n) {
684 sup[n] = _supply[_node_id[n]];
687 for (ArcIt a(_graph); a != INVALID; ++a) {
690 cap[a] = _upper[j] - c;
691 sup[_graph.source(a)] -= c;
692 sup[_graph.target(a)] += c;
695 for (ArcIt a(_graph); a != INVALID; ++a) {
696 cap[a] = _upper[_arc_idf[a]];
700 // Find a feasible flow using Circulation
701 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
702 circ(_graph, low, cap, sup);
703 if (!circ.flowMap(flow).run()) return INFEASIBLE;
705 // Set residual capacities and handle GEQ supply type
706 if (_sum_supply < 0) {
707 for (ArcIt a(_graph); a != INVALID; ++a) {
709 _res_cap[_arc_idf[a]] = cap[a] - fa;
710 _res_cap[_arc_idb[a]] = fa;
711 sup[_graph.source(a)] -= fa;
712 sup[_graph.target(a)] += fa;
714 for (NodeIt n(_graph); n != INVALID; ++n) {
715 excess[_node_id[n]] = sup[n];
717 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
719 int ra = _reverse[a];
720 _res_cap[a] = -_sum_supply + 1;
721 _res_cap[ra] = -excess[u];
726 for (ArcIt a(_graph); a != INVALID; ++a) {
728 _res_cap[_arc_idf[a]] = cap[a] - fa;
729 _res_cap[_arc_idb[a]] = fa;
731 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
732 int ra = _reverse[a];
743 // Build a StaticDigraph structure containing the current
745 void buildResidualNetwork() {
749 for (int j = 0; j != _res_arc_num; ++j) {
750 if (_res_cap[j] > 0) {
751 _arc_vec.push_back(IntPair(_source[j], _target[j]));
752 _cost_vec.push_back(_cost[j]);
753 _id_vec.push_back(j);
756 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
759 // Execute the algorithm and transform the results
760 void start(Method method) {
761 // Execute the algorithm
763 case SIMPLE_CYCLE_CANCELING:
764 startSimpleCycleCanceling();
766 case MINIMUM_MEAN_CYCLE_CANCELING:
767 startMinMeanCycleCanceling();
769 case CANCEL_AND_TIGHTEN:
770 startCancelAndTighten();
774 // Compute node potentials
775 if (method != SIMPLE_CYCLE_CANCELING) {
776 buildResidualNetwork();
777 typename BellmanFord<StaticDigraph, CostArcMap>
778 ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
784 // Handle non-zero lower bounds
786 int limit = _first_out[_root];
787 for (int j = 0; j != limit; ++j) {
788 if (!_forward[j]) _res_cap[j] += _lower[j];
793 // Execute the "Simple Cycle Canceling" method
794 void startSimpleCycleCanceling() {
795 // Constants for computing the iteration limits
796 const int BF_FIRST_LIMIT = 2;
797 const double BF_LIMIT_FACTOR = 1.5;
799 typedef VectorMap<StaticDigraph::Arc, Value> FilterMap;
800 typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
801 typedef VectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
802 typedef typename BellmanFord<ResDigraph, CostArcMap>
803 ::template SetDistMap<CostNodeMap>
804 ::template SetPredMap<PredMap>::Create BF;
806 // Build the residual network
809 for (int j = 0; j != _res_arc_num; ++j) {
810 _arc_vec.push_back(IntPair(_source[j], _target[j]));
811 _cost_vec.push_back(_cost[j]);
813 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
815 FilterMap filter_map(_res_cap);
816 ResDigraph rgr(_sgr, filter_map);
817 std::vector<int> cycle;
818 std::vector<StaticDigraph::Arc> pred(_res_arc_num);
819 PredMap pred_map(pred);
820 BF bf(rgr, _cost_map);
821 bf.distMap(_pi_map).predMap(pred_map);
823 int length_bound = BF_FIRST_LIMIT;
824 bool optimal = false;
828 bool cycle_found = false;
829 while (!cycle_found) {
830 // Perform some iterations of the Bellman-Ford algorithm
831 int curr_iter_num = iter_num + length_bound <= _node_num ?
832 length_bound : _node_num - iter_num;
833 iter_num += curr_iter_num;
834 int real_iter_num = curr_iter_num;
835 for (int i = 0; i < curr_iter_num; ++i) {
836 if (bf.processNextWeakRound()) {
841 if (real_iter_num < curr_iter_num) {
842 // Optimal flow is found
846 // Search for node disjoint negative cycles
847 std::vector<int> state(_res_node_num, 0);
849 for (int u = 0; u != _res_node_num; ++u) {
850 if (state[u] != 0) continue;
853 for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
854 -1 : rgr.id(rgr.source(pred[v]))) {
857 if (v != -1 && state[v] == id) {
858 // A negative cycle is found
861 StaticDigraph::Arc a = pred[v];
862 Value d, delta = _res_cap[rgr.id(a)];
863 cycle.push_back(rgr.id(a));
864 while (rgr.id(rgr.source(a)) != v) {
865 a = pred_map[rgr.source(a)];
866 d = _res_cap[rgr.id(a)];
867 if (d < delta) delta = d;
868 cycle.push_back(rgr.id(a));
871 // Augment along the cycle
872 for (int i = 0; i < int(cycle.size()); ++i) {
874 _res_cap[j] -= delta;
875 _res_cap[_reverse[j]] += delta;
881 // Increase iteration limit if no cycle is found
883 length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
889 // Execute the "Minimum Mean Cycle Canceling" method
890 void startMinMeanCycleCanceling() {
891 typedef SimplePath<StaticDigraph> SPath;
892 typedef typename SPath::ArcIt SPathArcIt;
893 typedef typename Howard<StaticDigraph, CostArcMap>
894 ::template SetPath<SPath>::Create MMC;
897 MMC mmc(_sgr, _cost_map);
899 buildResidualNetwork();
900 while (mmc.findMinMean() && mmc.cycleLength() < 0) {
904 // Compute delta value
906 for (SPathArcIt a(cycle); a != INVALID; ++a) {
907 Value d = _res_cap[_id_vec[_sgr.id(a)]];
908 if (d < delta) delta = d;
911 // Augment along the cycle
912 for (SPathArcIt a(cycle); a != INVALID; ++a) {
913 int j = _id_vec[_sgr.id(a)];
914 _res_cap[j] -= delta;
915 _res_cap[_reverse[j]] += delta;
918 // Rebuild the residual network
919 buildResidualNetwork();
923 // Execute the "Cancel And Tighten" method
924 void startCancelAndTighten() {
925 // Constants for the min mean cycle computations
926 const double LIMIT_FACTOR = 1.0;
927 const int MIN_LIMIT = 5;
929 // Contruct auxiliary data vectors
930 DoubleVector pi(_res_node_num, 0.0);
931 IntVector level(_res_node_num);
932 CharVector reached(_res_node_num);
933 CharVector processed(_res_node_num);
934 IntVector pred_node(_res_node_num);
935 IntVector pred_arc(_res_node_num);
936 std::vector<int> stack(_res_node_num);
937 std::vector<int> proc_vector(_res_node_num);
939 // Initialize epsilon
941 for (int a = 0; a != _res_arc_num; ++a) {
942 if (_res_cap[a] > 0 && -_cost[a] > epsilon)
947 Tolerance<double> tol;
949 int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
950 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
952 while (epsilon * _res_node_num >= 1) {
953 // Find and cancel cycles in the admissible network using DFS
954 for (int u = 0; u != _res_node_num; ++u) {
956 processed[u] = false;
960 for (int start = 0; start != _res_node_num; ++start) {
961 if (reached[start]) continue;
964 reached[start] = true;
965 pred_arc[start] = -1;
966 pred_node[start] = -1;
968 // Find the first admissible outgoing arc
969 double p = pi[start];
970 int a = _first_out[start];
971 int last_out = _first_out[start+1];
972 for (; a != last_out && (_res_cap[a] == 0 ||
973 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
975 processed[start] = true;
976 proc_vector[++proc_head] = start;
979 stack[++stack_head] = a;
981 while (stack_head >= 0) {
982 int sa = stack[stack_head];
987 // A new node is reached
993 last_out = _first_out[v+1];
994 for (; a != last_out && (_res_cap[a] == 0 ||
995 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
996 stack[++stack_head] = a == last_out ? -1 : a;
1001 Value d, delta = _res_cap[sa];
1002 for (n = u; n != v; n = pred_node[n]) {
1003 d = _res_cap[pred_arc[n]];
1010 // Augment along the cycle
1011 _res_cap[sa] -= delta;
1012 _res_cap[_reverse[sa]] += delta;
1013 for (n = u; n != v; n = pred_node[n]) {
1014 int pa = pred_arc[n];
1015 _res_cap[pa] -= delta;
1016 _res_cap[_reverse[pa]] += delta;
1018 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1026 // Find the next admissible outgoing arc
1028 a = stack[stack_head] + 1;
1029 last_out = _first_out[v+1];
1030 for (; a != last_out && (_res_cap[a] == 0 ||
1031 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1032 stack[stack_head] = a == last_out ? -1 : a;
1035 while (stack_head >= 0 && stack[stack_head] == -1) {
1036 processed[v] = true;
1037 proc_vector[++proc_head] = v;
1038 if (--stack_head >= 0) {
1039 // Find the next admissible outgoing arc
1040 v = _source[stack[stack_head]];
1042 a = stack[stack_head] + 1;
1043 last_out = _first_out[v+1];
1044 for (; a != last_out && (_res_cap[a] == 0 ||
1045 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1046 stack[stack_head] = a == last_out ? -1 : a;
1052 // Tighten potentials and epsilon
1054 for (int u = 0; u != _res_node_num; ++u) {
1057 for (int i = proc_head; i > 0; --i) {
1058 int u = proc_vector[i];
1060 int l = level[u] + 1;
1061 int last_out = _first_out[u+1];
1062 for (int a = _first_out[u]; a != last_out; ++a) {
1064 if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1065 l > level[v]) level[v] = l;
1069 // Modify potentials
1070 double q = std::numeric_limits<double>::max();
1071 for (int u = 0; u != _res_node_num; ++u) {
1073 double p, pu = pi[u];
1074 int last_out = _first_out[u+1];
1075 for (int a = _first_out[u]; a != last_out; ++a) {
1076 if (_res_cap[a] == 0) continue;
1078 int ld = lu - level[v];
1080 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1085 for (int u = 0; u != _res_node_num; ++u) {
1086 pi[u] -= q * level[u];
1091 for (int u = 0; u != _res_node_num; ++u) {
1092 double curr, pu = pi[u];
1093 int last_out = _first_out[u+1];
1094 for (int a = _first_out[u]; a != last_out; ++a) {
1095 if (_res_cap[a] == 0) continue;
1096 curr = _cost[a] + pu - pi[_target[a]];
1097 if (-curr > epsilon) epsilon = -curr;
1101 typedef Howard<StaticDigraph, CostArcMap> MMC;
1102 typedef typename BellmanFord<StaticDigraph, CostArcMap>
1103 ::template SetDistMap<CostNodeMap>::Create BF;
1105 // Set epsilon to the minimum cycle mean
1106 buildResidualNetwork();
1107 MMC mmc(_sgr, _cost_map);
1109 epsilon = -mmc.cycleMean();
1110 Cost cycle_cost = mmc.cycleLength();
1111 int cycle_size = mmc.cycleArcNum();
1113 // Compute feasible potentials for the current epsilon
1114 for (int i = 0; i != int(_cost_vec.size()); ++i) {
1115 _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1117 BF bf(_sgr, _cost_map);
1118 bf.distMap(_pi_map);
1121 for (int u = 0; u != _res_node_num; ++u) {
1122 pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1130 }; //class CycleCanceling
1136 #endif //LEMON_CYCLE_CANCELING_H