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 (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 \c V and \c C must be signed number types.
69 /// \warning All input data (capacities, supply values, and costs) must
71 /// \warning This algorithm does not support negative costs for such
72 /// arcs that have infinite upper bound.
74 /// \note For more information about the three available methods,
77 template <typename GR, typename V, typename C>
79 template <typename GR, typename V = int, typename C = V>
85 /// The type of the digraph
87 /// The type of the flow amounts, capacity bounds and supply values
89 /// The type of the arc costs
94 /// \brief Problem type constants for the \c run() function.
96 /// Enum type containing the problem type constants that can be
97 /// returned by the \ref run() function of the algorithm.
99 /// The problem has no feasible solution (flow).
101 /// The problem has optimal solution (i.e. it is feasible and
102 /// bounded), and the algorithm has found optimal flow and node
103 /// potentials (primal and dual solutions).
105 /// The digraph contains an arc of negative cost and infinite
106 /// upper bound. It means that the objective function is unbounded
107 /// on that arc, however, note that it could actually be bounded
108 /// over the feasible flows, but this algroithm cannot handle
113 /// \brief Constants for selecting the used method.
115 /// Enum type containing constants for selecting the used method
116 /// for the \ref run() function.
118 /// \ref CycleCanceling provides three different cycle-canceling
119 /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel and Tighten"
120 /// is used, which proved to be the most efficient and the most robust
121 /// on various test inputs.
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 with limited iteration
127 /// number for detecting negative cycles in the residual network.
128 SIMPLE_CYCLE_CANCELING,
129 /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
130 /// well-known strongly polynomial method
131 /// \ref goldberg89cyclecanceling. It improves along a
132 /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
133 /// Its running time complexity is O(n<sup>2</sup>m<sup>3</sup>log(n)).
134 MINIMUM_MEAN_CYCLE_CANCELING,
135 /// The "Cancel And Tighten" algorithm, which can be viewed as an
136 /// improved version of the previous method
137 /// \ref goldberg89cyclecanceling.
138 /// It is faster both in theory and in practice, its running time
139 /// complexity is O(n<sup>2</sup>m<sup>2</sup>log(n)).
145 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
147 typedef std::vector<int> IntVector;
148 typedef std::vector<double> DoubleVector;
149 typedef std::vector<Value> ValueVector;
150 typedef std::vector<Cost> CostVector;
151 typedef std::vector<char> BoolVector;
152 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
156 template <typename KT, typename VT>
157 class StaticVectorMap {
162 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
164 const Value& operator[](const Key& key) const {
165 return _v[StaticDigraph::id(key)];
168 Value& operator[](const Key& key) {
169 return _v[StaticDigraph::id(key)];
172 void set(const Key& key, const Value& val) {
173 _v[StaticDigraph::id(key)] = val;
177 std::vector<Value>& _v;
180 typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
181 typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
186 // Data related to the underlying digraph
194 // Parameters of the problem
198 // Data structures for storing the digraph
202 IntVector _first_out;
214 ValueVector _res_cap;
217 // Data for a StaticDigraph structure
218 typedef std::pair<int, int> IntPair;
220 std::vector<IntPair> _arc_vec;
221 std::vector<Cost> _cost_vec;
223 CostArcMap _cost_map;
228 /// \brief Constant for infinite upper bounds (capacities).
230 /// Constant for infinite upper bounds (capacities).
231 /// It is \c std::numeric_limits<Value>::infinity() if available,
232 /// \c std::numeric_limits<Value>::max() otherwise.
237 /// \brief Constructor.
239 /// The constructor of the class.
241 /// \param graph The digraph the algorithm runs on.
242 CycleCanceling(const GR& graph) :
243 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
244 _cost_map(_cost_vec), _pi_map(_pi),
245 INF(std::numeric_limits<Value>::has_infinity ?
246 std::numeric_limits<Value>::infinity() :
247 std::numeric_limits<Value>::max())
249 // Check the number types
250 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
251 "The flow type of CycleCanceling must be signed");
252 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
253 "The cost type of CycleCanceling must be signed");
255 // Reset data structures
260 /// The parameters of the algorithm can be specified using these
265 /// \brief Set the lower bounds on the arcs.
267 /// This function sets the lower bounds on the arcs.
268 /// If it is not used before calling \ref run(), the lower bounds
269 /// will be set to zero on all arcs.
271 /// \param map An arc map storing the lower bounds.
272 /// Its \c Value type must be convertible to the \c Value type
273 /// of the algorithm.
275 /// \return <tt>(*this)</tt>
276 template <typename LowerMap>
277 CycleCanceling& lowerMap(const LowerMap& map) {
279 for (ArcIt a(_graph); a != INVALID; ++a) {
280 _lower[_arc_idf[a]] = map[a];
281 _lower[_arc_idb[a]] = map[a];
286 /// \brief Set the upper bounds (capacities) on the arcs.
288 /// This function sets the upper bounds (capacities) on the arcs.
289 /// If it is not used before calling \ref run(), the upper bounds
290 /// will be set to \ref INF on all arcs (i.e. the flow value will be
291 /// unbounded from above).
293 /// \param map An arc map storing the upper bounds.
294 /// Its \c Value type must be convertible to the \c Value type
295 /// of the algorithm.
297 /// \return <tt>(*this)</tt>
298 template<typename UpperMap>
299 CycleCanceling& upperMap(const UpperMap& map) {
300 for (ArcIt a(_graph); a != INVALID; ++a) {
301 _upper[_arc_idf[a]] = map[a];
306 /// \brief Set the costs of the arcs.
308 /// This function sets the costs of the arcs.
309 /// If it is not used before calling \ref run(), the costs
310 /// will be set to \c 1 on all arcs.
312 /// \param map An arc map storing the costs.
313 /// Its \c Value type must be convertible to the \c Cost type
314 /// of the algorithm.
316 /// \return <tt>(*this)</tt>
317 template<typename CostMap>
318 CycleCanceling& costMap(const CostMap& map) {
319 for (ArcIt a(_graph); a != INVALID; ++a) {
320 _cost[_arc_idf[a]] = map[a];
321 _cost[_arc_idb[a]] = -map[a];
326 /// \brief Set the supply values of the nodes.
328 /// This function sets the supply values of the nodes.
329 /// If neither this function nor \ref stSupply() is used before
330 /// calling \ref run(), the supply of each node will be set to zero.
332 /// \param map A node map storing the supply values.
333 /// Its \c Value type must be convertible to the \c Value type
334 /// of the algorithm.
336 /// \return <tt>(*this)</tt>
337 template<typename SupplyMap>
338 CycleCanceling& supplyMap(const SupplyMap& map) {
339 for (NodeIt n(_graph); n != INVALID; ++n) {
340 _supply[_node_id[n]] = map[n];
345 /// \brief Set single source and target nodes and a supply value.
347 /// This function sets a single source node and a single target node
348 /// and the required flow value.
349 /// If neither this function nor \ref supplyMap() is used before
350 /// calling \ref run(), the supply of each node will be set to zero.
352 /// Using this function has the same effect as using \ref supplyMap()
353 /// with such a map in which \c k is assigned to \c s, \c -k is
354 /// assigned to \c t and all other nodes have zero supply value.
356 /// \param s The source node.
357 /// \param t The target node.
358 /// \param k The required amount of flow from node \c s to node \c t
359 /// (i.e. the supply of \c s and the demand of \c t).
361 /// \return <tt>(*this)</tt>
362 CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
363 for (int i = 0; i != _res_node_num; ++i) {
366 _supply[_node_id[s]] = k;
367 _supply[_node_id[t]] = -k;
373 /// \name Execution control
374 /// The algorithm can be executed using \ref run().
378 /// \brief Run the algorithm.
380 /// This function runs the algorithm.
381 /// The paramters can be specified using functions \ref lowerMap(),
382 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
385 /// CycleCanceling<ListDigraph> cc(graph);
386 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
387 /// .supplyMap(sup).run();
390 /// This function can be called more than once. All the given parameters
391 /// are kept for the next call, unless \ref resetParams() or \ref reset()
392 /// is used, thus only the modified parameters have to be set again.
393 /// If the underlying digraph was also modified after the construction
394 /// of the class (or the last \ref reset() call), then the \ref reset()
395 /// function must be called.
397 /// \param method The cycle-canceling method that will be used.
398 /// For more information, see \ref Method.
400 /// \return \c INFEASIBLE if no feasible flow exists,
401 /// \n \c OPTIMAL if the problem has optimal solution
402 /// (i.e. it is feasible and bounded), and the algorithm has found
403 /// optimal flow and node potentials (primal and dual solutions),
404 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
405 /// and infinite upper bound. It means that the objective function
406 /// is unbounded on that arc, however, note that it could actually be
407 /// bounded over the feasible flows, but this algroithm cannot handle
410 /// \see ProblemType, Method
411 /// \see resetParams(), reset()
412 ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
413 ProblemType pt = init();
414 if (pt != OPTIMAL) return pt;
419 /// \brief Reset all the parameters that have been given before.
421 /// This function resets all the paramaters that have been given
422 /// before using functions \ref lowerMap(), \ref upperMap(),
423 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
425 /// It is useful for multiple \ref run() calls. Basically, all the given
426 /// parameters are kept for the next \ref run() call, unless
427 /// \ref resetParams() or \ref reset() is used.
428 /// If the underlying digraph was also modified after the construction
429 /// of the class or the last \ref reset() call, then the \ref reset()
430 /// function must be used, otherwise \ref resetParams() is sufficient.
434 /// CycleCanceling<ListDigraph> cs(graph);
437 /// cc.lowerMap(lower).upperMap(upper).costMap(cost)
438 /// .supplyMap(sup).run();
440 /// // Run again with modified cost map (resetParams() is not called,
441 /// // so only the cost map have to be set again)
443 /// cc.costMap(cost).run();
445 /// // Run again from scratch using resetParams()
446 /// // (the lower bounds will be set to zero on all arcs)
447 /// cc.resetParams();
448 /// cc.upperMap(capacity).costMap(cost)
449 /// .supplyMap(sup).run();
452 /// \return <tt>(*this)</tt>
454 /// \see reset(), run()
455 CycleCanceling& resetParams() {
456 for (int i = 0; i != _res_node_num; ++i) {
459 int limit = _first_out[_root];
460 for (int j = 0; j != limit; ++j) {
463 _cost[j] = _forward[j] ? 1 : -1;
465 for (int j = limit; j != _res_arc_num; ++j) {
469 _cost[_reverse[j]] = 0;
475 /// \brief Reset the internal data structures and all the parameters
476 /// that have been given before.
478 /// This function resets the internal data structures and all the
479 /// paramaters that have been given before using functions \ref lowerMap(),
480 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
482 /// It is useful for multiple \ref run() calls. Basically, all the given
483 /// parameters are kept for the next \ref run() call, unless
484 /// \ref resetParams() or \ref reset() is used.
485 /// If the underlying digraph was also modified after the construction
486 /// of the class or the last \ref reset() call, then the \ref reset()
487 /// function must be used, otherwise \ref resetParams() is sufficient.
489 /// See \ref resetParams() for examples.
491 /// \return <tt>(*this)</tt>
493 /// \see resetParams(), run()
494 CycleCanceling& reset() {
496 _node_num = countNodes(_graph);
497 _arc_num = countArcs(_graph);
498 _res_node_num = _node_num + 1;
499 _res_arc_num = 2 * (_arc_num + _node_num);
502 _first_out.resize(_res_node_num + 1);
503 _forward.resize(_res_arc_num);
504 _source.resize(_res_arc_num);
505 _target.resize(_res_arc_num);
506 _reverse.resize(_res_arc_num);
508 _lower.resize(_res_arc_num);
509 _upper.resize(_res_arc_num);
510 _cost.resize(_res_arc_num);
511 _supply.resize(_res_node_num);
513 _res_cap.resize(_res_arc_num);
514 _pi.resize(_res_node_num);
516 _arc_vec.reserve(_res_arc_num);
517 _cost_vec.reserve(_res_arc_num);
518 _id_vec.reserve(_res_arc_num);
521 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
522 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
526 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
528 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
532 _target[j] = _node_id[_graph.runningNode(a)];
534 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
538 _target[j] = _node_id[_graph.runningNode(a)];
551 _first_out[_res_node_num] = k;
552 for (ArcIt a(_graph); a != INVALID; ++a) {
553 int fi = _arc_idf[a];
554 int bi = _arc_idb[a];
566 /// \name Query Functions
567 /// The results of the algorithm can be obtained using these
569 /// The \ref run() function must be called before using them.
573 /// \brief Return the total cost of the found flow.
575 /// This function returns the total cost of the found flow.
576 /// Its complexity is O(e).
578 /// \note The return type of the function can be specified as a
579 /// template parameter. For example,
581 /// cc.totalCost<double>();
583 /// It is useful if the total cost cannot be stored in the \c Cost
584 /// type of the algorithm, which is the default return type of the
587 /// \pre \ref run() must be called before using this function.
588 template <typename Number>
589 Number totalCost() const {
591 for (ArcIt a(_graph); a != INVALID; ++a) {
593 c += static_cast<Number>(_res_cap[i]) *
594 (-static_cast<Number>(_cost[i]));
600 Cost totalCost() const {
601 return totalCost<Cost>();
605 /// \brief Return the flow on the given arc.
607 /// This function returns the flow on the given arc.
609 /// \pre \ref run() must be called before using this function.
610 Value flow(const Arc& a) const {
611 return _res_cap[_arc_idb[a]];
614 /// \brief Return the flow map (the primal solution).
616 /// This function copies the flow value on each arc into the given
617 /// map. The \c Value type of the algorithm must be convertible to
618 /// the \c Value type of the map.
620 /// \pre \ref run() must be called before using this function.
621 template <typename FlowMap>
622 void flowMap(FlowMap &map) const {
623 for (ArcIt a(_graph); a != INVALID; ++a) {
624 map.set(a, _res_cap[_arc_idb[a]]);
628 /// \brief Return the potential (dual value) of the given node.
630 /// This function returns the potential (dual value) of the
633 /// \pre \ref run() must be called before using this function.
634 Cost potential(const Node& n) const {
635 return static_cast<Cost>(_pi[_node_id[n]]);
638 /// \brief Return the potential map (the dual solution).
640 /// This function copies the potential (dual value) of each node
641 /// into the given map.
642 /// The \c Cost type of the algorithm must be convertible to the
643 /// \c Value type of the map.
645 /// \pre \ref run() must be called before using this function.
646 template <typename PotentialMap>
647 void potentialMap(PotentialMap &map) const {
648 for (NodeIt n(_graph); n != INVALID; ++n) {
649 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
657 // Initialize the algorithm
659 if (_res_node_num <= 1) return INFEASIBLE;
661 // Check the sum of supply values
663 for (int i = 0; i != _root; ++i) {
664 _sum_supply += _supply[i];
666 if (_sum_supply > 0) return INFEASIBLE;
669 // Initialize vectors
670 for (int i = 0; i != _res_node_num; ++i) {
673 ValueVector excess(_supply);
675 // Remove infinite upper bounds and check negative arcs
676 const Value MAX = std::numeric_limits<Value>::max();
679 for (int i = 0; i != _root; ++i) {
680 last_out = _first_out[i+1];
681 for (int j = _first_out[i]; j != last_out; ++j) {
683 Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
684 if (c >= MAX) return UNBOUNDED;
686 excess[_target[j]] += c;
691 for (int i = 0; i != _root; ++i) {
692 last_out = _first_out[i+1];
693 for (int j = _first_out[i]; j != last_out; ++j) {
694 if (_forward[j] && _cost[j] < 0) {
696 if (c >= MAX) return UNBOUNDED;
698 excess[_target[j]] += c;
703 Value ex, max_cap = 0;
704 for (int i = 0; i != _res_node_num; ++i) {
706 if (ex < 0) max_cap -= ex;
708 for (int j = 0; j != _res_arc_num; ++j) {
709 if (_upper[j] >= MAX) _upper[j] = max_cap;
712 // Initialize maps for Circulation and remove non-zero lower bounds
713 ConstMap<Arc, Value> low(0);
714 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
715 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
716 ValueArcMap cap(_graph), flow(_graph);
717 ValueNodeMap sup(_graph);
718 for (NodeIt n(_graph); n != INVALID; ++n) {
719 sup[n] = _supply[_node_id[n]];
722 for (ArcIt a(_graph); a != INVALID; ++a) {
725 cap[a] = _upper[j] - c;
726 sup[_graph.source(a)] -= c;
727 sup[_graph.target(a)] += c;
730 for (ArcIt a(_graph); a != INVALID; ++a) {
731 cap[a] = _upper[_arc_idf[a]];
735 // Find a feasible flow using Circulation
736 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
737 circ(_graph, low, cap, sup);
738 if (!circ.flowMap(flow).run()) return INFEASIBLE;
740 // Set residual capacities and handle GEQ supply type
741 if (_sum_supply < 0) {
742 for (ArcIt a(_graph); a != INVALID; ++a) {
744 _res_cap[_arc_idf[a]] = cap[a] - fa;
745 _res_cap[_arc_idb[a]] = fa;
746 sup[_graph.source(a)] -= fa;
747 sup[_graph.target(a)] += fa;
749 for (NodeIt n(_graph); n != INVALID; ++n) {
750 excess[_node_id[n]] = sup[n];
752 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
754 int ra = _reverse[a];
755 _res_cap[a] = -_sum_supply + 1;
756 _res_cap[ra] = -excess[u];
761 for (ArcIt a(_graph); a != INVALID; ++a) {
763 _res_cap[_arc_idf[a]] = cap[a] - fa;
764 _res_cap[_arc_idb[a]] = fa;
766 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
767 int ra = _reverse[a];
778 // Build a StaticDigraph structure containing the current
780 void buildResidualNetwork() {
784 for (int j = 0; j != _res_arc_num; ++j) {
785 if (_res_cap[j] > 0) {
786 _arc_vec.push_back(IntPair(_source[j], _target[j]));
787 _cost_vec.push_back(_cost[j]);
788 _id_vec.push_back(j);
791 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
794 // Execute the algorithm and transform the results
795 void start(Method method) {
796 // Execute the algorithm
798 case SIMPLE_CYCLE_CANCELING:
799 startSimpleCycleCanceling();
801 case MINIMUM_MEAN_CYCLE_CANCELING:
802 startMinMeanCycleCanceling();
804 case CANCEL_AND_TIGHTEN:
805 startCancelAndTighten();
809 // Compute node potentials
810 if (method != SIMPLE_CYCLE_CANCELING) {
811 buildResidualNetwork();
812 typename BellmanFord<StaticDigraph, CostArcMap>
813 ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
819 // Handle non-zero lower bounds
821 int limit = _first_out[_root];
822 for (int j = 0; j != limit; ++j) {
823 if (!_forward[j]) _res_cap[j] += _lower[j];
828 // Execute the "Simple Cycle Canceling" method
829 void startSimpleCycleCanceling() {
830 // Constants for computing the iteration limits
831 const int BF_FIRST_LIMIT = 2;
832 const double BF_LIMIT_FACTOR = 1.5;
834 typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
835 typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
836 typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
837 typedef typename BellmanFord<ResDigraph, CostArcMap>
838 ::template SetDistMap<CostNodeMap>
839 ::template SetPredMap<PredMap>::Create BF;
841 // Build the residual network
844 for (int j = 0; j != _res_arc_num; ++j) {
845 _arc_vec.push_back(IntPair(_source[j], _target[j]));
846 _cost_vec.push_back(_cost[j]);
848 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
850 FilterMap filter_map(_res_cap);
851 ResDigraph rgr(_sgr, filter_map);
852 std::vector<int> cycle;
853 std::vector<StaticDigraph::Arc> pred(_res_arc_num);
854 PredMap pred_map(pred);
855 BF bf(rgr, _cost_map);
856 bf.distMap(_pi_map).predMap(pred_map);
858 int length_bound = BF_FIRST_LIMIT;
859 bool optimal = false;
863 bool cycle_found = false;
864 while (!cycle_found) {
865 // Perform some iterations of the Bellman-Ford algorithm
866 int curr_iter_num = iter_num + length_bound <= _node_num ?
867 length_bound : _node_num - iter_num;
868 iter_num += curr_iter_num;
869 int real_iter_num = curr_iter_num;
870 for (int i = 0; i < curr_iter_num; ++i) {
871 if (bf.processNextWeakRound()) {
876 if (real_iter_num < curr_iter_num) {
877 // Optimal flow is found
881 // Search for node disjoint negative cycles
882 std::vector<int> state(_res_node_num, 0);
884 for (int u = 0; u != _res_node_num; ++u) {
885 if (state[u] != 0) continue;
888 for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
889 -1 : rgr.id(rgr.source(pred[v]))) {
892 if (v != -1 && state[v] == id) {
893 // A negative cycle is found
896 StaticDigraph::Arc a = pred[v];
897 Value d, delta = _res_cap[rgr.id(a)];
898 cycle.push_back(rgr.id(a));
899 while (rgr.id(rgr.source(a)) != v) {
900 a = pred_map[rgr.source(a)];
901 d = _res_cap[rgr.id(a)];
902 if (d < delta) delta = d;
903 cycle.push_back(rgr.id(a));
906 // Augment along the cycle
907 for (int i = 0; i < int(cycle.size()); ++i) {
909 _res_cap[j] -= delta;
910 _res_cap[_reverse[j]] += delta;
916 // Increase iteration limit if no cycle is found
918 length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
924 // Execute the "Minimum Mean Cycle Canceling" method
925 void startMinMeanCycleCanceling() {
926 typedef SimplePath<StaticDigraph> SPath;
927 typedef typename SPath::ArcIt SPathArcIt;
928 typedef typename HowardMmc<StaticDigraph, CostArcMap>
929 ::template SetPath<SPath>::Create MMC;
932 MMC mmc(_sgr, _cost_map);
934 buildResidualNetwork();
935 while (mmc.findCycleMean() && mmc.cycleCost() < 0) {
939 // Compute delta value
941 for (SPathArcIt a(cycle); a != INVALID; ++a) {
942 Value d = _res_cap[_id_vec[_sgr.id(a)]];
943 if (d < delta) delta = d;
946 // Augment along the cycle
947 for (SPathArcIt a(cycle); a != INVALID; ++a) {
948 int j = _id_vec[_sgr.id(a)];
949 _res_cap[j] -= delta;
950 _res_cap[_reverse[j]] += delta;
953 // Rebuild the residual network
954 buildResidualNetwork();
958 // Execute the "Cancel And Tighten" method
959 void startCancelAndTighten() {
960 // Constants for the min mean cycle computations
961 const double LIMIT_FACTOR = 1.0;
962 const int MIN_LIMIT = 5;
964 // Contruct auxiliary data vectors
965 DoubleVector pi(_res_node_num, 0.0);
966 IntVector level(_res_node_num);
967 BoolVector reached(_res_node_num);
968 BoolVector processed(_res_node_num);
969 IntVector pred_node(_res_node_num);
970 IntVector pred_arc(_res_node_num);
971 std::vector<int> stack(_res_node_num);
972 std::vector<int> proc_vector(_res_node_num);
974 // Initialize epsilon
976 for (int a = 0; a != _res_arc_num; ++a) {
977 if (_res_cap[a] > 0 && -_cost[a] > epsilon)
982 Tolerance<double> tol;
984 int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
985 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
987 while (epsilon * _res_node_num >= 1) {
988 // Find and cancel cycles in the admissible network using DFS
989 for (int u = 0; u != _res_node_num; ++u) {
991 processed[u] = false;
995 for (int start = 0; start != _res_node_num; ++start) {
996 if (reached[start]) continue;
999 reached[start] = true;
1000 pred_arc[start] = -1;
1001 pred_node[start] = -1;
1003 // Find the first admissible outgoing arc
1004 double p = pi[start];
1005 int a = _first_out[start];
1006 int last_out = _first_out[start+1];
1007 for (; a != last_out && (_res_cap[a] == 0 ||
1008 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1009 if (a == last_out) {
1010 processed[start] = true;
1011 proc_vector[++proc_head] = start;
1014 stack[++stack_head] = a;
1016 while (stack_head >= 0) {
1017 int sa = stack[stack_head];
1018 int u = _source[sa];
1019 int v = _target[sa];
1022 // A new node is reached
1028 last_out = _first_out[v+1];
1029 for (; a != last_out && (_res_cap[a] == 0 ||
1030 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1031 stack[++stack_head] = a == last_out ? -1 : a;
1033 if (!processed[v]) {
1036 Value d, delta = _res_cap[sa];
1037 for (n = u; n != v; n = pred_node[n]) {
1038 d = _res_cap[pred_arc[n]];
1045 // Augment along the cycle
1046 _res_cap[sa] -= delta;
1047 _res_cap[_reverse[sa]] += delta;
1048 for (n = u; n != v; n = pred_node[n]) {
1049 int pa = pred_arc[n];
1050 _res_cap[pa] -= delta;
1051 _res_cap[_reverse[pa]] += delta;
1053 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1061 // Find the next admissible outgoing arc
1063 a = stack[stack_head] + 1;
1064 last_out = _first_out[v+1];
1065 for (; a != last_out && (_res_cap[a] == 0 ||
1066 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1067 stack[stack_head] = a == last_out ? -1 : a;
1070 while (stack_head >= 0 && stack[stack_head] == -1) {
1071 processed[v] = true;
1072 proc_vector[++proc_head] = v;
1073 if (--stack_head >= 0) {
1074 // Find the next admissible outgoing arc
1075 v = _source[stack[stack_head]];
1077 a = stack[stack_head] + 1;
1078 last_out = _first_out[v+1];
1079 for (; a != last_out && (_res_cap[a] == 0 ||
1080 !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1081 stack[stack_head] = a == last_out ? -1 : a;
1087 // Tighten potentials and epsilon
1089 for (int u = 0; u != _res_node_num; ++u) {
1092 for (int i = proc_head; i > 0; --i) {
1093 int u = proc_vector[i];
1095 int l = level[u] + 1;
1096 int last_out = _first_out[u+1];
1097 for (int a = _first_out[u]; a != last_out; ++a) {
1099 if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1100 l > level[v]) level[v] = l;
1104 // Modify potentials
1105 double q = std::numeric_limits<double>::max();
1106 for (int u = 0; u != _res_node_num; ++u) {
1108 double p, pu = pi[u];
1109 int last_out = _first_out[u+1];
1110 for (int a = _first_out[u]; a != last_out; ++a) {
1111 if (_res_cap[a] == 0) continue;
1113 int ld = lu - level[v];
1115 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1120 for (int u = 0; u != _res_node_num; ++u) {
1121 pi[u] -= q * level[u];
1126 for (int u = 0; u != _res_node_num; ++u) {
1127 double curr, pu = pi[u];
1128 int last_out = _first_out[u+1];
1129 for (int a = _first_out[u]; a != last_out; ++a) {
1130 if (_res_cap[a] == 0) continue;
1131 curr = _cost[a] + pu - pi[_target[a]];
1132 if (-curr > epsilon) epsilon = -curr;
1136 typedef HowardMmc<StaticDigraph, CostArcMap> MMC;
1137 typedef typename BellmanFord<StaticDigraph, CostArcMap>
1138 ::template SetDistMap<CostNodeMap>::Create BF;
1140 // Set epsilon to the minimum cycle mean
1141 buildResidualNetwork();
1142 MMC mmc(_sgr, _cost_map);
1143 mmc.findCycleMean();
1144 epsilon = -mmc.cycleMean();
1145 Cost cycle_cost = mmc.cycleCost();
1146 int cycle_size = mmc.cycleSize();
1148 // Compute feasible potentials for the current epsilon
1149 for (int i = 0; i != int(_cost_vec.size()); ++i) {
1150 _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1152 BF bf(_sgr, _cost_map);
1153 bf.distMap(_pi_map);
1156 for (int u = 0; u != _res_node_num; ++u) {
1157 pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1165 }; //class CycleCanceling
1171 #endif //LEMON_CYCLE_CANCELING_H