1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2010
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_mmc.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 is the \ref CANCEL_AND_TIGHTEN
52 /// "Cancel-and-Tighten" algorithm, thus it is the default method.
53 /// It runs in strongly polynomial time, but in practice, it is typically
54 /// orders of magnitude slower than the scaling algorithms and
55 /// \ref NetworkSimplex.
56 /// (For more information, see \ref min_cost_flow_algs "the module page".)
58 /// Most of the parameters of the problem (except for the digraph)
59 /// can be given using separate functions, and the algorithm can be
60 /// executed using the \ref run() function. If some parameters are not
61 /// specified, then default values will be used.
63 /// \tparam GR The digraph type the algorithm runs on.
64 /// \tparam V The number type used for flow amounts, capacity bounds
65 /// and supply values in the algorithm. By default, it is \c int.
66 /// \tparam C The number type used for costs and potentials in the
67 /// algorithm. By default, it is the same as \c V.
69 /// \warning Both \c V and \c C must be signed number types.
70 /// \warning All input data (capacities, supply values, and costs) must
72 /// \warning This algorithm does not support negative costs for
73 /// arcs having infinite upper bound.
75 /// \note For more information about the three available methods,
78 template <typename GR, typename V, typename C>
80 template <typename GR, typename V = int, typename C = V>
86 /// The type of the digraph
88 /// The type of the flow amounts, capacity bounds and supply values
90 /// The type of the arc costs
95 /// \brief Problem type constants for the \c run() function.
97 /// Enum type containing the problem type constants that can be
98 /// returned by the \ref run() function of the algorithm.
100 /// The problem has no feasible solution (flow).
102 /// The problem has optimal solution (i.e. it is feasible and
103 /// bounded), and the algorithm has found optimal flow and node
104 /// potentials (primal and dual solutions).
106 /// The digraph contains an arc of negative cost and infinite
107 /// upper bound. It means that the objective function is unbounded
108 /// on that arc, however, note that it could actually be bounded
109 /// over the feasible flows, but this algroithm cannot handle
114 /// \brief Constants for selecting the used method.
116 /// Enum type containing constants for selecting the used method
117 /// for the \ref run() function.
119 /// \ref CycleCanceling provides three different cycle-canceling
120 /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel-and-Tighten"
121 /// is used, which is by far the most efficient and the most robust.
122 /// However, the other methods can be selected using the \ref run()
123 /// function with the proper parameter.
125 /// A simple cycle-canceling method, which uses the
126 /// \ref BellmanFord "Bellman-Ford" algorithm for detecting negative
127 /// cycles in the residual network.
128 /// The number of Bellman-Ford iterations is bounded by a successively
130 SIMPLE_CYCLE_CANCELING,
131 /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
132 /// well-known strongly polynomial method
133 /// \ref goldberg89cyclecanceling. It improves along a
134 /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
135 /// Its running time complexity is O(n<sup>2</sup>e<sup>3</sup>log(n)).
136 MINIMUM_MEAN_CYCLE_CANCELING,
137 /// The "Cancel-and-Tighten" algorithm, which can be viewed as an
138 /// improved version of the previous method
139 /// \ref goldberg89cyclecanceling.
140 /// It is faster both in theory and in practice, its running time
141 /// complexity is O(n<sup>2</sup>e<sup>2</sup>log(n)).
147 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
149 typedef std::vector<int> IntVector;
150 typedef std::vector<double> DoubleVector;
151 typedef std::vector<Value> ValueVector;
152 typedef std::vector<Cost> CostVector;
153 typedef std::vector<char> BoolVector;
154 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
158 template <typename KT, typename VT>
159 class StaticVectorMap {
164 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
166 const Value& operator[](const Key& key) const {
167 return _v[StaticDigraph::id(key)];
170 Value& operator[](const Key& key) {
171 return _v[StaticDigraph::id(key)];
174 void set(const Key& key, const Value& val) {
175 _v[StaticDigraph::id(key)] = val;
179 std::vector<Value>& _v;
182 typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
183 typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
188 // Data related to the underlying digraph
196 // Parameters of the problem
200 // Data structures for storing the digraph
204 IntVector _first_out;
216 ValueVector _res_cap;
219 // Data for a StaticDigraph structure
220 typedef std::pair<int, int> IntPair;
222 std::vector<IntPair> _arc_vec;
223 std::vector<Cost> _cost_vec;
225 CostArcMap _cost_map;
230 /// \brief Constant for infinite upper bounds (capacities).
232 /// Constant for infinite upper bounds (capacities).
233 /// It is \c std::numeric_limits<Value>::infinity() if available,
234 /// \c std::numeric_limits<Value>::max() otherwise.
239 /// \brief Constructor.
241 /// The constructor of the class.
243 /// \param graph The digraph the algorithm runs on.
244 CycleCanceling(const GR& graph) :
245 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
246 _cost_map(_cost_vec), _pi_map(_pi),
247 INF(std::numeric_limits<Value>::has_infinity ?
248 std::numeric_limits<Value>::infinity() :
249 std::numeric_limits<Value>::max())
251 // Check the number types
252 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
253 "The flow type of CycleCanceling must be signed");
254 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
255 "The cost type of CycleCanceling must be signed");
257 // Reset data structures
262 /// The parameters of the algorithm can be specified using these
267 /// \brief Set the lower bounds on the arcs.
269 /// This function sets the lower bounds on the arcs.
270 /// If it is not used before calling \ref run(), the lower bounds
271 /// will be set to zero on all arcs.
273 /// \param map An arc map storing the lower bounds.
274 /// Its \c Value type must be convertible to the \c Value type
275 /// of the algorithm.
277 /// \return <tt>(*this)</tt>
278 template <typename LowerMap>
279 CycleCanceling& lowerMap(const LowerMap& map) {
281 for (ArcIt a(_graph); a != INVALID; ++a) {
282 _lower[_arc_idf[a]] = map[a];
283 _lower[_arc_idb[a]] = map[a];
288 /// \brief Set the upper bounds (capacities) on the arcs.
290 /// This function sets the upper bounds (capacities) on the arcs.
291 /// If it is not used before calling \ref run(), the upper bounds
292 /// will be set to \ref INF on all arcs (i.e. the flow value will be
293 /// unbounded from above).
295 /// \param map An arc map storing the upper bounds.
296 /// Its \c Value type must be convertible to the \c Value type
297 /// of the algorithm.
299 /// \return <tt>(*this)</tt>
300 template<typename UpperMap>
301 CycleCanceling& upperMap(const UpperMap& map) {
302 for (ArcIt a(_graph); a != INVALID; ++a) {
303 _upper[_arc_idf[a]] = map[a];
308 /// \brief Set the costs of the arcs.
310 /// This function sets the costs of the arcs.
311 /// If it is not used before calling \ref run(), the costs
312 /// will be set to \c 1 on all arcs.
314 /// \param map An arc map storing the costs.
315 /// Its \c Value type must be convertible to the \c Cost type
316 /// of the algorithm.
318 /// \return <tt>(*this)</tt>
319 template<typename CostMap>
320 CycleCanceling& costMap(const CostMap& map) {
321 for (ArcIt a(_graph); a != INVALID; ++a) {
322 _cost[_arc_idf[a]] = map[a];
323 _cost[_arc_idb[a]] = -map[a];
328 /// \brief Set the supply values of the nodes.
330 /// This function sets the supply values of the nodes.
331 /// If neither this function nor \ref stSupply() is used before
332 /// calling \ref run(), the supply of each node will be set to zero.
334 /// \param map A node map storing the supply values.
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 SupplyMap>
340 CycleCanceling& supplyMap(const SupplyMap& map) {
341 for (NodeIt n(_graph); n != INVALID; ++n) {
342 _supply[_node_id[n]] = map[n];
347 /// \brief Set single source and target nodes and a supply value.
349 /// This function sets a single source node and a single target node
350 /// and the required flow value.
351 /// If neither this function nor \ref supplyMap() is used before
352 /// calling \ref run(), the supply of each node will be set to zero.
354 /// Using this function has the same effect as using \ref supplyMap()
355 /// with a map in which \c k is assigned to \c s, \c -k is
356 /// assigned to \c t and all other nodes have zero supply value.
358 /// \param s The source node.
359 /// \param t The target node.
360 /// \param k The required amount of flow from node \c s to node \c t
361 /// (i.e. the supply of \c s and the demand of \c t).
363 /// \return <tt>(*this)</tt>
364 CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
365 for (int i = 0; i != _res_node_num; ++i) {
368 _supply[_node_id[s]] = k;
369 _supply[_node_id[t]] = -k;
375 /// \name Execution control
376 /// The algorithm can be executed using \ref run().
380 /// \brief Run the algorithm.
382 /// This function runs the algorithm.
383 /// The paramters can be specified using functions \ref lowerMap(),
384 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
387 /// CycleCanceling<ListDigraph> cc(graph);
388 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
389 /// .supplyMap(sup).run();
392 /// This function can be called more than once. All the given parameters
393 /// are kept for the next call, unless \ref resetParams() or \ref reset()
394 /// is used, thus only the modified parameters have to be set again.
395 /// If the underlying digraph was also modified after the construction
396 /// of the class (or the last \ref reset() call), then the \ref reset()
397 /// function must be called.
399 /// \param method The cycle-canceling method that will be used.
400 /// For more information, see \ref Method.
402 /// \return \c INFEASIBLE if no feasible flow exists,
403 /// \n \c OPTIMAL if the problem has optimal solution
404 /// (i.e. it is feasible and bounded), and the algorithm has found
405 /// optimal flow and node potentials (primal and dual solutions),
406 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
407 /// and infinite upper bound. It means that the objective function
408 /// is unbounded on that arc, however, note that it could actually be
409 /// bounded over the feasible flows, but this algroithm cannot handle
412 /// \see ProblemType, Method
413 /// \see resetParams(), reset()
414 ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
415 ProblemType pt = init();
416 if (pt != OPTIMAL) return pt;
421 /// \brief Reset all the parameters that have been given before.
423 /// This function resets all the paramaters that have been given
424 /// before using functions \ref lowerMap(), \ref upperMap(),
425 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
427 /// It is useful for multiple \ref run() calls. Basically, all the given
428 /// parameters are kept for the next \ref run() call, unless
429 /// \ref resetParams() or \ref reset() is used.
430 /// If the underlying digraph was also modified after the construction
431 /// of the class or the last \ref reset() call, then the \ref reset()
432 /// function must be used, otherwise \ref resetParams() is sufficient.
436 /// CycleCanceling<ListDigraph> cs(graph);
439 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
440 /// .supplyMap(sup).run();
442 /// // Run again with modified cost map (resetParams() is not called,
443 /// // so only the cost map have to be set again)
445 /// cc.costMap(cost).run();
447 /// // Run again from scratch using resetParams()
448 /// // (the lower bounds will be set to zero on all arcs)
449 /// cc.resetParams();
450 /// cc.upperMap(capacity).costMap(cost)
451 /// .supplyMap(sup).run();
454 /// \return <tt>(*this)</tt>
456 /// \see reset(), run()
457 CycleCanceling& resetParams() {
458 for (int i = 0; i != _res_node_num; ++i) {
461 int limit = _first_out[_root];
462 for (int j = 0; j != limit; ++j) {
465 _cost[j] = _forward[j] ? 1 : -1;
467 for (int j = limit; j != _res_arc_num; ++j) {
471 _cost[_reverse[j]] = 0;
477 /// \brief Reset the internal data structures and all the parameters
478 /// that have been given before.
480 /// This function resets the internal data structures and all the
481 /// paramaters that have been given before using functions \ref lowerMap(),
482 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
484 /// It is useful for multiple \ref run() calls. Basically, all the given
485 /// parameters are kept for the next \ref run() call, unless
486 /// \ref resetParams() or \ref reset() is used.
487 /// If the underlying digraph was also modified after the construction
488 /// of the class or the last \ref reset() call, then the \ref reset()
489 /// function must be used, otherwise \ref resetParams() is sufficient.
491 /// See \ref resetParams() for examples.
493 /// \return <tt>(*this)</tt>
495 /// \see resetParams(), run()
496 CycleCanceling& reset() {
498 _node_num = countNodes(_graph);
499 _arc_num = countArcs(_graph);
500 _res_node_num = _node_num + 1;
501 _res_arc_num = 2 * (_arc_num + _node_num);
504 _first_out.resize(_res_node_num + 1);
505 _forward.resize(_res_arc_num);
506 _source.resize(_res_arc_num);
507 _target.resize(_res_arc_num);
508 _reverse.resize(_res_arc_num);
510 _lower.resize(_res_arc_num);
511 _upper.resize(_res_arc_num);
512 _cost.resize(_res_arc_num);
513 _supply.resize(_res_node_num);
515 _res_cap.resize(_res_arc_num);
516 _pi.resize(_res_node_num);
518 _arc_vec.reserve(_res_arc_num);
519 _cost_vec.reserve(_res_arc_num);
520 _id_vec.reserve(_res_arc_num);
523 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
524 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
528 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
530 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
534 _target[j] = _node_id[_graph.runningNode(a)];
536 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
540 _target[j] = _node_id[_graph.runningNode(a)];
553 _first_out[_res_node_num] = k;
554 for (ArcIt a(_graph); a != INVALID; ++a) {
555 int fi = _arc_idf[a];
556 int bi = _arc_idb[a];
568 /// \name Query Functions
569 /// The results of the algorithm can be obtained using these
571 /// The \ref run() function must be called before using them.
575 /// \brief Return the total cost of the found flow.
577 /// This function returns the total cost of the found flow.
578 /// Its complexity is O(e).
580 /// \note The return type of the function can be specified as a
581 /// template parameter. For example,
583 /// cc.totalCost<double>();
585 /// It is useful if the total cost cannot be stored in the \c Cost
586 /// type of the algorithm, which is the default return type of the
589 /// \pre \ref run() must be called before using this function.
590 template <typename Number>
591 Number totalCost() const {
593 for (ArcIt a(_graph); a != INVALID; ++a) {
595 c += static_cast<Number>(_res_cap[i]) *
596 (-static_cast<Number>(_cost[i]));
602 Cost totalCost() const {
603 return totalCost<Cost>();
607 /// \brief Return the flow on the given arc.
609 /// This function returns the flow on the given arc.
611 /// \pre \ref run() must be called before using this function.
612 Value flow(const Arc& a) const {
613 return _res_cap[_arc_idb[a]];
616 /// \brief Copy the flow values (the primal solution) into the
619 /// This function copies the flow value on each arc into the given
620 /// map. The \c Value type of the algorithm must be convertible to
621 /// the \c Value type of the map.
623 /// \pre \ref run() must be called before using this function.
624 template <typename FlowMap>
625 void flowMap(FlowMap &map) const {
626 for (ArcIt a(_graph); a != INVALID; ++a) {
627 map.set(a, _res_cap[_arc_idb[a]]);
631 /// \brief Return the potential (dual value) of the given node.
633 /// This function returns the potential (dual value) of the
636 /// \pre \ref run() must be called before using this function.
637 Cost potential(const Node& n) const {
638 return static_cast<Cost>(_pi[_node_id[n]]);
641 /// \brief Copy the potential values (the dual solution) into the
644 /// This function copies the potential (dual value) of each node
645 /// into the given map.
646 /// The \c Cost type of the algorithm must be convertible to the
647 /// \c Value type of the map.
649 /// \pre \ref run() must be called before using this function.
650 template <typename PotentialMap>
651 void potentialMap(PotentialMap &map) const {
652 for (NodeIt n(_graph); n != INVALID; ++n) {
653 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
661 // Initialize the algorithm
663 if (_res_node_num <= 1) return INFEASIBLE;
665 // Check the sum of supply values
667 for (int i = 0; i != _root; ++i) {
668 _sum_supply += _supply[i];
670 if (_sum_supply > 0) return INFEASIBLE;
673 // Initialize vectors
674 for (int i = 0; i != _res_node_num; ++i) {
677 ValueVector excess(_supply);
679 // Remove infinite upper bounds and check negative arcs
680 const Value MAX = std::numeric_limits<Value>::max();
683 for (int i = 0; i != _root; ++i) {
684 last_out = _first_out[i+1];
685 for (int j = _first_out[i]; j != last_out; ++j) {
687 Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
688 if (c >= MAX) return UNBOUNDED;
690 excess[_target[j]] += c;
695 for (int i = 0; i != _root; ++i) {
696 last_out = _first_out[i+1];
697 for (int j = _first_out[i]; j != last_out; ++j) {
698 if (_forward[j] && _cost[j] < 0) {
700 if (c >= MAX) return UNBOUNDED;
702 excess[_target[j]] += c;
707 Value ex, max_cap = 0;
708 for (int i = 0; i != _res_node_num; ++i) {
710 if (ex < 0) max_cap -= ex;
712 for (int j = 0; j != _res_arc_num; ++j) {
713 if (_upper[j] >= MAX) _upper[j] = max_cap;
716 // Initialize maps for Circulation and remove non-zero lower bounds
717 ConstMap<Arc, Value> low(0);
718 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
719 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
720 ValueArcMap cap(_graph), flow(_graph);
721 ValueNodeMap sup(_graph);
722 for (NodeIt n(_graph); n != INVALID; ++n) {
723 sup[n] = _supply[_node_id[n]];
726 for (ArcIt a(_graph); a != INVALID; ++a) {
729 cap[a] = _upper[j] - c;
730 sup[_graph.source(a)] -= c;
731 sup[_graph.target(a)] += c;
734 for (ArcIt a(_graph); a != INVALID; ++a) {
735 cap[a] = _upper[_arc_idf[a]];
739 // Find a feasible flow using Circulation
740 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
741 circ(_graph, low, cap, sup);
742 if (!circ.flowMap(flow).run()) return INFEASIBLE;
744 // Set residual capacities and handle GEQ supply type
745 if (_sum_supply < 0) {
746 for (ArcIt a(_graph); a != INVALID; ++a) {
748 _res_cap[_arc_idf[a]] = cap[a] - fa;
749 _res_cap[_arc_idb[a]] = fa;
750 sup[_graph.source(a)] -= fa;
751 sup[_graph.target(a)] += fa;
753 for (NodeIt n(_graph); n != INVALID; ++n) {
754 excess[_node_id[n]] = sup[n];
756 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
758 int ra = _reverse[a];
759 _res_cap[a] = -_sum_supply + 1;
760 _res_cap[ra] = -excess[u];
765 for (ArcIt a(_graph); a != INVALID; ++a) {
767 _res_cap[_arc_idf[a]] = cap[a] - fa;
768 _res_cap[_arc_idb[a]] = fa;
770 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
771 int ra = _reverse[a];
782 // Build a StaticDigraph structure containing the current
784 void buildResidualNetwork() {
788 for (int j = 0; j != _res_arc_num; ++j) {
789 if (_res_cap[j] > 0) {
790 _arc_vec.push_back(IntPair(_source[j], _target[j]));
791 _cost_vec.push_back(_cost[j]);
792 _id_vec.push_back(j);
795 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
798 // Execute the algorithm and transform the results
799 void start(Method method) {
800 // Execute the algorithm
802 case SIMPLE_CYCLE_CANCELING:
803 startSimpleCycleCanceling();
805 case MINIMUM_MEAN_CYCLE_CANCELING:
806 startMinMeanCycleCanceling();
808 case CANCEL_AND_TIGHTEN:
809 startCancelAndTighten();
813 // Compute node potentials
814 if (method != SIMPLE_CYCLE_CANCELING) {
815 buildResidualNetwork();
816 typename BellmanFord<StaticDigraph, CostArcMap>
817 ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
823 // Handle non-zero lower bounds
825 int limit = _first_out[_root];
826 for (int j = 0; j != limit; ++j) {
827 if (!_forward[j]) _res_cap[j] += _lower[j];
832 // Execute the "Simple Cycle Canceling" method
833 void startSimpleCycleCanceling() {
834 // Constants for computing the iteration limits
835 const int BF_FIRST_LIMIT = 2;
836 const double BF_LIMIT_FACTOR = 1.5;
838 typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
839 typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
840 typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
841 typedef typename BellmanFord<ResDigraph, CostArcMap>
842 ::template SetDistMap<CostNodeMap>
843 ::template SetPredMap<PredMap>::Create BF;
845 // Build the residual network
848 for (int j = 0; j != _res_arc_num; ++j) {
849 _arc_vec.push_back(IntPair(_source[j], _target[j]));
850 _cost_vec.push_back(_cost[j]);
852 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
854 FilterMap filter_map(_res_cap);
855 ResDigraph rgr(_sgr, filter_map);
856 std::vector<int> cycle;
857 std::vector<StaticDigraph::Arc> pred(_res_arc_num);
858 PredMap pred_map(pred);
859 BF bf(rgr, _cost_map);
860 bf.distMap(_pi_map).predMap(pred_map);
862 int length_bound = BF_FIRST_LIMIT;
863 bool optimal = false;
867 bool cycle_found = false;
868 while (!cycle_found) {
869 // Perform some iterations of the Bellman-Ford algorithm
870 int curr_iter_num = iter_num + length_bound <= _node_num ?
871 length_bound : _node_num - iter_num;
872 iter_num += curr_iter_num;
873 int real_iter_num = curr_iter_num;
874 for (int i = 0; i < curr_iter_num; ++i) {
875 if (bf.processNextWeakRound()) {
880 if (real_iter_num < curr_iter_num) {
881 // Optimal flow is found
885 // Search for node disjoint negative cycles
886 std::vector<int> state(_res_node_num, 0);
888 for (int u = 0; u != _res_node_num; ++u) {
889 if (state[u] != 0) continue;
892 for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
893 -1 : rgr.id(rgr.source(pred[v]))) {
896 if (v != -1 && state[v] == id) {
897 // A negative cycle is found
900 StaticDigraph::Arc a = pred[v];
901 Value d, delta = _res_cap[rgr.id(a)];
902 cycle.push_back(rgr.id(a));
903 while (rgr.id(rgr.source(a)) != v) {
904 a = pred_map[rgr.source(a)];
905 d = _res_cap[rgr.id(a)];
906 if (d < delta) delta = d;
907 cycle.push_back(rgr.id(a));
910 // Augment along the cycle
911 for (int i = 0; i < int(cycle.size()); ++i) {
913 _res_cap[j] -= delta;
914 _res_cap[_reverse[j]] += delta;
920 // Increase iteration limit if no cycle is found
922 length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
928 // Execute the "Minimum Mean Cycle Canceling" method
929 void startMinMeanCycleCanceling() {
930 typedef SimplePath<StaticDigraph> SPath;
931 typedef typename SPath::ArcIt SPathArcIt;
932 typedef typename HowardMmc<StaticDigraph, CostArcMap>
933 ::template SetPath<SPath>::Create MMC;
936 MMC mmc(_sgr, _cost_map);
938 buildResidualNetwork();
939 while (mmc.findCycleMean() && mmc.cycleCost() < 0) {
943 // Compute delta value
945 for (SPathArcIt a(cycle); a != INVALID; ++a) {
946 Value d = _res_cap[_id_vec[_sgr.id(a)]];
947 if (d < delta) delta = d;
950 // Augment along the cycle
951 for (SPathArcIt a(cycle); a != INVALID; ++a) {
952 int j = _id_vec[_sgr.id(a)];
953 _res_cap[j] -= delta;
954 _res_cap[_reverse[j]] += delta;
957 // Rebuild the residual network
958 buildResidualNetwork();
962 // Execute the "Cancel-and-Tighten" method
963 void startCancelAndTighten() {
964 // Constants for the min mean cycle computations
965 const double LIMIT_FACTOR = 1.0;
966 const int MIN_LIMIT = 5;
968 // Contruct auxiliary data vectors
969 DoubleVector pi(_res_node_num, 0.0);
970 IntVector level(_res_node_num);
971 BoolVector reached(_res_node_num);
972 BoolVector processed(_res_node_num);
973 IntVector pred_node(_res_node_num);
974 IntVector pred_arc(_res_node_num);
975 std::vector<int> stack(_res_node_num);
976 std::vector<int> proc_vector(_res_node_num);
978 // Initialize epsilon
980 for (int a = 0; a != _res_arc_num; ++a) {
981 if (_res_cap[a] > 0 && -_cost[a] > epsilon)
986 Tolerance<double> tol;
988 int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
989 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
991 while (epsilon * _res_node_num >= 1) {
992 // Find and cancel cycles in the admissible network using DFS
993 for (int u = 0; u != _res_node_num; ++u) {
995 processed[u] = false;
999 for (int start = 0; start != _res_node_num; ++start) {
1000 if (reached[start]) continue;
1003 reached[start] = true;
1004 pred_arc[start] = -1;
1005 pred_node[start] = -1;
1007 // Find the first admissible outgoing arc
1008 double p = pi[start];
1009 int a = _first_out[start];
1010 int last_out = _first_out[start+1];
1011 for (; a != last_out && (_res_cap[a] == 0 ||
1012 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1013 if (a == last_out) {
1014 processed[start] = true;
1015 proc_vector[++proc_head] = start;
1018 stack[++stack_head] = a;
1020 while (stack_head >= 0) {
1021 int sa = stack[stack_head];
1022 int u = _source[sa];
1023 int v = _target[sa];
1026 // A new node is reached
1032 last_out = _first_out[v+1];
1033 for (; a != last_out && (_res_cap[a] == 0 ||
1034 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1035 stack[++stack_head] = a == last_out ? -1 : a;
1037 if (!processed[v]) {
1040 Value d, delta = _res_cap[sa];
1041 for (n = u; n != v; n = pred_node[n]) {
1042 d = _res_cap[pred_arc[n]];
1049 // Augment along the cycle
1050 _res_cap[sa] -= delta;
1051 _res_cap[_reverse[sa]] += delta;
1052 for (n = u; n != v; n = pred_node[n]) {
1053 int pa = pred_arc[n];
1054 _res_cap[pa] -= delta;
1055 _res_cap[_reverse[pa]] += delta;
1057 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1065 // Find the next admissible outgoing arc
1067 a = stack[stack_head] + 1;
1068 last_out = _first_out[v+1];
1069 for (; a != last_out && (_res_cap[a] == 0 ||
1070 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1071 stack[stack_head] = a == last_out ? -1 : a;
1074 while (stack_head >= 0 && stack[stack_head] == -1) {
1075 processed[v] = true;
1076 proc_vector[++proc_head] = v;
1077 if (--stack_head >= 0) {
1078 // Find the next admissible outgoing arc
1079 v = _source[stack[stack_head]];
1081 a = stack[stack_head] + 1;
1082 last_out = _first_out[v+1];
1083 for (; a != last_out && (_res_cap[a] == 0 ||
1084 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1085 stack[stack_head] = a == last_out ? -1 : a;
1091 // Tighten potentials and epsilon
1093 for (int u = 0; u != _res_node_num; ++u) {
1096 for (int i = proc_head; i > 0; --i) {
1097 int u = proc_vector[i];
1099 int l = level[u] + 1;
1100 int last_out = _first_out[u+1];
1101 for (int a = _first_out[u]; a != last_out; ++a) {
1103 if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1104 l > level[v]) level[v] = l;
1108 // Modify potentials
1109 double q = std::numeric_limits<double>::max();
1110 for (int u = 0; u != _res_node_num; ++u) {
1112 double p, pu = pi[u];
1113 int last_out = _first_out[u+1];
1114 for (int a = _first_out[u]; a != last_out; ++a) {
1115 if (_res_cap[a] == 0) continue;
1117 int ld = lu - level[v];
1119 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1124 for (int u = 0; u != _res_node_num; ++u) {
1125 pi[u] -= q * level[u];
1130 for (int u = 0; u != _res_node_num; ++u) {
1131 double curr, pu = pi[u];
1132 int last_out = _first_out[u+1];
1133 for (int a = _first_out[u]; a != last_out; ++a) {
1134 if (_res_cap[a] == 0) continue;
1135 curr = _cost[a] + pu - pi[_target[a]];
1136 if (-curr > epsilon) epsilon = -curr;
1140 typedef HowardMmc<StaticDigraph, CostArcMap> MMC;
1141 typedef typename BellmanFord<StaticDigraph, CostArcMap>
1142 ::template SetDistMap<CostNodeMap>::Create BF;
1144 // Set epsilon to the minimum cycle mean
1145 buildResidualNetwork();
1146 MMC mmc(_sgr, _cost_map);
1147 mmc.findCycleMean();
1148 epsilon = -mmc.cycleMean();
1149 Cost cycle_cost = mmc.cycleCost();
1150 int cycle_size = mmc.cycleSize();
1152 // Compute feasible potentials for the current epsilon
1153 for (int i = 0; i != int(_cost_vec.size()); ++i) {
1154 _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1156 BF bf(_sgr, _cost_map);
1157 bf.distMap(_pi_map);
1160 for (int u = 0; u != _res_node_num; ++u) {
1161 pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1169 }; //class CycleCanceling
1175 #endif //LEMON_CYCLE_CANCELING_H