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_COST_SCALING_H
20 #define LEMON_COST_SCALING_H
22 /// \ingroup min_cost_flow_algs
24 /// \brief Cost scaling algorithm for finding a minimum cost flow.
30 #include <lemon/core.h>
31 #include <lemon/maps.h>
32 #include <lemon/math.h>
33 #include <lemon/static_graph.h>
34 #include <lemon/circulation.h>
35 #include <lemon/bellman_ford.h>
39 /// \brief Default traits class of CostScaling algorithm.
41 /// Default traits class of CostScaling algorithm.
42 /// \tparam GR Digraph type.
43 /// \tparam V The number type used for flow amounts, capacity bounds
44 /// and supply values. By default it is \c int.
45 /// \tparam C The number type used for costs and potentials.
46 /// By default it is the same as \c V.
48 template <typename GR, typename V = int, typename C = V>
50 template < typename GR, typename V = int, typename C = V,
51 bool integer = std::numeric_limits<C>::is_integer >
53 struct CostScalingDefaultTraits
55 /// The type of the digraph
57 /// The type of the flow amounts, capacity bounds and supply values
59 /// The type of the arc costs
62 /// \brief The large cost type used for internal computations
64 /// The large cost type used for internal computations.
65 /// It is \c long \c long if the \c Cost type is integer,
66 /// otherwise it is \c double.
67 /// \c Cost must be convertible to \c LargeCost.
68 typedef double LargeCost;
71 // Default traits class for integer cost types
72 template <typename GR, typename V, typename C>
73 struct CostScalingDefaultTraits<GR, V, C, true>
78 #ifdef LEMON_HAVE_LONG_LONG
79 typedef long long LargeCost;
81 typedef long LargeCost;
86 /// \addtogroup min_cost_flow_algs
89 /// \brief Implementation of the Cost Scaling algorithm for
90 /// finding a \ref min_cost_flow "minimum cost flow".
92 /// \ref CostScaling implements a cost scaling algorithm that performs
93 /// push/augment and relabel operations for finding a \ref min_cost_flow
94 /// "minimum cost flow" \cite amo93networkflows, \cite goldberg90approximation,
95 /// \cite goldberg97efficient, \cite bunnagel98efficient.
96 /// It is a highly efficient primal-dual solution method, which
97 /// can be viewed as the generalization of the \ref Preflow
98 /// "preflow push-relabel" algorithm for the maximum flow problem.
99 /// It is a polynomial algorithm, its running time complexity is
100 /// \f$O(n^2e\log(nK))\f$, where <i>K</i> denotes the maximum arc cost.
102 /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
103 /// implementations available in LEMON for solving this problem.
104 /// (For more information, see \ref min_cost_flow_algs "the module page".)
106 /// Most of the parameters of the problem (except for the digraph)
107 /// can be given using separate functions, and the algorithm can be
108 /// executed using the \ref run() function. If some parameters are not
109 /// specified, then default values will be used.
111 /// \tparam GR The digraph type the algorithm runs on.
112 /// \tparam V The number type used for flow amounts, capacity bounds
113 /// and supply values in the algorithm. By default, it is \c int.
114 /// \tparam C The number type used for costs and potentials in the
115 /// algorithm. By default, it is the same as \c V.
116 /// \tparam TR The traits class that defines various types used by the
117 /// algorithm. By default, it is \ref CostScalingDefaultTraits
118 /// "CostScalingDefaultTraits<GR, V, C>".
119 /// In most cases, this parameter should not be set directly,
120 /// consider to use the named template parameters instead.
122 /// \warning Both \c V and \c C must be signed number types.
123 /// \warning All input data (capacities, supply values, and costs) must
125 /// \warning This algorithm does not support negative costs for
126 /// arcs having infinite upper bound.
128 /// \note %CostScaling provides three different internal methods,
129 /// from which the most efficient one is used by default.
130 /// For more information, see \ref Method.
132 template <typename GR, typename V, typename C, typename TR>
134 template < typename GR, typename V = int, typename C = V,
135 typename TR = CostScalingDefaultTraits<GR, V, C> >
141 /// The type of the digraph
142 typedef typename TR::Digraph Digraph;
143 /// The type of the flow amounts, capacity bounds and supply values
144 typedef typename TR::Value Value;
145 /// The type of the arc costs
146 typedef typename TR::Cost Cost;
148 /// \brief The large cost type
150 /// The large cost type used for internal computations.
151 /// By default, it is \c long \c long if the \c Cost type is integer,
152 /// otherwise it is \c double.
153 typedef typename TR::LargeCost LargeCost;
155 /// \brief The \ref lemon::CostScalingDefaultTraits "traits class"
161 /// \brief Problem type constants for the \c run() function.
163 /// Enum type containing the problem type constants that can be
164 /// returned by the \ref run() function of the algorithm.
166 /// The problem has no feasible solution (flow).
168 /// The problem has optimal solution (i.e. it is feasible and
169 /// bounded), and the algorithm has found optimal flow and node
170 /// potentials (primal and dual solutions).
172 /// The digraph contains an arc of negative cost and infinite
173 /// upper bound. It means that the objective function is unbounded
174 /// on that arc, however, note that it could actually be bounded
175 /// over the feasible flows, but this algroithm cannot handle
180 /// \brief Constants for selecting the internal method.
182 /// Enum type containing constants for selecting the internal method
183 /// for the \ref run() function.
185 /// \ref CostScaling provides three internal methods that differ mainly
186 /// in their base operations, which are used in conjunction with the
187 /// relabel operation.
188 /// By default, the so called \ref PARTIAL_AUGMENT
189 /// "Partial Augment-Relabel" method is used, which turned out to be
190 /// the most efficient and the most robust on various test inputs.
191 /// However, the other methods can be selected using the \ref run()
192 /// function with the proper parameter.
194 /// Local push operations are used, i.e. flow is moved only on one
195 /// admissible arc at once.
197 /// Augment operations are used, i.e. flow is moved on admissible
198 /// paths from a node with excess to a node with deficit.
200 /// Partial augment operations are used, i.e. flow is moved on
201 /// admissible paths started from a node with excess, but the
202 /// lengths of these paths are limited. This method can be viewed
203 /// as a combined version of the previous two operations.
209 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
211 typedef std::vector<int> IntVector;
212 typedef std::vector<Value> ValueVector;
213 typedef std::vector<Cost> CostVector;
214 typedef std::vector<LargeCost> LargeCostVector;
215 typedef std::vector<char> BoolVector;
216 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
220 template <typename KT, typename VT>
221 class StaticVectorMap {
226 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
228 const Value& operator[](const Key& key) const {
229 return _v[StaticDigraph::id(key)];
232 Value& operator[](const Key& key) {
233 return _v[StaticDigraph::id(key)];
236 void set(const Key& key, const Value& val) {
237 _v[StaticDigraph::id(key)] = val;
241 std::vector<Value>& _v;
244 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
248 // Data related to the underlying digraph
256 // Parameters of the problem
261 // Data structures for storing the digraph
265 IntVector _first_out;
277 ValueVector _res_cap;
278 LargeCostVector _cost;
282 std::deque<int> _active_nodes;
289 IntVector _bucket_next;
290 IntVector _bucket_prev;
296 /// \brief Constant for infinite upper bounds (capacities).
298 /// Constant for infinite upper bounds (capacities).
299 /// It is \c std::numeric_limits<Value>::infinity() if available,
300 /// \c std::numeric_limits<Value>::max() otherwise.
305 /// \name Named Template Parameters
308 template <typename T>
309 struct SetLargeCostTraits : public Traits {
313 /// \brief \ref named-templ-param "Named parameter" for setting
314 /// \c LargeCost type.
316 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
317 /// type, which is used for internal computations in the algorithm.
318 /// \c Cost must be convertible to \c LargeCost.
319 template <typename T>
321 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
322 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
333 /// \brief Constructor.
335 /// The constructor of the class.
337 /// \param graph The digraph the algorithm runs on.
338 CostScaling(const GR& graph) :
339 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
340 INF(std::numeric_limits<Value>::has_infinity ?
341 std::numeric_limits<Value>::infinity() :
342 std::numeric_limits<Value>::max())
344 // Check the number types
345 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
346 "The flow type of CostScaling must be signed");
347 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
348 "The cost type of CostScaling must be signed");
350 // Reset data structures
355 /// The parameters of the algorithm can be specified using these
360 /// \brief Set the lower bounds on the arcs.
362 /// This function sets the lower bounds on the arcs.
363 /// If it is not used before calling \ref run(), the lower bounds
364 /// will be set to zero on all arcs.
366 /// \param map An arc map storing the lower bounds.
367 /// Its \c Value type must be convertible to the \c Value type
368 /// of the algorithm.
370 /// \return <tt>(*this)</tt>
371 template <typename LowerMap>
372 CostScaling& lowerMap(const LowerMap& map) {
374 for (ArcIt a(_graph); a != INVALID; ++a) {
375 _lower[_arc_idf[a]] = map[a];
376 _lower[_arc_idb[a]] = map[a];
381 /// \brief Set the upper bounds (capacities) on the arcs.
383 /// This function sets the upper bounds (capacities) on the arcs.
384 /// If it is not used before calling \ref run(), the upper bounds
385 /// will be set to \ref INF on all arcs (i.e. the flow value will be
386 /// unbounded from above).
388 /// \param map An arc map storing the upper bounds.
389 /// Its \c Value type must be convertible to the \c Value type
390 /// of the algorithm.
392 /// \return <tt>(*this)</tt>
393 template<typename UpperMap>
394 CostScaling& upperMap(const UpperMap& map) {
395 for (ArcIt a(_graph); a != INVALID; ++a) {
396 _upper[_arc_idf[a]] = map[a];
401 /// \brief Set the costs of the arcs.
403 /// This function sets the costs of the arcs.
404 /// If it is not used before calling \ref run(), the costs
405 /// will be set to \c 1 on all arcs.
407 /// \param map An arc map storing the costs.
408 /// Its \c Value type must be convertible to the \c Cost type
409 /// of the algorithm.
411 /// \return <tt>(*this)</tt>
412 template<typename CostMap>
413 CostScaling& costMap(const CostMap& map) {
414 for (ArcIt a(_graph); a != INVALID; ++a) {
415 _scost[_arc_idf[a]] = map[a];
416 _scost[_arc_idb[a]] = -map[a];
421 /// \brief Set the supply values of the nodes.
423 /// This function sets the supply values of the nodes.
424 /// If neither this function nor \ref stSupply() is used before
425 /// calling \ref run(), the supply of each node will be set to zero.
427 /// \param map A node map storing the supply values.
428 /// Its \c Value type must be convertible to the \c Value type
429 /// of the algorithm.
431 /// \return <tt>(*this)</tt>
432 template<typename SupplyMap>
433 CostScaling& supplyMap(const SupplyMap& map) {
434 for (NodeIt n(_graph); n != INVALID; ++n) {
435 _supply[_node_id[n]] = map[n];
440 /// \brief Set single source and target nodes and a supply value.
442 /// This function sets a single source node and a single target node
443 /// and the required flow value.
444 /// If neither this function nor \ref supplyMap() is used before
445 /// calling \ref run(), the supply of each node will be set to zero.
447 /// Using this function has the same effect as using \ref supplyMap()
448 /// with a map in which \c k is assigned to \c s, \c -k is
449 /// assigned to \c t and all other nodes have zero supply value.
451 /// \param s The source node.
452 /// \param t The target node.
453 /// \param k The required amount of flow from node \c s to node \c t
454 /// (i.e. the supply of \c s and the demand of \c t).
456 /// \return <tt>(*this)</tt>
457 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
458 for (int i = 0; i != _res_node_num; ++i) {
461 _supply[_node_id[s]] = k;
462 _supply[_node_id[t]] = -k;
468 /// \name Execution control
469 /// The algorithm can be executed using \ref run().
473 /// \brief Run the algorithm.
475 /// This function runs the algorithm.
476 /// The paramters can be specified using functions \ref lowerMap(),
477 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
480 /// CostScaling<ListDigraph> cs(graph);
481 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
482 /// .supplyMap(sup).run();
485 /// This function can be called more than once. All the given parameters
486 /// are kept for the next call, unless \ref resetParams() or \ref reset()
487 /// is used, thus only the modified parameters have to be set again.
488 /// If the underlying digraph was also modified after the construction
489 /// of the class (or the last \ref reset() call), then the \ref reset()
490 /// function must be called.
492 /// \param method The internal method that will be used in the
493 /// algorithm. For more information, see \ref Method.
494 /// \param factor The cost scaling factor. It must be at least two.
496 /// \return \c INFEASIBLE if no feasible flow exists,
497 /// \n \c OPTIMAL if the problem has optimal solution
498 /// (i.e. it is feasible and bounded), and the algorithm has found
499 /// optimal flow and node potentials (primal and dual solutions),
500 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
501 /// and infinite upper bound. It means that the objective function
502 /// is unbounded on that arc, however, note that it could actually be
503 /// bounded over the feasible flows, but this algroithm cannot handle
506 /// \see ProblemType, Method
507 /// \see resetParams(), reset()
508 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
509 LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
511 ProblemType pt = init();
512 if (pt != OPTIMAL) return pt;
517 /// \brief Reset all the parameters that have been given before.
519 /// This function resets all the paramaters that have been given
520 /// before using functions \ref lowerMap(), \ref upperMap(),
521 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
523 /// It is useful for multiple \ref run() calls. Basically, all the given
524 /// parameters are kept for the next \ref run() call, unless
525 /// \ref resetParams() or \ref reset() is used.
526 /// If the underlying digraph was also modified after the construction
527 /// of the class or the last \ref reset() call, then the \ref reset()
528 /// function must be used, otherwise \ref resetParams() is sufficient.
532 /// CostScaling<ListDigraph> cs(graph);
535 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
536 /// .supplyMap(sup).run();
538 /// // Run again with modified cost map (resetParams() is not called,
539 /// // so only the cost map have to be set again)
541 /// cs.costMap(cost).run();
543 /// // Run again from scratch using resetParams()
544 /// // (the lower bounds will be set to zero on all arcs)
545 /// cs.resetParams();
546 /// cs.upperMap(capacity).costMap(cost)
547 /// .supplyMap(sup).run();
550 /// \return <tt>(*this)</tt>
552 /// \see reset(), run()
553 CostScaling& resetParams() {
554 for (int i = 0; i != _res_node_num; ++i) {
557 int limit = _first_out[_root];
558 for (int j = 0; j != limit; ++j) {
561 _scost[j] = _forward[j] ? 1 : -1;
563 for (int j = limit; j != _res_arc_num; ++j) {
567 _scost[_reverse[j]] = 0;
573 /// \brief Reset the internal data structures and all the parameters
574 /// that have been given before.
576 /// This function resets the internal data structures and all the
577 /// paramaters that have been given before using functions \ref lowerMap(),
578 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
580 /// It is useful for multiple \ref run() calls. By default, all the given
581 /// parameters are kept for the next \ref run() call, unless
582 /// \ref resetParams() or \ref reset() is used.
583 /// If the underlying digraph was also modified after the construction
584 /// of the class or the last \ref reset() call, then the \ref reset()
585 /// function must be used, otherwise \ref resetParams() is sufficient.
587 /// See \ref resetParams() for examples.
589 /// \return <tt>(*this)</tt>
591 /// \see resetParams(), run()
592 CostScaling& reset() {
594 _node_num = countNodes(_graph);
595 _arc_num = countArcs(_graph);
596 _res_node_num = _node_num + 1;
597 _res_arc_num = 2 * (_arc_num + _node_num);
600 _first_out.resize(_res_node_num + 1);
601 _forward.resize(_res_arc_num);
602 _source.resize(_res_arc_num);
603 _target.resize(_res_arc_num);
604 _reverse.resize(_res_arc_num);
606 _lower.resize(_res_arc_num);
607 _upper.resize(_res_arc_num);
608 _scost.resize(_res_arc_num);
609 _supply.resize(_res_node_num);
611 _res_cap.resize(_res_arc_num);
612 _cost.resize(_res_arc_num);
613 _pi.resize(_res_node_num);
614 _excess.resize(_res_node_num);
615 _next_out.resize(_res_node_num);
618 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
619 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
623 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
625 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
629 _target[j] = _node_id[_graph.runningNode(a)];
631 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
635 _target[j] = _node_id[_graph.runningNode(a)];
648 _first_out[_res_node_num] = k;
649 for (ArcIt a(_graph); a != INVALID; ++a) {
650 int fi = _arc_idf[a];
651 int bi = _arc_idb[a];
663 /// \name Query Functions
664 /// The results of the algorithm can be obtained using these
666 /// The \ref run() function must be called before using them.
670 /// \brief Return the total cost of the found flow.
672 /// This function returns the total cost of the found flow.
673 /// Its complexity is O(e).
675 /// \note The return type of the function can be specified as a
676 /// template parameter. For example,
678 /// cs.totalCost<double>();
680 /// It is useful if the total cost cannot be stored in the \c Cost
681 /// type of the algorithm, which is the default return type of the
684 /// \pre \ref run() must be called before using this function.
685 template <typename Number>
686 Number totalCost() const {
688 for (ArcIt a(_graph); a != INVALID; ++a) {
690 c += static_cast<Number>(_res_cap[i]) *
691 (-static_cast<Number>(_scost[i]));
697 Cost totalCost() const {
698 return totalCost<Cost>();
702 /// \brief Return the flow on the given arc.
704 /// This function returns the flow on the given arc.
706 /// \pre \ref run() must be called before using this function.
707 Value flow(const Arc& a) const {
708 return _res_cap[_arc_idb[a]];
711 /// \brief Copy the flow values (the primal solution) into the
714 /// This function copies the flow value on each arc into the given
715 /// map. The \c Value type of the algorithm must be convertible to
716 /// the \c Value type of the map.
718 /// \pre \ref run() must be called before using this function.
719 template <typename FlowMap>
720 void flowMap(FlowMap &map) const {
721 for (ArcIt a(_graph); a != INVALID; ++a) {
722 map.set(a, _res_cap[_arc_idb[a]]);
726 /// \brief Return the potential (dual value) of the given node.
728 /// This function returns the potential (dual value) of the
731 /// \pre \ref run() must be called before using this function.
732 Cost potential(const Node& n) const {
733 return static_cast<Cost>(_pi[_node_id[n]]);
736 /// \brief Copy the potential values (the dual solution) into the
739 /// This function copies the potential (dual value) of each node
740 /// into the given map.
741 /// The \c Cost type of the algorithm must be convertible to the
742 /// \c Value type of the map.
744 /// \pre \ref run() must be called before using this function.
745 template <typename PotentialMap>
746 void potentialMap(PotentialMap &map) const {
747 for (NodeIt n(_graph); n != INVALID; ++n) {
748 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
756 // Initialize the algorithm
758 if (_res_node_num <= 1) return INFEASIBLE;
760 // Check the sum of supply values
762 for (int i = 0; i != _root; ++i) {
763 _sum_supply += _supply[i];
765 if (_sum_supply > 0) return INFEASIBLE;
767 // Check lower and upper bounds
768 LEMON_DEBUG(checkBoundMaps(),
769 "Upper bounds must be greater or equal to the lower bounds");
772 // Initialize vectors
773 for (int i = 0; i != _res_node_num; ++i) {
775 _excess[i] = _supply[i];
778 // Remove infinite upper bounds and check negative arcs
779 const Value MAX = std::numeric_limits<Value>::max();
782 for (int i = 0; i != _root; ++i) {
783 last_out = _first_out[i+1];
784 for (int j = _first_out[i]; j != last_out; ++j) {
786 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
787 if (c >= MAX) return UNBOUNDED;
789 _excess[_target[j]] += c;
794 for (int i = 0; i != _root; ++i) {
795 last_out = _first_out[i+1];
796 for (int j = _first_out[i]; j != last_out; ++j) {
797 if (_forward[j] && _scost[j] < 0) {
799 if (c >= MAX) return UNBOUNDED;
801 _excess[_target[j]] += c;
806 Value ex, max_cap = 0;
807 for (int i = 0; i != _res_node_num; ++i) {
810 if (ex < 0) max_cap -= ex;
812 for (int j = 0; j != _res_arc_num; ++j) {
813 if (_upper[j] >= MAX) _upper[j] = max_cap;
816 // Initialize the large cost vector and the epsilon parameter
819 for (int i = 0; i != _root; ++i) {
820 last_out = _first_out[i+1];
821 for (int j = _first_out[i]; j != last_out; ++j) {
822 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
824 if (lc > _epsilon) _epsilon = lc;
829 // Initialize maps for Circulation and remove non-zero lower bounds
830 ConstMap<Arc, Value> low(0);
831 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
832 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
833 ValueArcMap cap(_graph), flow(_graph);
834 ValueNodeMap sup(_graph);
835 for (NodeIt n(_graph); n != INVALID; ++n) {
836 sup[n] = _supply[_node_id[n]];
839 for (ArcIt a(_graph); a != INVALID; ++a) {
842 cap[a] = _upper[j] - c;
843 sup[_graph.source(a)] -= c;
844 sup[_graph.target(a)] += c;
847 for (ArcIt a(_graph); a != INVALID; ++a) {
848 cap[a] = _upper[_arc_idf[a]];
853 for (NodeIt n(_graph); n != INVALID; ++n) {
854 if (sup[n] > 0) ++_sup_node_num;
857 // Find a feasible flow using Circulation
858 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
859 circ(_graph, low, cap, sup);
860 if (!circ.flowMap(flow).run()) return INFEASIBLE;
862 // Set residual capacities and handle GEQ supply type
863 if (_sum_supply < 0) {
864 for (ArcIt a(_graph); a != INVALID; ++a) {
866 _res_cap[_arc_idf[a]] = cap[a] - fa;
867 _res_cap[_arc_idb[a]] = fa;
868 sup[_graph.source(a)] -= fa;
869 sup[_graph.target(a)] += fa;
871 for (NodeIt n(_graph); n != INVALID; ++n) {
872 _excess[_node_id[n]] = sup[n];
874 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
876 int ra = _reverse[a];
877 _res_cap[a] = -_sum_supply + 1;
878 _res_cap[ra] = -_excess[u];
884 for (ArcIt a(_graph); a != INVALID; ++a) {
886 _res_cap[_arc_idf[a]] = cap[a] - fa;
887 _res_cap[_arc_idb[a]] = fa;
889 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
890 int ra = _reverse[a];
898 // Initialize data structures for buckets
899 _max_rank = _alpha * _res_node_num;
900 _buckets.resize(_max_rank);
901 _bucket_next.resize(_res_node_num + 1);
902 _bucket_prev.resize(_res_node_num + 1);
903 _rank.resize(_res_node_num + 1);
908 // Check if the upper bound is greater or equal to the lower bound
910 bool checkBoundMaps() {
911 for (int j = 0; j != _res_arc_num; ++j) {
912 if (_upper[j] < _lower[j]) return false;
917 // Execute the algorithm and transform the results
918 void start(Method method) {
919 const int MAX_PARTIAL_PATH_LENGTH = 4;
926 startAugment(_res_node_num - 1);
928 case PARTIAL_AUGMENT:
929 startAugment(MAX_PARTIAL_PATH_LENGTH);
933 // Compute node potentials (dual solution)
934 for (int i = 0; i != _res_node_num; ++i) {
935 _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
938 for (int i = 0; optimal && i != _res_node_num; ++i) {
939 LargeCost pi_i = _pi[i];
940 int last_out = _first_out[i+1];
941 for (int j = _first_out[i]; j != last_out; ++j) {
942 if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
950 // Compute node potentials for the original costs with BellmanFord
951 // (if it is necessary)
952 typedef std::pair<int, int> IntPair;
954 std::vector<IntPair> arc_vec;
955 std::vector<LargeCost> cost_vec;
956 LargeCostArcMap cost_map(cost_vec);
960 for (int j = 0; j != _res_arc_num; ++j) {
961 if (_res_cap[j] > 0) {
962 int u = _source[j], v = _target[j];
963 arc_vec.push_back(IntPair(u, v));
964 cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
967 sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
969 typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
974 for (int i = 0; i != _res_node_num; ++i) {
975 _pi[i] += bf.dist(sgr.node(i));
979 // Shift potentials to meet the requirements of the GEQ type
980 // optimality conditions
981 LargeCost max_pot = _pi[_root];
982 for (int i = 0; i != _res_node_num; ++i) {
983 if (_pi[i] > max_pot) max_pot = _pi[i];
986 for (int i = 0; i != _res_node_num; ++i) {
991 // Handle non-zero lower bounds
993 int limit = _first_out[_root];
994 for (int j = 0; j != limit; ++j) {
995 if (!_forward[j]) _res_cap[j] += _lower[j];
1000 // Initialize a cost scaling phase
1002 // Saturate arcs not satisfying the optimality condition
1003 for (int u = 0; u != _res_node_num; ++u) {
1004 int last_out = _first_out[u+1];
1005 LargeCost pi_u = _pi[u];
1006 for (int a = _first_out[u]; a != last_out; ++a) {
1007 Value delta = _res_cap[a];
1010 if (_cost[a] + pi_u - _pi[v] < 0) {
1011 _excess[u] -= delta;
1012 _excess[v] += delta;
1014 _res_cap[_reverse[a]] += delta;
1020 // Find active nodes (i.e. nodes with positive excess)
1021 for (int u = 0; u != _res_node_num; ++u) {
1022 if (_excess[u] > 0) _active_nodes.push_back(u);
1025 // Initialize the next arcs
1026 for (int u = 0; u != _res_node_num; ++u) {
1027 _next_out[u] = _first_out[u];
1031 // Price (potential) refinement heuristic
1032 bool priceRefinement() {
1034 // Stack for stroing the topological order
1035 IntVector stack(_res_node_num);
1039 while (topologicalSort(stack, stack_top)) {
1041 // Compute node ranks in the acyclic admissible network and
1042 // store the nodes in buckets
1043 for (int i = 0; i != _res_node_num; ++i) {
1046 const int bucket_end = _root + 1;
1047 for (int r = 0; r != _max_rank; ++r) {
1048 _buckets[r] = bucket_end;
1051 for ( ; stack_top >= 0; --stack_top) {
1052 int u = stack[stack_top], v;
1053 int rank_u = _rank[u];
1055 LargeCost rc, pi_u = _pi[u];
1056 int last_out = _first_out[u+1];
1057 for (int a = _first_out[u]; a != last_out; ++a) {
1058 if (_res_cap[a] > 0) {
1060 rc = _cost[a] + pi_u - _pi[v];
1062 LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1063 if (nrc < LargeCost(_max_rank)) {
1064 int new_rank_v = rank_u + static_cast<int>(nrc);
1065 if (new_rank_v > _rank[v]) {
1066 _rank[v] = new_rank_v;
1074 top_rank = std::max(top_rank, rank_u);
1075 int bfirst = _buckets[rank_u];
1076 _bucket_next[u] = bfirst;
1077 _bucket_prev[bfirst] = u;
1078 _buckets[rank_u] = u;
1082 // Check if the current flow is epsilon-optimal
1083 if (top_rank == 0) {
1087 // Process buckets in top-down order
1088 for (int rank = top_rank; rank > 0; --rank) {
1089 while (_buckets[rank] != bucket_end) {
1090 // Remove the first node from the current bucket
1091 int u = _buckets[rank];
1092 _buckets[rank] = _bucket_next[u];
1094 // Search the outgoing arcs of u
1095 LargeCost rc, pi_u = _pi[u];
1096 int last_out = _first_out[u+1];
1097 int v, old_rank_v, new_rank_v;
1098 for (int a = _first_out[u]; a != last_out; ++a) {
1099 if (_res_cap[a] > 0) {
1101 old_rank_v = _rank[v];
1103 if (old_rank_v < rank) {
1105 // Compute the new rank of node v
1106 rc = _cost[a] + pi_u - _pi[v];
1110 LargeCost nrc = rc / _epsilon;
1112 if (nrc < LargeCost(_max_rank)) {
1113 new_rank_v = rank - 1 - static_cast<int>(nrc);
1117 // Change the rank of node v
1118 if (new_rank_v > old_rank_v) {
1119 _rank[v] = new_rank_v;
1121 // Remove v from its old bucket
1122 if (old_rank_v > 0) {
1123 if (_buckets[old_rank_v] == v) {
1124 _buckets[old_rank_v] = _bucket_next[v];
1126 int pv = _bucket_prev[v], nv = _bucket_next[v];
1127 _bucket_next[pv] = nv;
1128 _bucket_prev[nv] = pv;
1132 // Insert v into its new bucket
1133 int nv = _buckets[new_rank_v];
1134 _bucket_next[v] = nv;
1135 _bucket_prev[nv] = v;
1136 _buckets[new_rank_v] = v;
1142 // Refine potential of node u
1143 _pi[u] -= rank * _epsilon;
1152 // Find and cancel cycles in the admissible network and
1153 // determine topological order using DFS
1154 bool topologicalSort(IntVector &stack, int &stack_top) {
1155 const int MAX_CYCLE_CANCEL = 1;
1157 BoolVector reached(_res_node_num, false);
1158 BoolVector processed(_res_node_num, false);
1159 IntVector pred(_res_node_num);
1160 for (int i = 0; i != _res_node_num; ++i) {
1161 _next_out[i] = _first_out[i];
1166 for (int start = 0; start != _res_node_num; ++start) {
1167 if (reached[start]) continue;
1169 // Start DFS search from this start node
1173 // Check the outgoing arcs of the current tip node
1174 reached[tip] = true;
1175 LargeCost pi_tip = _pi[tip];
1176 int a, last_out = _first_out[tip+1];
1177 for (a = _next_out[tip]; a != last_out; ++a) {
1178 if (_res_cap[a] > 0) {
1180 if (_cost[a] + pi_tip - _pi[v] < 0) {
1182 // A new node is reached
1188 last_out = _first_out[tip+1];
1191 else if (!processed[v]) {
1196 // Find the minimum residual capacity along the cycle
1197 Value d, delta = _res_cap[a];
1198 int u, delta_node = tip;
1199 for (u = tip; u != v; ) {
1201 d = _res_cap[_next_out[u]];
1208 // Augment along the cycle
1209 _res_cap[a] -= delta;
1210 _res_cap[_reverse[a]] += delta;
1211 for (u = tip; u != v; ) {
1213 int ca = _next_out[u];
1214 _res_cap[ca] -= delta;
1215 _res_cap[_reverse[ca]] += delta;
1218 // Check the maximum number of cycle canceling
1219 if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1223 // Roll back search to delta_node
1224 if (delta_node != tip) {
1225 for (u = tip; u != delta_node; u = pred[u]) {
1229 a = _next_out[tip] + 1;
1230 last_out = _first_out[tip+1];
1238 // Step back to the previous node
1239 if (a == last_out) {
1240 processed[tip] = true;
1241 stack[++stack_top] = tip;
1244 // Finish DFS from the current start node
1253 return (cycle_cnt == 0);
1256 // Global potential update heuristic
1257 void globalUpdate() {
1258 const int bucket_end = _root + 1;
1260 // Initialize buckets
1261 for (int r = 0; r != _max_rank; ++r) {
1262 _buckets[r] = bucket_end;
1264 Value total_excess = 0;
1265 int b0 = bucket_end;
1266 for (int i = 0; i != _res_node_num; ++i) {
1267 if (_excess[i] < 0) {
1269 _bucket_next[i] = b0;
1270 _bucket_prev[b0] = i;
1273 total_excess += _excess[i];
1274 _rank[i] = _max_rank;
1277 if (total_excess == 0) return;
1280 // Search the buckets
1282 for ( ; r != _max_rank; ++r) {
1283 while (_buckets[r] != bucket_end) {
1284 // Remove the first node from the current bucket
1285 int u = _buckets[r];
1286 _buckets[r] = _bucket_next[u];
1288 // Search the incoming arcs of u
1289 LargeCost pi_u = _pi[u];
1290 int last_out = _first_out[u+1];
1291 for (int a = _first_out[u]; a != last_out; ++a) {
1292 int ra = _reverse[a];
1293 if (_res_cap[ra] > 0) {
1294 int v = _source[ra];
1295 int old_rank_v = _rank[v];
1296 if (r < old_rank_v) {
1297 // Compute the new rank of v
1298 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1299 int new_rank_v = old_rank_v;
1300 if (nrc < LargeCost(_max_rank)) {
1301 new_rank_v = r + 1 + static_cast<int>(nrc);
1304 // Change the rank of v
1305 if (new_rank_v < old_rank_v) {
1306 _rank[v] = new_rank_v;
1307 _next_out[v] = _first_out[v];
1309 // Remove v from its old bucket
1310 if (old_rank_v < _max_rank) {
1311 if (_buckets[old_rank_v] == v) {
1312 _buckets[old_rank_v] = _bucket_next[v];
1314 int pv = _bucket_prev[v], nv = _bucket_next[v];
1315 _bucket_next[pv] = nv;
1316 _bucket_prev[nv] = pv;
1320 // Insert v into its new bucket
1321 int nv = _buckets[new_rank_v];
1322 _bucket_next[v] = nv;
1323 _bucket_prev[nv] = v;
1324 _buckets[new_rank_v] = v;
1330 // Finish search if there are no more active nodes
1331 if (_excess[u] > 0) {
1332 total_excess -= _excess[u];
1333 if (total_excess <= 0) break;
1336 if (total_excess <= 0) break;
1340 for (int u = 0; u != _res_node_num; ++u) {
1341 int k = std::min(_rank[u], r);
1343 _pi[u] -= _epsilon * k;
1344 _next_out[u] = _first_out[u];
1349 /// Execute the algorithm performing augment and relabel operations
1350 void startAugment(int max_length) {
1351 // Paramters for heuristics
1352 const int PRICE_REFINEMENT_LIMIT = 2;
1353 const double GLOBAL_UPDATE_FACTOR = 1.0;
1354 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1355 (_res_node_num + _sup_node_num * _sup_node_num));
1356 int next_global_update_limit = global_update_skip;
1358 // Perform cost scaling phases
1360 BoolVector path_arc(_res_arc_num, false);
1361 int relabel_cnt = 0;
1362 int eps_phase_cnt = 0;
1363 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1364 1 : _epsilon / _alpha )
1368 // Price refinement heuristic
1369 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1370 if (priceRefinement()) continue;
1373 // Initialize current phase
1376 // Perform partial augment and relabel operations
1378 // Select an active node (FIFO selection)
1379 while (_active_nodes.size() > 0 &&
1380 _excess[_active_nodes.front()] <= 0) {
1381 _active_nodes.pop_front();
1383 if (_active_nodes.size() == 0) break;
1384 int start = _active_nodes.front();
1386 // Find an augmenting path from the start node
1388 while (int(path.size()) < max_length && _excess[tip] >= 0) {
1390 LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1391 LargeCost pi_tip = _pi[tip];
1392 int last_out = _first_out[tip+1];
1393 for (int a = _next_out[tip]; a != last_out; ++a) {
1394 if (_res_cap[a] > 0) {
1396 rc = _cost[a] + pi_tip - _pi[u];
1401 goto augment; // a cycle is found, stop path search
1407 else if (rc < min_red_cost) {
1415 int ra = _reverse[path.back()];
1417 std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1419 last_out = _next_out[tip];
1420 for (int a = _first_out[tip]; a != last_out; ++a) {
1421 if (_res_cap[a] > 0) {
1422 rc = _cost[a] + pi_tip - _pi[_target[a]];
1423 if (rc < min_red_cost) {
1428 _pi[tip] -= min_red_cost + _epsilon;
1429 _next_out[tip] = _first_out[tip];
1434 int pa = path.back();
1435 path_arc[pa] = false;
1443 // Augment along the found path (as much flow as possible)
1446 int pa, u, v = start;
1447 for (int i = 0; i != int(path.size()); ++i) {
1451 path_arc[pa] = false;
1452 delta = std::min(_res_cap[pa], _excess[u]);
1453 _res_cap[pa] -= delta;
1454 _res_cap[_reverse[pa]] += delta;
1455 _excess[u] -= delta;
1456 _excess[v] += delta;
1457 if (_excess[v] > 0 && _excess[v] <= delta) {
1458 _active_nodes.push_back(v);
1463 // Global update heuristic
1464 if (relabel_cnt >= next_global_update_limit) {
1466 next_global_update_limit += global_update_skip;
1474 /// Execute the algorithm performing push and relabel operations
1476 // Paramters for heuristics
1477 const int PRICE_REFINEMENT_LIMIT = 2;
1478 const double GLOBAL_UPDATE_FACTOR = 2.0;
1480 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1481 (_res_node_num + _sup_node_num * _sup_node_num));
1482 int next_global_update_limit = global_update_skip;
1484 // Perform cost scaling phases
1485 BoolVector hyper(_res_node_num, false);
1486 LargeCostVector hyper_cost(_res_node_num);
1487 int relabel_cnt = 0;
1488 int eps_phase_cnt = 0;
1489 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1490 1 : _epsilon / _alpha )
1494 // Price refinement heuristic
1495 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1496 if (priceRefinement()) continue;
1499 // Initialize current phase
1502 // Perform push and relabel operations
1503 while (_active_nodes.size() > 0) {
1504 LargeCost min_red_cost, rc, pi_n;
1506 int n, t, a, last_out = _res_arc_num;
1509 // Select an active node (FIFO selection)
1510 n = _active_nodes.front();
1511 last_out = _first_out[n+1];
1514 // Perform push operations if there are admissible arcs
1515 if (_excess[n] > 0) {
1516 for (a = _next_out[n]; a != last_out; ++a) {
1517 if (_res_cap[a] > 0 &&
1518 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1519 delta = std::min(_res_cap[a], _excess[n]);
1522 // Push-look-ahead heuristic
1523 Value ahead = -_excess[t];
1524 int last_out_t = _first_out[t+1];
1525 LargeCost pi_t = _pi[t];
1526 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1527 if (_res_cap[ta] > 0 &&
1528 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1529 ahead += _res_cap[ta];
1530 if (ahead >= delta) break;
1532 if (ahead < 0) ahead = 0;
1534 // Push flow along the arc
1535 if (ahead < delta && !hyper[t]) {
1536 _res_cap[a] -= ahead;
1537 _res_cap[_reverse[a]] += ahead;
1538 _excess[n] -= ahead;
1539 _excess[t] += ahead;
1540 _active_nodes.push_front(t);
1542 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1546 _res_cap[a] -= delta;
1547 _res_cap[_reverse[a]] += delta;
1548 _excess[n] -= delta;
1549 _excess[t] += delta;
1550 if (_excess[t] > 0 && _excess[t] <= delta)
1551 _active_nodes.push_back(t);
1554 if (_excess[n] == 0) {
1563 // Relabel the node if it is still active (or hyper)
1564 if (_excess[n] > 0 || hyper[n]) {
1565 min_red_cost = hyper[n] ? -hyper_cost[n] :
1566 std::numeric_limits<LargeCost>::max();
1567 for (int a = _first_out[n]; a != last_out; ++a) {
1568 if (_res_cap[a] > 0) {
1569 rc = _cost[a] + pi_n - _pi[_target[a]];
1570 if (rc < min_red_cost) {
1575 _pi[n] -= min_red_cost + _epsilon;
1576 _next_out[n] = _first_out[n];
1581 // Remove nodes that are not active nor hyper
1583 while ( _active_nodes.size() > 0 &&
1584 _excess[_active_nodes.front()] <= 0 &&
1585 !hyper[_active_nodes.front()] ) {
1586 _active_nodes.pop_front();
1589 // Global update heuristic
1590 if (relabel_cnt >= next_global_update_limit) {
1592 for (int u = 0; u != _res_node_num; ++u)
1594 next_global_update_limit += global_update_skip;
1600 }; //class CostScaling
1606 #endif //LEMON_COST_SCALING_H