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");
253 // Reset data structures
258 /// The parameters of the algorithm can be specified using these
263 /// \brief Set the lower bounds on the arcs.
265 /// This function sets the lower bounds on the arcs.
266 /// If it is not used before calling \ref run(), the lower bounds
267 /// will be set to zero on all arcs.
269 /// \param map An arc map storing the lower bounds.
270 /// Its \c Value type must be convertible to the \c Value type
271 /// of the algorithm.
273 /// \return <tt>(*this)</tt>
274 template <typename LowerMap>
275 CycleCanceling& lowerMap(const LowerMap& map) {
277 for (ArcIt a(_graph); a != INVALID; ++a) {
278 _lower[_arc_idf[a]] = map[a];
279 _lower[_arc_idb[a]] = map[a];
284 /// \brief Set the upper bounds (capacities) on the arcs.
286 /// This function sets the upper bounds (capacities) on the arcs.
287 /// If it is not used before calling \ref run(), the upper bounds
288 /// will be set to \ref INF on all arcs (i.e. the flow value will be
289 /// unbounded from above).
291 /// \param map An arc map storing the upper bounds.
292 /// Its \c Value type must be convertible to the \c Value type
293 /// of the algorithm.
295 /// \return <tt>(*this)</tt>
296 template<typename UpperMap>
297 CycleCanceling& upperMap(const UpperMap& map) {
298 for (ArcIt a(_graph); a != INVALID; ++a) {
299 _upper[_arc_idf[a]] = map[a];
304 /// \brief Set the costs of the arcs.
306 /// This function sets the costs of the arcs.
307 /// If it is not used before calling \ref run(), the costs
308 /// will be set to \c 1 on all arcs.
310 /// \param map An arc map storing the costs.
311 /// Its \c Value type must be convertible to the \c Cost type
312 /// of the algorithm.
314 /// \return <tt>(*this)</tt>
315 template<typename CostMap>
316 CycleCanceling& costMap(const CostMap& map) {
317 for (ArcIt a(_graph); a != INVALID; ++a) {
318 _cost[_arc_idf[a]] = map[a];
319 _cost[_arc_idb[a]] = -map[a];
324 /// \brief Set the supply values of the nodes.
326 /// This function sets the supply values of the nodes.
327 /// If neither this function nor \ref stSupply() is used before
328 /// calling \ref run(), the supply of each node will be set to zero.
330 /// \param map A node map storing the supply values.
331 /// Its \c Value type must be convertible to the \c Value type
332 /// of the algorithm.
334 /// \return <tt>(*this)</tt>
335 template<typename SupplyMap>
336 CycleCanceling& supplyMap(const SupplyMap& map) {
337 for (NodeIt n(_graph); n != INVALID; ++n) {
338 _supply[_node_id[n]] = map[n];
343 /// \brief Set single source and target nodes and a supply value.
345 /// This function sets a single source node and a single target node
346 /// and the required flow value.
347 /// If neither this function nor \ref supplyMap() is used before
348 /// calling \ref run(), the supply of each node will be set to zero.
350 /// Using this function has the same effect as using \ref supplyMap()
351 /// with such a map in which \c k is assigned to \c s, \c -k is
352 /// assigned to \c t and all other nodes have zero supply value.
354 /// \param s The source node.
355 /// \param t The target node.
356 /// \param k The required amount of flow from node \c s to node \c t
357 /// (i.e. the supply of \c s and the demand of \c t).
359 /// \return <tt>(*this)</tt>
360 CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
361 for (int i = 0; i != _res_node_num; ++i) {
364 _supply[_node_id[s]] = k;
365 _supply[_node_id[t]] = -k;
371 /// \name Execution control
372 /// The algorithm can be executed using \ref run().
376 /// \brief Run the algorithm.
378 /// This function runs the algorithm.
379 /// The paramters can be specified using functions \ref lowerMap(),
380 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
383 /// CycleCanceling<ListDigraph> cc(graph);
384 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
385 /// .supplyMap(sup).run();
388 /// This function can be called more than once. All the given parameters
389 /// are kept for the next call, unless \ref resetParams() or \ref reset()
390 /// is used, thus only the modified parameters have to be set again.
391 /// If the underlying digraph was also modified after the construction
392 /// of the class (or the last \ref reset() call), then the \ref reset()
393 /// function must be called.
395 /// \param method The cycle-canceling method that will be used.
396 /// For more information, see \ref Method.
398 /// \return \c INFEASIBLE if no feasible flow exists,
399 /// \n \c OPTIMAL if the problem has optimal solution
400 /// (i.e. it is feasible and bounded), and the algorithm has found
401 /// optimal flow and node potentials (primal and dual solutions),
402 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
403 /// and infinite upper bound. It means that the objective function
404 /// is unbounded on that arc, however, note that it could actually be
405 /// bounded over the feasible flows, but this algroithm cannot handle
408 /// \see ProblemType, Method
409 /// \see resetParams(), reset()
410 ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
411 ProblemType pt = init();
412 if (pt != OPTIMAL) return pt;
417 /// \brief Reset all the parameters that have been given before.
419 /// This function resets all the paramaters that have been given
420 /// before using functions \ref lowerMap(), \ref upperMap(),
421 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
423 /// It is useful for multiple \ref run() calls. Basically, all the given
424 /// parameters are kept for the next \ref run() call, unless
425 /// \ref resetParams() or \ref reset() is used.
426 /// If the underlying digraph was also modified after the construction
427 /// of the class or the last \ref reset() call, then the \ref reset()
428 /// function must be used, otherwise \ref resetParams() is sufficient.
432 /// CycleCanceling<ListDigraph> cs(graph);
435 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
436 /// .supplyMap(sup).run();
438 /// // Run again with modified cost map (resetParams() is not called,
439 /// // so only the cost map have to be set again)
441 /// cc.costMap(cost).run();
443 /// // Run again from scratch using resetParams()
444 /// // (the lower bounds will be set to zero on all arcs)
445 /// cc.resetParams();
446 /// cc.upperMap(capacity).costMap(cost)
447 /// .supplyMap(sup).run();
450 /// \return <tt>(*this)</tt>
452 /// \see reset(), run()
453 CycleCanceling& resetParams() {
454 for (int i = 0; i != _res_node_num; ++i) {
457 int limit = _first_out[_root];
458 for (int j = 0; j != limit; ++j) {
461 _cost[j] = _forward[j] ? 1 : -1;
463 for (int j = limit; j != _res_arc_num; ++j) {
467 _cost[_reverse[j]] = 0;
473 /// \brief Reset the internal data structures and all the parameters
474 /// that have been given before.
476 /// This function resets the internal data structures and all the
477 /// paramaters that have been given before using functions \ref lowerMap(),
478 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
480 /// It is useful for multiple \ref run() calls. Basically, all the given
481 /// parameters are kept for the next \ref run() call, unless
482 /// \ref resetParams() or \ref reset() is used.
483 /// If the underlying digraph was also modified after the construction
484 /// of the class or the last \ref reset() call, then the \ref reset()
485 /// function must be used, otherwise \ref resetParams() is sufficient.
487 /// See \ref resetParams() for examples.
489 /// \return <tt>(*this)</tt>
491 /// \see resetParams(), run()
492 CycleCanceling& reset() {
494 _node_num = countNodes(_graph);
495 _arc_num = countArcs(_graph);
496 _res_node_num = _node_num + 1;
497 _res_arc_num = 2 * (_arc_num + _node_num);
500 _first_out.resize(_res_node_num + 1);
501 _forward.resize(_res_arc_num);
502 _source.resize(_res_arc_num);
503 _target.resize(_res_arc_num);
504 _reverse.resize(_res_arc_num);
506 _lower.resize(_res_arc_num);
507 _upper.resize(_res_arc_num);
508 _cost.resize(_res_arc_num);
509 _supply.resize(_res_node_num);
511 _res_cap.resize(_res_arc_num);
512 _pi.resize(_res_node_num);
514 _arc_vec.reserve(_res_arc_num);
515 _cost_vec.reserve(_res_arc_num);
516 _id_vec.reserve(_res_arc_num);
519 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
520 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
524 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
526 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
530 _target[j] = _node_id[_graph.runningNode(a)];
532 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
536 _target[j] = _node_id[_graph.runningNode(a)];
549 _first_out[_res_node_num] = k;
550 for (ArcIt a(_graph); a != INVALID; ++a) {
551 int fi = _arc_idf[a];
552 int bi = _arc_idb[a];
564 /// \name Query Functions
565 /// The results of the algorithm can be obtained using these
567 /// The \ref run() function must be called before using them.
571 /// \brief Return the total cost of the found flow.
573 /// This function returns the total cost of the found flow.
574 /// Its complexity is O(e).
576 /// \note The return type of the function can be specified as a
577 /// template parameter. For example,
579 /// cc.totalCost<double>();
581 /// It is useful if the total cost cannot be stored in the \c Cost
582 /// type of the algorithm, which is the default return type of the
585 /// \pre \ref run() must be called before using this function.
586 template <typename Number>
587 Number totalCost() const {
589 for (ArcIt a(_graph); a != INVALID; ++a) {
591 c += static_cast<Number>(_res_cap[i]) *
592 (-static_cast<Number>(_cost[i]));
598 Cost totalCost() const {
599 return totalCost<Cost>();
603 /// \brief Return the flow on the given arc.
605 /// This function returns the flow on the given arc.
607 /// \pre \ref run() must be called before using this function.
608 Value flow(const Arc& a) const {
609 return _res_cap[_arc_idb[a]];
612 /// \brief Return the flow map (the primal solution).
614 /// This function copies the flow value on each arc into the given
615 /// map. The \c Value type of the algorithm must be convertible to
616 /// the \c Value type of the map.
618 /// \pre \ref run() must be called before using this function.
619 template <typename FlowMap>
620 void flowMap(FlowMap &map) const {
621 for (ArcIt a(_graph); a != INVALID; ++a) {
622 map.set(a, _res_cap[_arc_idb[a]]);
626 /// \brief Return the potential (dual value) of the given node.
628 /// This function returns the potential (dual value) of the
631 /// \pre \ref run() must be called before using this function.
632 Cost potential(const Node& n) const {
633 return static_cast<Cost>(_pi[_node_id[n]]);
636 /// \brief Return the potential map (the dual solution).
638 /// This function copies the potential (dual value) of each node
639 /// into the given map.
640 /// The \c Cost type of the algorithm must be convertible to the
641 /// \c Value type of the map.
643 /// \pre \ref run() must be called before using this function.
644 template <typename PotentialMap>
645 void potentialMap(PotentialMap &map) const {
646 for (NodeIt n(_graph); n != INVALID; ++n) {
647 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
655 // Initialize the algorithm
657 if (_res_node_num <= 1) return INFEASIBLE;
659 // Check the sum of supply values
661 for (int i = 0; i != _root; ++i) {
662 _sum_supply += _supply[i];
664 if (_sum_supply > 0) return INFEASIBLE;
667 // Initialize vectors
668 for (int i = 0; i != _res_node_num; ++i) {
671 ValueVector excess(_supply);
673 // Remove infinite upper bounds and check negative arcs
674 const Value MAX = std::numeric_limits<Value>::max();
677 for (int i = 0; i != _root; ++i) {
678 last_out = _first_out[i+1];
679 for (int j = _first_out[i]; j != last_out; ++j) {
681 Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
682 if (c >= MAX) return UNBOUNDED;
684 excess[_target[j]] += c;
689 for (int i = 0; i != _root; ++i) {
690 last_out = _first_out[i+1];
691 for (int j = _first_out[i]; j != last_out; ++j) {
692 if (_forward[j] && _cost[j] < 0) {
694 if (c >= MAX) return UNBOUNDED;
696 excess[_target[j]] += c;
701 Value ex, max_cap = 0;
702 for (int i = 0; i != _res_node_num; ++i) {
704 if (ex < 0) max_cap -= ex;
706 for (int j = 0; j != _res_arc_num; ++j) {
707 if (_upper[j] >= MAX) _upper[j] = max_cap;
710 // Initialize maps for Circulation and remove non-zero lower bounds
711 ConstMap<Arc, Value> low(0);
712 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
713 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
714 ValueArcMap cap(_graph), flow(_graph);
715 ValueNodeMap sup(_graph);
716 for (NodeIt n(_graph); n != INVALID; ++n) {
717 sup[n] = _supply[_node_id[n]];
720 for (ArcIt a(_graph); a != INVALID; ++a) {
723 cap[a] = _upper[j] - c;
724 sup[_graph.source(a)] -= c;
725 sup[_graph.target(a)] += c;
728 for (ArcIt a(_graph); a != INVALID; ++a) {
729 cap[a] = _upper[_arc_idf[a]];
733 // Find a feasible flow using Circulation
734 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
735 circ(_graph, low, cap, sup);
736 if (!circ.flowMap(flow).run()) return INFEASIBLE;
738 // Set residual capacities and handle GEQ supply type
739 if (_sum_supply < 0) {
740 for (ArcIt a(_graph); a != INVALID; ++a) {
742 _res_cap[_arc_idf[a]] = cap[a] - fa;
743 _res_cap[_arc_idb[a]] = fa;
744 sup[_graph.source(a)] -= fa;
745 sup[_graph.target(a)] += fa;
747 for (NodeIt n(_graph); n != INVALID; ++n) {
748 excess[_node_id[n]] = sup[n];
750 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
752 int ra = _reverse[a];
753 _res_cap[a] = -_sum_supply + 1;
754 _res_cap[ra] = -excess[u];
759 for (ArcIt a(_graph); a != INVALID; ++a) {
761 _res_cap[_arc_idf[a]] = cap[a] - fa;
762 _res_cap[_arc_idb[a]] = fa;
764 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
765 int ra = _reverse[a];
776 // Build a StaticDigraph structure containing the current
778 void buildResidualNetwork() {
782 for (int j = 0; j != _res_arc_num; ++j) {
783 if (_res_cap[j] > 0) {
784 _arc_vec.push_back(IntPair(_source[j], _target[j]));
785 _cost_vec.push_back(_cost[j]);
786 _id_vec.push_back(j);
789 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
792 // Execute the algorithm and transform the results
793 void start(Method method) {
794 // Execute the algorithm
796 case SIMPLE_CYCLE_CANCELING:
797 startSimpleCycleCanceling();
799 case MINIMUM_MEAN_CYCLE_CANCELING:
800 startMinMeanCycleCanceling();
802 case CANCEL_AND_TIGHTEN:
803 startCancelAndTighten();
807 // Compute node potentials
808 if (method != SIMPLE_CYCLE_CANCELING) {
809 buildResidualNetwork();
810 typename BellmanFord<StaticDigraph, CostArcMap>
811 ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
817 // Handle non-zero lower bounds
819 int limit = _first_out[_root];
820 for (int j = 0; j != limit; ++j) {
821 if (!_forward[j]) _res_cap[j] += _lower[j];
826 // Execute the "Simple Cycle Canceling" method
827 void startSimpleCycleCanceling() {
828 // Constants for computing the iteration limits
829 const int BF_FIRST_LIMIT = 2;
830 const double BF_LIMIT_FACTOR = 1.5;
832 typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
833 typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
834 typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
835 typedef typename BellmanFord<ResDigraph, CostArcMap>
836 ::template SetDistMap<CostNodeMap>
837 ::template SetPredMap<PredMap>::Create BF;
839 // Build the residual network
842 for (int j = 0; j != _res_arc_num; ++j) {
843 _arc_vec.push_back(IntPair(_source[j], _target[j]));
844 _cost_vec.push_back(_cost[j]);
846 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
848 FilterMap filter_map(_res_cap);
849 ResDigraph rgr(_sgr, filter_map);
850 std::vector<int> cycle;
851 std::vector<StaticDigraph::Arc> pred(_res_arc_num);
852 PredMap pred_map(pred);
853 BF bf(rgr, _cost_map);
854 bf.distMap(_pi_map).predMap(pred_map);
856 int length_bound = BF_FIRST_LIMIT;
857 bool optimal = false;
861 bool cycle_found = false;
862 while (!cycle_found) {
863 // Perform some iterations of the Bellman-Ford algorithm
864 int curr_iter_num = iter_num + length_bound <= _node_num ?
865 length_bound : _node_num - iter_num;
866 iter_num += curr_iter_num;
867 int real_iter_num = curr_iter_num;
868 for (int i = 0; i < curr_iter_num; ++i) {
869 if (bf.processNextWeakRound()) {
874 if (real_iter_num < curr_iter_num) {
875 // Optimal flow is found
879 // Search for node disjoint negative cycles
880 std::vector<int> state(_res_node_num, 0);
882 for (int u = 0; u != _res_node_num; ++u) {
883 if (state[u] != 0) continue;
886 for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
887 -1 : rgr.id(rgr.source(pred[v]))) {
890 if (v != -1 && state[v] == id) {
891 // A negative cycle is found
894 StaticDigraph::Arc a = pred[v];
895 Value d, delta = _res_cap[rgr.id(a)];
896 cycle.push_back(rgr.id(a));
897 while (rgr.id(rgr.source(a)) != v) {
898 a = pred_map[rgr.source(a)];
899 d = _res_cap[rgr.id(a)];
900 if (d < delta) delta = d;
901 cycle.push_back(rgr.id(a));
904 // Augment along the cycle
905 for (int i = 0; i < int(cycle.size()); ++i) {
907 _res_cap[j] -= delta;
908 _res_cap[_reverse[j]] += delta;
914 // Increase iteration limit if no cycle is found
916 length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
922 // Execute the "Minimum Mean Cycle Canceling" method
923 void startMinMeanCycleCanceling() {
924 typedef SimplePath<StaticDigraph> SPath;
925 typedef typename SPath::ArcIt SPathArcIt;
926 typedef typename Howard<StaticDigraph, CostArcMap>
927 ::template SetPath<SPath>::Create MMC;
930 MMC mmc(_sgr, _cost_map);
932 buildResidualNetwork();
933 while (mmc.findMinMean() && mmc.cycleLength() < 0) {
937 // Compute delta value
939 for (SPathArcIt a(cycle); a != INVALID; ++a) {
940 Value d = _res_cap[_id_vec[_sgr.id(a)]];
941 if (d < delta) delta = d;
944 // Augment along the cycle
945 for (SPathArcIt a(cycle); a != INVALID; ++a) {
946 int j = _id_vec[_sgr.id(a)];
947 _res_cap[j] -= delta;
948 _res_cap[_reverse[j]] += delta;
951 // Rebuild the residual network
952 buildResidualNetwork();
956 // Execute the "Cancel And Tighten" method
957 void startCancelAndTighten() {
958 // Constants for the min mean cycle computations
959 const double LIMIT_FACTOR = 1.0;
960 const int MIN_LIMIT = 5;
962 // Contruct auxiliary data vectors
963 DoubleVector pi(_res_node_num, 0.0);
964 IntVector level(_res_node_num);
965 CharVector reached(_res_node_num);
966 CharVector processed(_res_node_num);
967 IntVector pred_node(_res_node_num);
968 IntVector pred_arc(_res_node_num);
969 std::vector<int> stack(_res_node_num);
970 std::vector<int> proc_vector(_res_node_num);
972 // Initialize epsilon
974 for (int a = 0; a != _res_arc_num; ++a) {
975 if (_res_cap[a] > 0 && -_cost[a] > epsilon)
980 Tolerance<double> tol;
982 int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
983 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
985 while (epsilon * _res_node_num >= 1) {
986 // Find and cancel cycles in the admissible network using DFS
987 for (int u = 0; u != _res_node_num; ++u) {
989 processed[u] = false;
993 for (int start = 0; start != _res_node_num; ++start) {
994 if (reached[start]) continue;
997 reached[start] = true;
998 pred_arc[start] = -1;
999 pred_node[start] = -1;
1001 // Find the first admissible outgoing arc
1002 double p = pi[start];
1003 int a = _first_out[start];
1004 int last_out = _first_out[start+1];
1005 for (; a != last_out && (_res_cap[a] == 0 ||
1006 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1007 if (a == last_out) {
1008 processed[start] = true;
1009 proc_vector[++proc_head] = start;
1012 stack[++stack_head] = a;
1014 while (stack_head >= 0) {
1015 int sa = stack[stack_head];
1016 int u = _source[sa];
1017 int v = _target[sa];
1020 // A new node is reached
1026 last_out = _first_out[v+1];
1027 for (; a != last_out && (_res_cap[a] == 0 ||
1028 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1029 stack[++stack_head] = a == last_out ? -1 : a;
1031 if (!processed[v]) {
1034 Value d, delta = _res_cap[sa];
1035 for (n = u; n != v; n = pred_node[n]) {
1036 d = _res_cap[pred_arc[n]];
1043 // Augment along the cycle
1044 _res_cap[sa] -= delta;
1045 _res_cap[_reverse[sa]] += delta;
1046 for (n = u; n != v; n = pred_node[n]) {
1047 int pa = pred_arc[n];
1048 _res_cap[pa] -= delta;
1049 _res_cap[_reverse[pa]] += delta;
1051 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1059 // Find the next admissible outgoing arc
1061 a = stack[stack_head] + 1;
1062 last_out = _first_out[v+1];
1063 for (; a != last_out && (_res_cap[a] == 0 ||
1064 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1065 stack[stack_head] = a == last_out ? -1 : a;
1068 while (stack_head >= 0 && stack[stack_head] == -1) {
1069 processed[v] = true;
1070 proc_vector[++proc_head] = v;
1071 if (--stack_head >= 0) {
1072 // Find the next admissible outgoing arc
1073 v = _source[stack[stack_head]];
1075 a = stack[stack_head] + 1;
1076 last_out = _first_out[v+1];
1077 for (; a != last_out && (_res_cap[a] == 0 ||
1078 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1079 stack[stack_head] = a == last_out ? -1 : a;
1085 // Tighten potentials and epsilon
1087 for (int u = 0; u != _res_node_num; ++u) {
1090 for (int i = proc_head; i > 0; --i) {
1091 int u = proc_vector[i];
1093 int l = level[u] + 1;
1094 int last_out = _first_out[u+1];
1095 for (int a = _first_out[u]; a != last_out; ++a) {
1097 if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1098 l > level[v]) level[v] = l;
1102 // Modify potentials
1103 double q = std::numeric_limits<double>::max();
1104 for (int u = 0; u != _res_node_num; ++u) {
1106 double p, pu = pi[u];
1107 int last_out = _first_out[u+1];
1108 for (int a = _first_out[u]; a != last_out; ++a) {
1109 if (_res_cap[a] == 0) continue;
1111 int ld = lu - level[v];
1113 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1118 for (int u = 0; u != _res_node_num; ++u) {
1119 pi[u] -= q * level[u];
1124 for (int u = 0; u != _res_node_num; ++u) {
1125 double curr, pu = pi[u];
1126 int last_out = _first_out[u+1];
1127 for (int a = _first_out[u]; a != last_out; ++a) {
1128 if (_res_cap[a] == 0) continue;
1129 curr = _cost[a] + pu - pi[_target[a]];
1130 if (-curr > epsilon) epsilon = -curr;
1134 typedef Howard<StaticDigraph, CostArcMap> MMC;
1135 typedef typename BellmanFord<StaticDigraph, CostArcMap>
1136 ::template SetDistMap<CostNodeMap>::Create BF;
1138 // Set epsilon to the minimum cycle mean
1139 buildResidualNetwork();
1140 MMC mmc(_sgr, _cost_map);
1142 epsilon = -mmc.cycleMean();
1143 Cost cycle_cost = mmc.cycleLength();
1144 int cycle_size = mmc.cycleArcNum();
1146 // Compute feasible potentials for the current epsilon
1147 for (int i = 0; i != int(_cost_vec.size()); ++i) {
1148 _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1150 BF bf(_sgr, _cost_map);
1151 bf.distMap(_pi_map);
1154 for (int u = 0; u != _res_node_num; ++u) {
1155 pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1163 }; //class CycleCanceling
1169 #endif //LEMON_CYCLE_CANCELING_H