1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
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,
95 /// \cite goldberg90approximation,
96 /// \cite goldberg97efficient, \cite bunnagel98efficient.
97 /// It is a highly efficient primal-dual solution method, which
98 /// can be viewed as the generalization of the \ref Preflow
99 /// "preflow push-relabel" algorithm for the maximum flow problem.
100 /// It is a polynomial algorithm, its running time complexity is
101 /// \f$O(n^2m\log(nK))\f$, where <i>K</i> denotes the maximum arc cost.
103 /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
104 /// implementations available in LEMON for solving this problem.
105 /// (For more information, see \ref min_cost_flow_algs "the module page".)
107 /// Most of the parameters of the problem (except for the digraph)
108 /// can be given using separate functions, and the algorithm can be
109 /// executed using the \ref run() function. If some parameters are not
110 /// specified, then default values will be used.
112 /// \tparam GR The digraph type the algorithm runs on.
113 /// \tparam V The number type used for flow amounts, capacity bounds
114 /// and supply values in the algorithm. By default, it is \c int.
115 /// \tparam C The number type used for costs and potentials in the
116 /// algorithm. By default, it is the same as \c V.
117 /// \tparam TR The traits class that defines various types used by the
118 /// algorithm. By default, it is \ref CostScalingDefaultTraits
119 /// "CostScalingDefaultTraits<GR, V, C>".
120 /// In most cases, this parameter should not be set directly,
121 /// consider to use the named template parameters instead.
123 /// \warning Both \c V and \c C must be signed number types.
124 /// \warning All input data (capacities, supply values, and costs) must
126 /// \warning This algorithm does not support negative costs for
127 /// arcs having infinite upper bound.
129 /// \note %CostScaling provides three different internal methods,
130 /// from which the most efficient one is used by default.
131 /// For more information, see \ref Method.
133 template <typename GR, typename V, typename C, typename TR>
135 template < typename GR, typename V = int, typename C = V,
136 typename TR = CostScalingDefaultTraits<GR, V, C> >
142 /// The type of the digraph
143 typedef typename TR::Digraph Digraph;
144 /// The type of the flow amounts, capacity bounds and supply values
145 typedef typename TR::Value Value;
146 /// The type of the arc costs
147 typedef typename TR::Cost Cost;
149 /// \brief The large cost type
151 /// The large cost type used for internal computations.
152 /// By default, it is \c long \c long if the \c Cost type is integer,
153 /// otherwise it is \c double.
154 typedef typename TR::LargeCost LargeCost;
156 /// \brief The \ref lemon::CostScalingDefaultTraits "traits class"
162 /// \brief Problem type constants for the \c run() function.
164 /// Enum type containing the problem type constants that can be
165 /// returned by the \ref run() function of the algorithm.
167 /// The problem has no feasible solution (flow).
169 /// The problem has optimal solution (i.e. it is feasible and
170 /// bounded), and the algorithm has found optimal flow and node
171 /// potentials (primal and dual solutions).
173 /// The digraph contains an arc of negative cost and infinite
174 /// upper bound. It means that the objective function is unbounded
175 /// on that arc, however, note that it could actually be bounded
176 /// over the feasible flows, but this algroithm cannot handle
181 /// \brief Constants for selecting the internal method.
183 /// Enum type containing constants for selecting the internal method
184 /// for the \ref run() function.
186 /// \ref CostScaling provides three internal methods that differ mainly
187 /// in their base operations, which are used in conjunction with the
188 /// relabel operation.
189 /// By default, the so called \ref PARTIAL_AUGMENT
190 /// "Partial Augment-Relabel" method is used, which turned out to be
191 /// the most efficient and the most robust on various test inputs.
192 /// However, the other methods can be selected using the \ref run()
193 /// function with the proper parameter.
195 /// Local push operations are used, i.e. flow is moved only on one
196 /// admissible arc at once.
198 /// Augment operations are used, i.e. flow is moved on admissible
199 /// paths from a node with excess to a node with deficit.
201 /// Partial augment operations are used, i.e. flow is moved on
202 /// admissible paths started from a node with excess, but the
203 /// lengths of these paths are limited. This method can be viewed
204 /// as a combined version of the previous two operations.
210 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
212 typedef std::vector<int> IntVector;
213 typedef std::vector<Value> ValueVector;
214 typedef std::vector<Cost> CostVector;
215 typedef std::vector<LargeCost> LargeCostVector;
216 typedef std::vector<char> BoolVector;
217 // Note: vector<char> is used instead of vector<bool>
218 // for efficiency reasons
222 template <typename KT, typename VT>
223 class StaticVectorMap {
228 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
230 const Value& operator[](const Key& key) const {
231 return _v[StaticDigraph::id(key)];
234 Value& operator[](const Key& key) {
235 return _v[StaticDigraph::id(key)];
238 void set(const Key& key, const Value& val) {
239 _v[StaticDigraph::id(key)] = val;
243 std::vector<Value>& _v;
246 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
250 // Data related to the underlying digraph
258 // Parameters of the problem
263 // Data structures for storing the digraph
267 IntVector _first_out;
279 ValueVector _res_cap;
280 LargeCostVector _cost;
284 std::deque<int> _active_nodes;
291 IntVector _bucket_next;
292 IntVector _bucket_prev;
298 /// \brief Constant for infinite upper bounds (capacities).
300 /// Constant for infinite upper bounds (capacities).
301 /// It is \c std::numeric_limits<Value>::infinity() if available,
302 /// \c std::numeric_limits<Value>::max() otherwise.
307 /// \name Named Template Parameters
310 template <typename T>
311 struct SetLargeCostTraits : public Traits {
315 /// \brief \ref named-templ-param "Named parameter" for setting
316 /// \c LargeCost type.
318 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
319 /// type, which is used for internal computations in the algorithm.
320 /// \c Cost must be convertible to \c LargeCost.
321 template <typename T>
323 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
324 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
335 /// \brief Constructor.
337 /// The constructor of the class.
339 /// \param graph The digraph the algorithm runs on.
340 CostScaling(const GR& graph) :
341 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
342 INF(std::numeric_limits<Value>::has_infinity ?
343 std::numeric_limits<Value>::infinity() :
344 std::numeric_limits<Value>::max())
346 // Check the number types
347 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
348 "The flow type of CostScaling must be signed");
349 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
350 "The cost type of CostScaling must be signed");
352 // Reset data structures
357 /// The parameters of the algorithm can be specified using these
362 /// \brief Set the lower bounds on the arcs.
364 /// This function sets the lower bounds on the arcs.
365 /// If it is not used before calling \ref run(), the lower bounds
366 /// will be set to zero on all arcs.
368 /// \param map An arc map storing the lower bounds.
369 /// Its \c Value type must be convertible to the \c Value type
370 /// of the algorithm.
372 /// \return <tt>(*this)</tt>
373 template <typename LowerMap>
374 CostScaling& lowerMap(const LowerMap& map) {
376 for (ArcIt a(_graph); a != INVALID; ++a) {
377 _lower[_arc_idf[a]] = map[a];
378 _lower[_arc_idb[a]] = map[a];
383 /// \brief Set the upper bounds (capacities) on the arcs.
385 /// This function sets the upper bounds (capacities) on the arcs.
386 /// If it is not used before calling \ref run(), the upper bounds
387 /// will be set to \ref INF on all arcs (i.e. the flow value will be
388 /// unbounded from above).
390 /// \param map An arc map storing the upper bounds.
391 /// Its \c Value type must be convertible to the \c Value type
392 /// of the algorithm.
394 /// \return <tt>(*this)</tt>
395 template<typename UpperMap>
396 CostScaling& upperMap(const UpperMap& map) {
397 for (ArcIt a(_graph); a != INVALID; ++a) {
398 _upper[_arc_idf[a]] = map[a];
403 /// \brief Set the costs of the arcs.
405 /// This function sets the costs of the arcs.
406 /// If it is not used before calling \ref run(), the costs
407 /// will be set to \c 1 on all arcs.
409 /// \param map An arc map storing the costs.
410 /// Its \c Value type must be convertible to the \c Cost type
411 /// of the algorithm.
413 /// \return <tt>(*this)</tt>
414 template<typename CostMap>
415 CostScaling& costMap(const CostMap& map) {
416 for (ArcIt a(_graph); a != INVALID; ++a) {
417 _scost[_arc_idf[a]] = map[a];
418 _scost[_arc_idb[a]] = -map[a];
423 /// \brief Set the supply values of the nodes.
425 /// This function sets the supply values of the nodes.
426 /// If neither this function nor \ref stSupply() is used before
427 /// calling \ref run(), the supply of each node will be set to zero.
429 /// \param map A node map storing the supply values.
430 /// Its \c Value type must be convertible to the \c Value type
431 /// of the algorithm.
433 /// \return <tt>(*this)</tt>
434 template<typename SupplyMap>
435 CostScaling& supplyMap(const SupplyMap& map) {
436 for (NodeIt n(_graph); n != INVALID; ++n) {
437 _supply[_node_id[n]] = map[n];
442 /// \brief Set single source and target nodes and a supply value.
444 /// This function sets a single source node and a single target node
445 /// and the required flow value.
446 /// If neither this function nor \ref supplyMap() is used before
447 /// calling \ref run(), the supply of each node will be set to zero.
449 /// Using this function has the same effect as using \ref supplyMap()
450 /// with a map in which \c k is assigned to \c s, \c -k is
451 /// assigned to \c t and all other nodes have zero supply value.
453 /// \param s The source node.
454 /// \param t The target node.
455 /// \param k The required amount of flow from node \c s to node \c t
456 /// (i.e. the supply of \c s and the demand of \c t).
458 /// \return <tt>(*this)</tt>
459 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
460 for (int i = 0; i != _res_node_num; ++i) {
463 _supply[_node_id[s]] = k;
464 _supply[_node_id[t]] = -k;
470 /// \name Execution control
471 /// The algorithm can be executed using \ref run().
475 /// \brief Run the algorithm.
477 /// This function runs the algorithm.
478 /// The paramters can be specified using functions \ref lowerMap(),
479 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
482 /// CostScaling<ListDigraph> cs(graph);
483 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
484 /// .supplyMap(sup).run();
487 /// This function can be called more than once. All the given parameters
488 /// are kept for the next call, unless \ref resetParams() or \ref reset()
489 /// is used, thus only the modified parameters have to be set again.
490 /// If the underlying digraph was also modified after the construction
491 /// of the class (or the last \ref reset() call), then the \ref reset()
492 /// function must be called.
494 /// \param method The internal method that will be used in the
495 /// algorithm. For more information, see \ref Method.
496 /// \param factor The cost scaling factor. It must be at least two.
498 /// \return \c INFEASIBLE if no feasible flow exists,
499 /// \n \c OPTIMAL if the problem has optimal solution
500 /// (i.e. it is feasible and bounded), and the algorithm has found
501 /// optimal flow and node potentials (primal and dual solutions),
502 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
503 /// and infinite upper bound. It means that the objective function
504 /// is unbounded on that arc, however, note that it could actually be
505 /// bounded over the feasible flows, but this algroithm cannot handle
508 /// \see ProblemType, Method
509 /// \see resetParams(), reset()
510 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
511 LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
513 ProblemType pt = init();
514 if (pt != OPTIMAL) return pt;
519 /// \brief Reset all the parameters that have been given before.
521 /// This function resets all the paramaters that have been given
522 /// before using functions \ref lowerMap(), \ref upperMap(),
523 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
525 /// It is useful for multiple \ref run() calls. Basically, all the given
526 /// parameters are kept for the next \ref run() call, unless
527 /// \ref resetParams() or \ref reset() is used.
528 /// If the underlying digraph was also modified after the construction
529 /// of the class or the last \ref reset() call, then the \ref reset()
530 /// function must be used, otherwise \ref resetParams() is sufficient.
534 /// CostScaling<ListDigraph> cs(graph);
537 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
538 /// .supplyMap(sup).run();
540 /// // Run again with modified cost map (resetParams() is not called,
541 /// // so only the cost map have to be set again)
543 /// cs.costMap(cost).run();
545 /// // Run again from scratch using resetParams()
546 /// // (the lower bounds will be set to zero on all arcs)
547 /// cs.resetParams();
548 /// cs.upperMap(capacity).costMap(cost)
549 /// .supplyMap(sup).run();
552 /// \return <tt>(*this)</tt>
554 /// \see reset(), run()
555 CostScaling& resetParams() {
556 for (int i = 0; i != _res_node_num; ++i) {
559 int limit = _first_out[_root];
560 for (int j = 0; j != limit; ++j) {
563 _scost[j] = _forward[j] ? 1 : -1;
565 for (int j = limit; j != _res_arc_num; ++j) {
569 _scost[_reverse[j]] = 0;
575 /// \brief Reset the internal data structures and all the parameters
576 /// that have been given before.
578 /// This function resets the internal data structures and all the
579 /// paramaters that have been given before using functions \ref lowerMap(),
580 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
582 /// It is useful for multiple \ref run() calls. By default, all the given
583 /// parameters are kept for the next \ref run() call, unless
584 /// \ref resetParams() or \ref reset() is used.
585 /// If the underlying digraph was also modified after the construction
586 /// of the class or the last \ref reset() call, then the \ref reset()
587 /// function must be used, otherwise \ref resetParams() is sufficient.
589 /// See \ref resetParams() for examples.
591 /// \return <tt>(*this)</tt>
593 /// \see resetParams(), run()
594 CostScaling& reset() {
596 _node_num = countNodes(_graph);
597 _arc_num = countArcs(_graph);
598 _res_node_num = _node_num + 1;
599 _res_arc_num = 2 * (_arc_num + _node_num);
602 _first_out.resize(_res_node_num + 1);
603 _forward.resize(_res_arc_num);
604 _source.resize(_res_arc_num);
605 _target.resize(_res_arc_num);
606 _reverse.resize(_res_arc_num);
608 _lower.resize(_res_arc_num);
609 _upper.resize(_res_arc_num);
610 _scost.resize(_res_arc_num);
611 _supply.resize(_res_node_num);
613 _res_cap.resize(_res_arc_num);
614 _cost.resize(_res_arc_num);
615 _pi.resize(_res_node_num);
616 _excess.resize(_res_node_num);
617 _next_out.resize(_res_node_num);
620 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
621 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
625 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
627 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
631 _target[j] = _node_id[_graph.runningNode(a)];
633 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
637 _target[j] = _node_id[_graph.runningNode(a)];
650 _first_out[_res_node_num] = k;
651 for (ArcIt a(_graph); a != INVALID; ++a) {
652 int fi = _arc_idf[a];
653 int bi = _arc_idb[a];
665 /// \name Query Functions
666 /// The results of the algorithm can be obtained using these
668 /// The \ref run() function must be called before using them.
672 /// \brief Return the total cost of the found flow.
674 /// This function returns the total cost of the found flow.
675 /// Its complexity is O(m).
677 /// \note The return type of the function can be specified as a
678 /// template parameter. For example,
680 /// cs.totalCost<double>();
682 /// It is useful if the total cost cannot be stored in the \c Cost
683 /// type of the algorithm, which is the default return type of the
686 /// \pre \ref run() must be called before using this function.
687 template <typename Number>
688 Number totalCost() const {
690 for (ArcIt a(_graph); a != INVALID; ++a) {
692 c += static_cast<Number>(_res_cap[i]) *
693 (-static_cast<Number>(_scost[i]));
699 Cost totalCost() const {
700 return totalCost<Cost>();
704 /// \brief Return the flow on the given arc.
706 /// This function returns the flow on the given arc.
708 /// \pre \ref run() must be called before using this function.
709 Value flow(const Arc& a) const {
710 return _res_cap[_arc_idb[a]];
713 /// \brief Copy the flow values (the primal solution) into the
716 /// This function copies the flow value on each arc into the given
717 /// map. The \c Value type of the algorithm must be convertible to
718 /// the \c Value type of the map.
720 /// \pre \ref run() must be called before using this function.
721 template <typename FlowMap>
722 void flowMap(FlowMap &map) const {
723 for (ArcIt a(_graph); a != INVALID; ++a) {
724 map.set(a, _res_cap[_arc_idb[a]]);
728 /// \brief Return the potential (dual value) of the given node.
730 /// This function returns the potential (dual value) of the
733 /// \pre \ref run() must be called before using this function.
734 Cost potential(const Node& n) const {
735 return static_cast<Cost>(_pi[_node_id[n]]);
738 /// \brief Copy the potential values (the dual solution) into the
741 /// This function copies the potential (dual value) of each node
742 /// into the given map.
743 /// The \c Cost type of the algorithm must be convertible to the
744 /// \c Value type of the map.
746 /// \pre \ref run() must be called before using this function.
747 template <typename PotentialMap>
748 void potentialMap(PotentialMap &map) const {
749 for (NodeIt n(_graph); n != INVALID; ++n) {
750 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
758 // Initialize the algorithm
760 if (_res_node_num <= 1) return INFEASIBLE;
762 // Check the sum of supply values
764 for (int i = 0; i != _root; ++i) {
765 _sum_supply += _supply[i];
767 if (_sum_supply > 0) return INFEASIBLE;
769 // Check lower and upper bounds
770 LEMON_DEBUG(checkBoundMaps(),
771 "Upper bounds must be greater or equal to the lower bounds");
774 // Initialize vectors
775 for (int i = 0; i != _res_node_num; ++i) {
777 _excess[i] = _supply[i];
780 // Remove infinite upper bounds and check negative arcs
781 const Value MAX = std::numeric_limits<Value>::max();
784 for (int i = 0; i != _root; ++i) {
785 last_out = _first_out[i+1];
786 for (int j = _first_out[i]; j != last_out; ++j) {
788 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
789 if (c >= MAX) return UNBOUNDED;
791 _excess[_target[j]] += c;
796 for (int i = 0; i != _root; ++i) {
797 last_out = _first_out[i+1];
798 for (int j = _first_out[i]; j != last_out; ++j) {
799 if (_forward[j] && _scost[j] < 0) {
801 if (c >= MAX) return UNBOUNDED;
803 _excess[_target[j]] += c;
808 Value ex, max_cap = 0;
809 for (int i = 0; i != _res_node_num; ++i) {
812 if (ex < 0) max_cap -= ex;
814 for (int j = 0; j != _res_arc_num; ++j) {
815 if (_upper[j] >= MAX) _upper[j] = max_cap;
818 // Initialize the large cost vector and the epsilon parameter
821 for (int i = 0; i != _root; ++i) {
822 last_out = _first_out[i+1];
823 for (int j = _first_out[i]; j != last_out; ++j) {
824 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
826 if (lc > _epsilon) _epsilon = lc;
831 // Initialize maps for Circulation and remove non-zero lower bounds
832 ConstMap<Arc, Value> low(0);
833 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
834 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
835 ValueArcMap cap(_graph), flow(_graph);
836 ValueNodeMap sup(_graph);
837 for (NodeIt n(_graph); n != INVALID; ++n) {
838 sup[n] = _supply[_node_id[n]];
841 for (ArcIt a(_graph); a != INVALID; ++a) {
844 cap[a] = _upper[j] - c;
845 sup[_graph.source(a)] -= c;
846 sup[_graph.target(a)] += c;
849 for (ArcIt a(_graph); a != INVALID; ++a) {
850 cap[a] = _upper[_arc_idf[a]];
855 for (NodeIt n(_graph); n != INVALID; ++n) {
856 if (sup[n] > 0) ++_sup_node_num;
859 // Find a feasible flow using Circulation
860 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
861 circ(_graph, low, cap, sup);
862 if (!circ.flowMap(flow).run()) return INFEASIBLE;
864 // Set residual capacities and handle GEQ supply type
865 if (_sum_supply < 0) {
866 for (ArcIt a(_graph); a != INVALID; ++a) {
868 _res_cap[_arc_idf[a]] = cap[a] - fa;
869 _res_cap[_arc_idb[a]] = fa;
870 sup[_graph.source(a)] -= fa;
871 sup[_graph.target(a)] += fa;
873 for (NodeIt n(_graph); n != INVALID; ++n) {
874 _excess[_node_id[n]] = sup[n];
876 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
878 int ra = _reverse[a];
879 _res_cap[a] = -_sum_supply + 1;
880 _res_cap[ra] = -_excess[u];
886 for (ArcIt a(_graph); a != INVALID; ++a) {
888 _res_cap[_arc_idf[a]] = cap[a] - fa;
889 _res_cap[_arc_idb[a]] = fa;
891 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
892 int ra = _reverse[a];
900 // Initialize data structures for buckets
901 _max_rank = _alpha * _res_node_num;
902 _buckets.resize(_max_rank);
903 _bucket_next.resize(_res_node_num + 1);
904 _bucket_prev.resize(_res_node_num + 1);
905 _rank.resize(_res_node_num + 1);
910 // Check if the upper bound is greater or equal to the lower bound
912 bool checkBoundMaps() {
913 for (int j = 0; j != _res_arc_num; ++j) {
914 if (_upper[j] < _lower[j]) return false;
919 // Execute the algorithm and transform the results
920 void start(Method method) {
921 const int MAX_PARTIAL_PATH_LENGTH = 4;
928 startAugment(_res_node_num - 1);
930 case PARTIAL_AUGMENT:
931 startAugment(MAX_PARTIAL_PATH_LENGTH);
935 // Compute node potentials (dual solution)
936 for (int i = 0; i != _res_node_num; ++i) {
937 _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
940 for (int i = 0; optimal && i != _res_node_num; ++i) {
941 LargeCost pi_i = _pi[i];
942 int last_out = _first_out[i+1];
943 for (int j = _first_out[i]; j != last_out; ++j) {
944 if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
952 // Compute node potentials for the original costs with BellmanFord
953 // (if it is necessary)
954 typedef std::pair<int, int> IntPair;
956 std::vector<IntPair> arc_vec;
957 std::vector<LargeCost> cost_vec;
958 LargeCostArcMap cost_map(cost_vec);
962 for (int j = 0; j != _res_arc_num; ++j) {
963 if (_res_cap[j] > 0) {
964 int u = _source[j], v = _target[j];
965 arc_vec.push_back(IntPair(u, v));
966 cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
969 sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
971 typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
976 for (int i = 0; i != _res_node_num; ++i) {
977 _pi[i] += bf.dist(sgr.node(i));
981 // Shift potentials to meet the requirements of the GEQ type
982 // optimality conditions
983 LargeCost max_pot = _pi[_root];
984 for (int i = 0; i != _res_node_num; ++i) {
985 if (_pi[i] > max_pot) max_pot = _pi[i];
988 for (int i = 0; i != _res_node_num; ++i) {
993 // Handle non-zero lower bounds
995 int limit = _first_out[_root];
996 for (int j = 0; j != limit; ++j) {
997 if (!_forward[j]) _res_cap[j] += _lower[j];
1002 // Initialize a cost scaling phase
1004 // Saturate arcs not satisfying the optimality condition
1005 for (int u = 0; u != _res_node_num; ++u) {
1006 int last_out = _first_out[u+1];
1007 LargeCost pi_u = _pi[u];
1008 for (int a = _first_out[u]; a != last_out; ++a) {
1009 Value delta = _res_cap[a];
1012 if (_cost[a] + pi_u - _pi[v] < 0) {
1013 _excess[u] -= delta;
1014 _excess[v] += delta;
1016 _res_cap[_reverse[a]] += delta;
1022 // Find active nodes (i.e. nodes with positive excess)
1023 for (int u = 0; u != _res_node_num; ++u) {
1024 if (_excess[u] > 0) _active_nodes.push_back(u);
1027 // Initialize the next arcs
1028 for (int u = 0; u != _res_node_num; ++u) {
1029 _next_out[u] = _first_out[u];
1033 // Price (potential) refinement heuristic
1034 bool priceRefinement() {
1036 // Stack for stroing the topological order
1037 IntVector stack(_res_node_num);
1041 while (topologicalSort(stack, stack_top)) {
1043 // Compute node ranks in the acyclic admissible network and
1044 // store the nodes in buckets
1045 for (int i = 0; i != _res_node_num; ++i) {
1048 const int bucket_end = _root + 1;
1049 for (int r = 0; r != _max_rank; ++r) {
1050 _buckets[r] = bucket_end;
1053 for ( ; stack_top >= 0; --stack_top) {
1054 int u = stack[stack_top], v;
1055 int rank_u = _rank[u];
1057 LargeCost rc, pi_u = _pi[u];
1058 int last_out = _first_out[u+1];
1059 for (int a = _first_out[u]; a != last_out; ++a) {
1060 if (_res_cap[a] > 0) {
1062 rc = _cost[a] + pi_u - _pi[v];
1064 LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1065 if (nrc < LargeCost(_max_rank)) {
1066 int new_rank_v = rank_u + static_cast<int>(nrc);
1067 if (new_rank_v > _rank[v]) {
1068 _rank[v] = new_rank_v;
1076 top_rank = std::max(top_rank, rank_u);
1077 int bfirst = _buckets[rank_u];
1078 _bucket_next[u] = bfirst;
1079 _bucket_prev[bfirst] = u;
1080 _buckets[rank_u] = u;
1084 // Check if the current flow is epsilon-optimal
1085 if (top_rank == 0) {
1089 // Process buckets in top-down order
1090 for (int rank = top_rank; rank > 0; --rank) {
1091 while (_buckets[rank] != bucket_end) {
1092 // Remove the first node from the current bucket
1093 int u = _buckets[rank];
1094 _buckets[rank] = _bucket_next[u];
1096 // Search the outgoing arcs of u
1097 LargeCost rc, pi_u = _pi[u];
1098 int last_out = _first_out[u+1];
1099 int v, old_rank_v, new_rank_v;
1100 for (int a = _first_out[u]; a != last_out; ++a) {
1101 if (_res_cap[a] > 0) {
1103 old_rank_v = _rank[v];
1105 if (old_rank_v < rank) {
1107 // Compute the new rank of node v
1108 rc = _cost[a] + pi_u - _pi[v];
1112 LargeCost nrc = rc / _epsilon;
1114 if (nrc < LargeCost(_max_rank)) {
1115 new_rank_v = rank - 1 - static_cast<int>(nrc);
1119 // Change the rank of node v
1120 if (new_rank_v > old_rank_v) {
1121 _rank[v] = new_rank_v;
1123 // Remove v from its old bucket
1124 if (old_rank_v > 0) {
1125 if (_buckets[old_rank_v] == v) {
1126 _buckets[old_rank_v] = _bucket_next[v];
1128 int pv = _bucket_prev[v], nv = _bucket_next[v];
1129 _bucket_next[pv] = nv;
1130 _bucket_prev[nv] = pv;
1134 // Insert v into its new bucket
1135 int nv = _buckets[new_rank_v];
1136 _bucket_next[v] = nv;
1137 _bucket_prev[nv] = v;
1138 _buckets[new_rank_v] = v;
1144 // Refine potential of node u
1145 _pi[u] -= rank * _epsilon;
1154 // Find and cancel cycles in the admissible network and
1155 // determine topological order using DFS
1156 bool topologicalSort(IntVector &stack, int &stack_top) {
1157 const int MAX_CYCLE_CANCEL = 1;
1159 BoolVector reached(_res_node_num, false);
1160 BoolVector processed(_res_node_num, false);
1161 IntVector pred(_res_node_num);
1162 for (int i = 0; i != _res_node_num; ++i) {
1163 _next_out[i] = _first_out[i];
1168 for (int start = 0; start != _res_node_num; ++start) {
1169 if (reached[start]) continue;
1171 // Start DFS search from this start node
1175 // Check the outgoing arcs of the current tip node
1176 reached[tip] = true;
1177 LargeCost pi_tip = _pi[tip];
1178 int a, last_out = _first_out[tip+1];
1179 for (a = _next_out[tip]; a != last_out; ++a) {
1180 if (_res_cap[a] > 0) {
1182 if (_cost[a] + pi_tip - _pi[v] < 0) {
1184 // A new node is reached
1190 last_out = _first_out[tip+1];
1193 else if (!processed[v]) {
1198 // Find the minimum residual capacity along the cycle
1199 Value d, delta = _res_cap[a];
1200 int u, delta_node = tip;
1201 for (u = tip; u != v; ) {
1203 d = _res_cap[_next_out[u]];
1210 // Augment along the cycle
1211 _res_cap[a] -= delta;
1212 _res_cap[_reverse[a]] += delta;
1213 for (u = tip; u != v; ) {
1215 int ca = _next_out[u];
1216 _res_cap[ca] -= delta;
1217 _res_cap[_reverse[ca]] += delta;
1220 // Check the maximum number of cycle canceling
1221 if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1225 // Roll back search to delta_node
1226 if (delta_node != tip) {
1227 for (u = tip; u != delta_node; u = pred[u]) {
1231 a = _next_out[tip] + 1;
1232 last_out = _first_out[tip+1];
1240 // Step back to the previous node
1241 if (a == last_out) {
1242 processed[tip] = true;
1243 stack[++stack_top] = tip;
1246 // Finish DFS from the current start node
1255 return (cycle_cnt == 0);
1258 // Global potential update heuristic
1259 void globalUpdate() {
1260 const int bucket_end = _root + 1;
1262 // Initialize buckets
1263 for (int r = 0; r != _max_rank; ++r) {
1264 _buckets[r] = bucket_end;
1266 Value total_excess = 0;
1267 int b0 = bucket_end;
1268 for (int i = 0; i != _res_node_num; ++i) {
1269 if (_excess[i] < 0) {
1271 _bucket_next[i] = b0;
1272 _bucket_prev[b0] = i;
1275 total_excess += _excess[i];
1276 _rank[i] = _max_rank;
1279 if (total_excess == 0) return;
1282 // Search the buckets
1284 for ( ; r != _max_rank; ++r) {
1285 while (_buckets[r] != bucket_end) {
1286 // Remove the first node from the current bucket
1287 int u = _buckets[r];
1288 _buckets[r] = _bucket_next[u];
1290 // Search the incoming arcs of u
1291 LargeCost pi_u = _pi[u];
1292 int last_out = _first_out[u+1];
1293 for (int a = _first_out[u]; a != last_out; ++a) {
1294 int ra = _reverse[a];
1295 if (_res_cap[ra] > 0) {
1296 int v = _source[ra];
1297 int old_rank_v = _rank[v];
1298 if (r < old_rank_v) {
1299 // Compute the new rank of v
1300 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1301 int new_rank_v = old_rank_v;
1302 if (nrc < LargeCost(_max_rank)) {
1303 new_rank_v = r + 1 + static_cast<int>(nrc);
1306 // Change the rank of v
1307 if (new_rank_v < old_rank_v) {
1308 _rank[v] = new_rank_v;
1309 _next_out[v] = _first_out[v];
1311 // Remove v from its old bucket
1312 if (old_rank_v < _max_rank) {
1313 if (_buckets[old_rank_v] == v) {
1314 _buckets[old_rank_v] = _bucket_next[v];
1316 int pv = _bucket_prev[v], nv = _bucket_next[v];
1317 _bucket_next[pv] = nv;
1318 _bucket_prev[nv] = pv;
1322 // Insert v into its new bucket
1323 int nv = _buckets[new_rank_v];
1324 _bucket_next[v] = nv;
1325 _bucket_prev[nv] = v;
1326 _buckets[new_rank_v] = v;
1332 // Finish search if there are no more active nodes
1333 if (_excess[u] > 0) {
1334 total_excess -= _excess[u];
1335 if (total_excess <= 0) break;
1338 if (total_excess <= 0) break;
1342 for (int u = 0; u != _res_node_num; ++u) {
1343 int k = std::min(_rank[u], r);
1345 _pi[u] -= _epsilon * k;
1346 _next_out[u] = _first_out[u];
1351 /// Execute the algorithm performing augment and relabel operations
1352 void startAugment(int max_length) {
1353 // Paramters for heuristics
1354 const int PRICE_REFINEMENT_LIMIT = 2;
1355 const double GLOBAL_UPDATE_FACTOR = 1.0;
1356 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1357 (_res_node_num + _sup_node_num * _sup_node_num));
1358 int next_global_update_limit = global_update_skip;
1360 // Perform cost scaling phases
1362 BoolVector path_arc(_res_arc_num, false);
1363 int relabel_cnt = 0;
1364 int eps_phase_cnt = 0;
1365 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1366 1 : _epsilon / _alpha )
1370 // Price refinement heuristic
1371 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1372 if (priceRefinement()) continue;
1375 // Initialize current phase
1378 // Perform partial augment and relabel operations
1380 // Select an active node (FIFO selection)
1381 while (_active_nodes.size() > 0 &&
1382 _excess[_active_nodes.front()] <= 0) {
1383 _active_nodes.pop_front();
1385 if (_active_nodes.size() == 0) break;
1386 int start = _active_nodes.front();
1388 // Find an augmenting path from the start node
1390 while (int(path.size()) < max_length && _excess[tip] >= 0) {
1392 LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1393 LargeCost pi_tip = _pi[tip];
1394 int last_out = _first_out[tip+1];
1395 for (int a = _next_out[tip]; a != last_out; ++a) {
1396 if (_res_cap[a] > 0) {
1398 rc = _cost[a] + pi_tip - _pi[u];
1403 goto augment; // a cycle is found, stop path search
1409 else if (rc < min_red_cost) {
1417 int ra = _reverse[path.back()];
1419 std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1421 last_out = _next_out[tip];
1422 for (int a = _first_out[tip]; a != last_out; ++a) {
1423 if (_res_cap[a] > 0) {
1424 rc = _cost[a] + pi_tip - _pi[_target[a]];
1425 if (rc < min_red_cost) {
1430 _pi[tip] -= min_red_cost + _epsilon;
1431 _next_out[tip] = _first_out[tip];
1436 int pa = path.back();
1437 path_arc[pa] = false;
1445 // Augment along the found path (as much flow as possible)
1448 int pa, u, v = start;
1449 for (int i = 0; i != int(path.size()); ++i) {
1453 path_arc[pa] = false;
1454 delta = std::min(_res_cap[pa], _excess[u]);
1455 _res_cap[pa] -= delta;
1456 _res_cap[_reverse[pa]] += delta;
1457 _excess[u] -= delta;
1458 _excess[v] += delta;
1459 if (_excess[v] > 0 && _excess[v] <= delta) {
1460 _active_nodes.push_back(v);
1465 // Global update heuristic
1466 if (relabel_cnt >= next_global_update_limit) {
1468 next_global_update_limit += global_update_skip;
1476 /// Execute the algorithm performing push and relabel operations
1478 // Paramters for heuristics
1479 const int PRICE_REFINEMENT_LIMIT = 2;
1480 const double GLOBAL_UPDATE_FACTOR = 2.0;
1482 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1483 (_res_node_num + _sup_node_num * _sup_node_num));
1484 int next_global_update_limit = global_update_skip;
1486 // Perform cost scaling phases
1487 BoolVector hyper(_res_node_num, false);
1488 LargeCostVector hyper_cost(_res_node_num);
1489 int relabel_cnt = 0;
1490 int eps_phase_cnt = 0;
1491 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1492 1 : _epsilon / _alpha )
1496 // Price refinement heuristic
1497 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1498 if (priceRefinement()) continue;
1501 // Initialize current phase
1504 // Perform push and relabel operations
1505 while (_active_nodes.size() > 0) {
1506 LargeCost min_red_cost, rc, pi_n;
1508 int n, t, a, last_out = _res_arc_num;
1511 // Select an active node (FIFO selection)
1512 n = _active_nodes.front();
1513 last_out = _first_out[n+1];
1516 // Perform push operations if there are admissible arcs
1517 if (_excess[n] > 0) {
1518 for (a = _next_out[n]; a != last_out; ++a) {
1519 if (_res_cap[a] > 0 &&
1520 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1521 delta = std::min(_res_cap[a], _excess[n]);
1524 // Push-look-ahead heuristic
1525 Value ahead = -_excess[t];
1526 int last_out_t = _first_out[t+1];
1527 LargeCost pi_t = _pi[t];
1528 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1529 if (_res_cap[ta] > 0 &&
1530 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1531 ahead += _res_cap[ta];
1532 if (ahead >= delta) break;
1534 if (ahead < 0) ahead = 0;
1536 // Push flow along the arc
1537 if (ahead < delta && !hyper[t]) {
1538 _res_cap[a] -= ahead;
1539 _res_cap[_reverse[a]] += ahead;
1540 _excess[n] -= ahead;
1541 _excess[t] += ahead;
1542 _active_nodes.push_front(t);
1544 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1548 _res_cap[a] -= delta;
1549 _res_cap[_reverse[a]] += delta;
1550 _excess[n] -= delta;
1551 _excess[t] += delta;
1552 if (_excess[t] > 0 && _excess[t] <= delta)
1553 _active_nodes.push_back(t);
1556 if (_excess[n] == 0) {
1565 // Relabel the node if it is still active (or hyper)
1566 if (_excess[n] > 0 || hyper[n]) {
1567 min_red_cost = hyper[n] ? -hyper_cost[n] :
1568 std::numeric_limits<LargeCost>::max();
1569 for (int a = _first_out[n]; a != last_out; ++a) {
1570 if (_res_cap[a] > 0) {
1571 rc = _cost[a] + pi_n - _pi[_target[a]];
1572 if (rc < min_red_cost) {
1577 _pi[n] -= min_red_cost + _epsilon;
1578 _next_out[n] = _first_out[n];
1583 // Remove nodes that are not active nor hyper
1585 while ( _active_nodes.size() > 0 &&
1586 _excess[_active_nodes.front()] <= 0 &&
1587 !hyper[_active_nodes.front()] ) {
1588 _active_nodes.pop_front();
1591 // Global update heuristic
1592 if (relabel_cnt >= next_global_update_limit) {
1594 for (int u = 0; u != _res_node_num; ++u)
1596 next_global_update_limit += global_update_skip;
1602 }; //class CostScaling
1608 #endif //LEMON_COST_SCALING_H