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];
382 /// \brief Set the upper bounds (capacities) on the arcs.
384 /// This function sets the upper bounds (capacities) on the arcs.
385 /// If it is not used before calling \ref run(), the upper bounds
386 /// will be set to \ref INF on all arcs (i.e. the flow value will be
387 /// unbounded from above).
389 /// \param map An arc map storing the upper bounds.
390 /// Its \c Value type must be convertible to the \c Value type
391 /// of the algorithm.
393 /// \return <tt>(*this)</tt>
394 template<typename UpperMap>
395 CostScaling& upperMap(const UpperMap& map) {
396 for (ArcIt a(_graph); a != INVALID; ++a) {
397 _upper[_arc_idf[a]] = map[a];
402 /// \brief Set the costs of the arcs.
404 /// This function sets the costs of the arcs.
405 /// If it is not used before calling \ref run(), the costs
406 /// will be set to \c 1 on all arcs.
408 /// \param map An arc map storing the costs.
409 /// Its \c Value type must be convertible to the \c Cost type
410 /// of the algorithm.
412 /// \return <tt>(*this)</tt>
413 template<typename CostMap>
414 CostScaling& costMap(const CostMap& map) {
415 for (ArcIt a(_graph); a != INVALID; ++a) {
416 _scost[_arc_idf[a]] = map[a];
417 _scost[_arc_idb[a]] = -map[a];
422 /// \brief Set the supply values of the nodes.
424 /// This function sets the supply values of the nodes.
425 /// If neither this function nor \ref stSupply() is used before
426 /// calling \ref run(), the supply of each node will be set to zero.
428 /// \param map A node map storing the supply values.
429 /// Its \c Value type must be convertible to the \c Value type
430 /// of the algorithm.
432 /// \return <tt>(*this)</tt>
433 template<typename SupplyMap>
434 CostScaling& supplyMap(const SupplyMap& map) {
435 for (NodeIt n(_graph); n != INVALID; ++n) {
436 _supply[_node_id[n]] = map[n];
441 /// \brief Set single source and target nodes and a supply value.
443 /// This function sets a single source node and a single target node
444 /// and the required flow value.
445 /// If neither this function nor \ref supplyMap() is used before
446 /// calling \ref run(), the supply of each node will be set to zero.
448 /// Using this function has the same effect as using \ref supplyMap()
449 /// with a map in which \c k is assigned to \c s, \c -k is
450 /// assigned to \c t and all other nodes have zero supply value.
452 /// \param s The source node.
453 /// \param t The target node.
454 /// \param k The required amount of flow from node \c s to node \c t
455 /// (i.e. the supply of \c s and the demand of \c t).
457 /// \return <tt>(*this)</tt>
458 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
459 for (int i = 0; i != _res_node_num; ++i) {
462 _supply[_node_id[s]] = k;
463 _supply[_node_id[t]] = -k;
469 /// \name Execution control
470 /// The algorithm can be executed using \ref run().
474 /// \brief Run the algorithm.
476 /// This function runs the algorithm.
477 /// The paramters can be specified using functions \ref lowerMap(),
478 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
481 /// CostScaling<ListDigraph> cs(graph);
482 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
483 /// .supplyMap(sup).run();
486 /// This function can be called more than once. All the given parameters
487 /// are kept for the next call, unless \ref resetParams() or \ref reset()
488 /// is used, thus only the modified parameters have to be set again.
489 /// If the underlying digraph was also modified after the construction
490 /// of the class (or the last \ref reset() call), then the \ref reset()
491 /// function must be called.
493 /// \param method The internal method that will be used in the
494 /// algorithm. For more information, see \ref Method.
495 /// \param factor The cost scaling factor. It must be at least two.
497 /// \return \c INFEASIBLE if no feasible flow exists,
498 /// \n \c OPTIMAL if the problem has optimal solution
499 /// (i.e. it is feasible and bounded), and the algorithm has found
500 /// optimal flow and node potentials (primal and dual solutions),
501 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
502 /// and infinite upper bound. It means that the objective function
503 /// is unbounded on that arc, however, note that it could actually be
504 /// bounded over the feasible flows, but this algroithm cannot handle
507 /// \see ProblemType, Method
508 /// \see resetParams(), reset()
509 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
510 LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
512 ProblemType pt = init();
513 if (pt != OPTIMAL) return pt;
518 /// \brief Reset all the parameters that have been given before.
520 /// This function resets all the paramaters that have been given
521 /// before using functions \ref lowerMap(), \ref upperMap(),
522 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
524 /// It is useful for multiple \ref run() calls. Basically, all the given
525 /// parameters are kept for the next \ref run() call, unless
526 /// \ref resetParams() or \ref reset() is used.
527 /// If the underlying digraph was also modified after the construction
528 /// of the class or the last \ref reset() call, then the \ref reset()
529 /// function must be used, otherwise \ref resetParams() is sufficient.
533 /// CostScaling<ListDigraph> cs(graph);
536 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
537 /// .supplyMap(sup).run();
539 /// // Run again with modified cost map (resetParams() is not called,
540 /// // so only the cost map have to be set again)
542 /// cs.costMap(cost).run();
544 /// // Run again from scratch using resetParams()
545 /// // (the lower bounds will be set to zero on all arcs)
546 /// cs.resetParams();
547 /// cs.upperMap(capacity).costMap(cost)
548 /// .supplyMap(sup).run();
551 /// \return <tt>(*this)</tt>
553 /// \see reset(), run()
554 CostScaling& resetParams() {
555 for (int i = 0; i != _res_node_num; ++i) {
558 int limit = _first_out[_root];
559 for (int j = 0; j != limit; ++j) {
562 _scost[j] = _forward[j] ? 1 : -1;
564 for (int j = limit; j != _res_arc_num; ++j) {
568 _scost[_reverse[j]] = 0;
574 /// \brief Reset the internal data structures and all the parameters
575 /// that have been given before.
577 /// This function resets the internal data structures and all the
578 /// paramaters that have been given before using functions \ref lowerMap(),
579 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
581 /// It is useful for multiple \ref run() calls. By default, all the given
582 /// parameters are kept for the next \ref run() call, unless
583 /// \ref resetParams() or \ref reset() is used.
584 /// If the underlying digraph was also modified after the construction
585 /// of the class or the last \ref reset() call, then the \ref reset()
586 /// function must be used, otherwise \ref resetParams() is sufficient.
588 /// See \ref resetParams() for examples.
590 /// \return <tt>(*this)</tt>
592 /// \see resetParams(), run()
593 CostScaling& reset() {
595 _node_num = countNodes(_graph);
596 _arc_num = countArcs(_graph);
597 _res_node_num = _node_num + 1;
598 _res_arc_num = 2 * (_arc_num + _node_num);
601 _first_out.resize(_res_node_num + 1);
602 _forward.resize(_res_arc_num);
603 _source.resize(_res_arc_num);
604 _target.resize(_res_arc_num);
605 _reverse.resize(_res_arc_num);
607 _lower.resize(_res_arc_num);
608 _upper.resize(_res_arc_num);
609 _scost.resize(_res_arc_num);
610 _supply.resize(_res_node_num);
612 _res_cap.resize(_res_arc_num);
613 _cost.resize(_res_arc_num);
614 _pi.resize(_res_node_num);
615 _excess.resize(_res_node_num);
616 _next_out.resize(_res_node_num);
619 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
620 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
624 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
626 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
630 _target[j] = _node_id[_graph.runningNode(a)];
632 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
636 _target[j] = _node_id[_graph.runningNode(a)];
649 _first_out[_res_node_num] = k;
650 for (ArcIt a(_graph); a != INVALID; ++a) {
651 int fi = _arc_idf[a];
652 int bi = _arc_idb[a];
664 /// \name Query Functions
665 /// The results of the algorithm can be obtained using these
667 /// The \ref run() function must be called before using them.
671 /// \brief Return the total cost of the found flow.
673 /// This function returns the total cost of the found flow.
674 /// Its complexity is O(m).
676 /// \note The return type of the function can be specified as a
677 /// template parameter. For example,
679 /// cs.totalCost<double>();
681 /// It is useful if the total cost cannot be stored in the \c Cost
682 /// type of the algorithm, which is the default return type of the
685 /// \pre \ref run() must be called before using this function.
686 template <typename Number>
687 Number totalCost() const {
689 for (ArcIt a(_graph); a != INVALID; ++a) {
691 c += static_cast<Number>(_res_cap[i]) *
692 (-static_cast<Number>(_scost[i]));
698 Cost totalCost() const {
699 return totalCost<Cost>();
703 /// \brief Return the flow on the given arc.
705 /// This function returns the flow on the given arc.
707 /// \pre \ref run() must be called before using this function.
708 Value flow(const Arc& a) const {
709 return _res_cap[_arc_idb[a]];
712 /// \brief Copy the flow values (the primal solution) into the
715 /// This function copies the flow value on each arc into the given
716 /// map. The \c Value type of the algorithm must be convertible to
717 /// the \c Value type of the map.
719 /// \pre \ref run() must be called before using this function.
720 template <typename FlowMap>
721 void flowMap(FlowMap &map) const {
722 for (ArcIt a(_graph); a != INVALID; ++a) {
723 map.set(a, _res_cap[_arc_idb[a]]);
727 /// \brief Return the potential (dual value) of the given node.
729 /// This function returns the potential (dual value) of the
732 /// \pre \ref run() must be called before using this function.
733 Cost potential(const Node& n) const {
734 return static_cast<Cost>(_pi[_node_id[n]]);
737 /// \brief Copy the potential values (the dual solution) into the
740 /// This function copies the potential (dual value) of each node
741 /// into the given map.
742 /// The \c Cost type of the algorithm must be convertible to the
743 /// \c Value type of the map.
745 /// \pre \ref run() must be called before using this function.
746 template <typename PotentialMap>
747 void potentialMap(PotentialMap &map) const {
748 for (NodeIt n(_graph); n != INVALID; ++n) {
749 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
757 // Initialize the algorithm
759 if (_res_node_num <= 1) return INFEASIBLE;
761 // Check the sum of supply values
763 for (int i = 0; i != _root; ++i) {
764 _sum_supply += _supply[i];
766 if (_sum_supply > 0) return INFEASIBLE;
768 // Check lower and upper bounds
769 LEMON_DEBUG(checkBoundMaps(),
770 "Upper bounds must be greater or equal to the lower bounds");
773 // Initialize vectors
774 for (int i = 0; i != _res_node_num; ++i) {
776 _excess[i] = _supply[i];
779 // Remove infinite upper bounds and check negative arcs
780 const Value MAX = std::numeric_limits<Value>::max();
783 for (int i = 0; i != _root; ++i) {
784 last_out = _first_out[i+1];
785 for (int j = _first_out[i]; j != last_out; ++j) {
787 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
788 if (c >= MAX) return UNBOUNDED;
790 _excess[_target[j]] += c;
795 for (int i = 0; i != _root; ++i) {
796 last_out = _first_out[i+1];
797 for (int j = _first_out[i]; j != last_out; ++j) {
798 if (_forward[j] && _scost[j] < 0) {
800 if (c >= MAX) return UNBOUNDED;
802 _excess[_target[j]] += c;
807 Value ex, max_cap = 0;
808 for (int i = 0; i != _res_node_num; ++i) {
811 if (ex < 0) max_cap -= ex;
813 for (int j = 0; j != _res_arc_num; ++j) {
814 if (_upper[j] >= MAX) _upper[j] = max_cap;
817 // Initialize the large cost vector and the epsilon parameter
820 for (int i = 0; i != _root; ++i) {
821 last_out = _first_out[i+1];
822 for (int j = _first_out[i]; j != last_out; ++j) {
823 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
825 if (lc > _epsilon) _epsilon = lc;
830 // Initialize maps for Circulation and remove non-zero lower bounds
831 ConstMap<Arc, Value> low(0);
832 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
833 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
834 ValueArcMap cap(_graph), flow(_graph);
835 ValueNodeMap sup(_graph);
836 for (NodeIt n(_graph); n != INVALID; ++n) {
837 sup[n] = _supply[_node_id[n]];
840 for (ArcIt a(_graph); a != INVALID; ++a) {
843 cap[a] = _upper[j] - c;
844 sup[_graph.source(a)] -= c;
845 sup[_graph.target(a)] += c;
848 for (ArcIt a(_graph); a != INVALID; ++a) {
849 cap[a] = _upper[_arc_idf[a]];
854 for (NodeIt n(_graph); n != INVALID; ++n) {
855 if (sup[n] > 0) ++_sup_node_num;
858 // Find a feasible flow using Circulation
859 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
860 circ(_graph, low, cap, sup);
861 if (!circ.flowMap(flow).run()) return INFEASIBLE;
863 // Set residual capacities and handle GEQ supply type
864 if (_sum_supply < 0) {
865 for (ArcIt a(_graph); a != INVALID; ++a) {
867 _res_cap[_arc_idf[a]] = cap[a] - fa;
868 _res_cap[_arc_idb[a]] = fa;
869 sup[_graph.source(a)] -= fa;
870 sup[_graph.target(a)] += fa;
872 for (NodeIt n(_graph); n != INVALID; ++n) {
873 _excess[_node_id[n]] = sup[n];
875 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
877 int ra = _reverse[a];
878 _res_cap[a] = -_sum_supply + 1;
879 _res_cap[ra] = -_excess[u];
885 for (ArcIt a(_graph); a != INVALID; ++a) {
887 _res_cap[_arc_idf[a]] = cap[a] - fa;
888 _res_cap[_arc_idb[a]] = fa;
890 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
891 int ra = _reverse[a];
899 // Initialize data structures for buckets
900 _max_rank = _alpha * _res_node_num;
901 _buckets.resize(_max_rank);
902 _bucket_next.resize(_res_node_num + 1);
903 _bucket_prev.resize(_res_node_num + 1);
904 _rank.resize(_res_node_num + 1);
909 // Check if the upper bound is greater than or equal to the lower bound
910 // on each forward arc.
911 bool checkBoundMaps() {
912 for (int j = 0; j != _res_arc_num; ++j) {
913 if (_forward[j] && _upper[j] < _lower[j]) return false;
918 // Execute the algorithm and transform the results
919 void start(Method method) {
920 const int MAX_PARTIAL_PATH_LENGTH = 4;
927 startAugment(_res_node_num - 1);
929 case PARTIAL_AUGMENT:
930 startAugment(MAX_PARTIAL_PATH_LENGTH);
934 // Compute node potentials (dual solution)
935 for (int i = 0; i != _res_node_num; ++i) {
936 _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
939 for (int i = 0; optimal && i != _res_node_num; ++i) {
940 LargeCost pi_i = _pi[i];
941 int last_out = _first_out[i+1];
942 for (int j = _first_out[i]; j != last_out; ++j) {
943 if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
951 // Compute node potentials for the original costs with BellmanFord
952 // (if it is necessary)
953 typedef std::pair<int, int> IntPair;
955 std::vector<IntPair> arc_vec;
956 std::vector<LargeCost> cost_vec;
957 LargeCostArcMap cost_map(cost_vec);
961 for (int j = 0; j != _res_arc_num; ++j) {
962 if (_res_cap[j] > 0) {
963 int u = _source[j], v = _target[j];
964 arc_vec.push_back(IntPair(u, v));
965 cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
968 sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
970 typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
975 for (int i = 0; i != _res_node_num; ++i) {
976 _pi[i] += bf.dist(sgr.node(i));
980 // Shift potentials to meet the requirements of the GEQ type
981 // optimality conditions
982 LargeCost max_pot = _pi[_root];
983 for (int i = 0; i != _res_node_num; ++i) {
984 if (_pi[i] > max_pot) max_pot = _pi[i];
987 for (int i = 0; i != _res_node_num; ++i) {
992 // Handle non-zero lower bounds
994 int limit = _first_out[_root];
995 for (int j = 0; j != limit; ++j) {
996 if (_forward[j]) _res_cap[_reverse[j]] += _lower[j];
1001 // Initialize a cost scaling phase
1003 // Saturate arcs not satisfying the optimality condition
1004 for (int u = 0; u != _res_node_num; ++u) {
1005 int last_out = _first_out[u+1];
1006 LargeCost pi_u = _pi[u];
1007 for (int a = _first_out[u]; a != last_out; ++a) {
1008 Value delta = _res_cap[a];
1011 if (_cost[a] + pi_u - _pi[v] < 0) {
1012 _excess[u] -= delta;
1013 _excess[v] += delta;
1015 _res_cap[_reverse[a]] += delta;
1021 // Find active nodes (i.e. nodes with positive excess)
1022 for (int u = 0; u != _res_node_num; ++u) {
1023 if (_excess[u] > 0) _active_nodes.push_back(u);
1026 // Initialize the next arcs
1027 for (int u = 0; u != _res_node_num; ++u) {
1028 _next_out[u] = _first_out[u];
1032 // Price (potential) refinement heuristic
1033 bool priceRefinement() {
1035 // Stack for stroing the topological order
1036 IntVector stack(_res_node_num);
1040 while (topologicalSort(stack, stack_top)) {
1042 // Compute node ranks in the acyclic admissible network and
1043 // store the nodes in buckets
1044 for (int i = 0; i != _res_node_num; ++i) {
1047 const int bucket_end = _root + 1;
1048 for (int r = 0; r != _max_rank; ++r) {
1049 _buckets[r] = bucket_end;
1052 for ( ; stack_top >= 0; --stack_top) {
1053 int u = stack[stack_top], v;
1054 int rank_u = _rank[u];
1056 LargeCost rc, pi_u = _pi[u];
1057 int last_out = _first_out[u+1];
1058 for (int a = _first_out[u]; a != last_out; ++a) {
1059 if (_res_cap[a] > 0) {
1061 rc = _cost[a] + pi_u - _pi[v];
1063 LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1064 if (nrc < LargeCost(_max_rank)) {
1065 int new_rank_v = rank_u + static_cast<int>(nrc);
1066 if (new_rank_v > _rank[v]) {
1067 _rank[v] = new_rank_v;
1075 top_rank = std::max(top_rank, rank_u);
1076 int bfirst = _buckets[rank_u];
1077 _bucket_next[u] = bfirst;
1078 _bucket_prev[bfirst] = u;
1079 _buckets[rank_u] = u;
1083 // Check if the current flow is epsilon-optimal
1084 if (top_rank == 0) {
1088 // Process buckets in top-down order
1089 for (int rank = top_rank; rank > 0; --rank) {
1090 while (_buckets[rank] != bucket_end) {
1091 // Remove the first node from the current bucket
1092 int u = _buckets[rank];
1093 _buckets[rank] = _bucket_next[u];
1095 // Search the outgoing arcs of u
1096 LargeCost rc, pi_u = _pi[u];
1097 int last_out = _first_out[u+1];
1098 int v, old_rank_v, new_rank_v;
1099 for (int a = _first_out[u]; a != last_out; ++a) {
1100 if (_res_cap[a] > 0) {
1102 old_rank_v = _rank[v];
1104 if (old_rank_v < rank) {
1106 // Compute the new rank of node v
1107 rc = _cost[a] + pi_u - _pi[v];
1111 LargeCost nrc = rc / _epsilon;
1113 if (nrc < LargeCost(_max_rank)) {
1114 new_rank_v = rank - 1 - static_cast<int>(nrc);
1118 // Change the rank of node v
1119 if (new_rank_v > old_rank_v) {
1120 _rank[v] = new_rank_v;
1122 // Remove v from its old bucket
1123 if (old_rank_v > 0) {
1124 if (_buckets[old_rank_v] == v) {
1125 _buckets[old_rank_v] = _bucket_next[v];
1127 int pv = _bucket_prev[v], nv = _bucket_next[v];
1128 _bucket_next[pv] = nv;
1129 _bucket_prev[nv] = pv;
1133 // Insert v into its new bucket
1134 int nv = _buckets[new_rank_v];
1135 _bucket_next[v] = nv;
1136 _bucket_prev[nv] = v;
1137 _buckets[new_rank_v] = v;
1143 // Refine potential of node u
1144 _pi[u] -= rank * _epsilon;
1153 // Find and cancel cycles in the admissible network and
1154 // determine topological order using DFS
1155 bool topologicalSort(IntVector &stack, int &stack_top) {
1156 const int MAX_CYCLE_CANCEL = 1;
1158 BoolVector reached(_res_node_num, false);
1159 BoolVector processed(_res_node_num, false);
1160 IntVector pred(_res_node_num);
1161 for (int i = 0; i != _res_node_num; ++i) {
1162 _next_out[i] = _first_out[i];
1167 for (int start = 0; start != _res_node_num; ++start) {
1168 if (reached[start]) continue;
1170 // Start DFS search from this start node
1174 // Check the outgoing arcs of the current tip node
1175 reached[tip] = true;
1176 LargeCost pi_tip = _pi[tip];
1177 int a, last_out = _first_out[tip+1];
1178 for (a = _next_out[tip]; a != last_out; ++a) {
1179 if (_res_cap[a] > 0) {
1181 if (_cost[a] + pi_tip - _pi[v] < 0) {
1183 // A new node is reached
1189 last_out = _first_out[tip+1];
1192 else if (!processed[v]) {
1197 // Find the minimum residual capacity along the cycle
1198 Value d, delta = _res_cap[a];
1199 int u, delta_node = tip;
1200 for (u = tip; u != v; ) {
1202 d = _res_cap[_next_out[u]];
1209 // Augment along the cycle
1210 _res_cap[a] -= delta;
1211 _res_cap[_reverse[a]] += delta;
1212 for (u = tip; u != v; ) {
1214 int ca = _next_out[u];
1215 _res_cap[ca] -= delta;
1216 _res_cap[_reverse[ca]] += delta;
1219 // Check the maximum number of cycle canceling
1220 if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1224 // Roll back search to delta_node
1225 if (delta_node != tip) {
1226 for (u = tip; u != delta_node; u = pred[u]) {
1230 a = _next_out[tip] + 1;
1231 last_out = _first_out[tip+1];
1239 // Step back to the previous node
1240 if (a == last_out) {
1241 processed[tip] = true;
1242 stack[++stack_top] = tip;
1245 // Finish DFS from the current start node
1254 return (cycle_cnt == 0);
1257 // Global potential update heuristic
1258 void globalUpdate() {
1259 const int bucket_end = _root + 1;
1261 // Initialize buckets
1262 for (int r = 0; r != _max_rank; ++r) {
1263 _buckets[r] = bucket_end;
1265 Value total_excess = 0;
1266 int b0 = bucket_end;
1267 for (int i = 0; i != _res_node_num; ++i) {
1268 if (_excess[i] < 0) {
1270 _bucket_next[i] = b0;
1271 _bucket_prev[b0] = i;
1274 total_excess += _excess[i];
1275 _rank[i] = _max_rank;
1278 if (total_excess == 0) return;
1281 // Search the buckets
1283 for ( ; r != _max_rank; ++r) {
1284 while (_buckets[r] != bucket_end) {
1285 // Remove the first node from the current bucket
1286 int u = _buckets[r];
1287 _buckets[r] = _bucket_next[u];
1289 // Search the incoming arcs of u
1290 LargeCost pi_u = _pi[u];
1291 int last_out = _first_out[u+1];
1292 for (int a = _first_out[u]; a != last_out; ++a) {
1293 int ra = _reverse[a];
1294 if (_res_cap[ra] > 0) {
1295 int v = _source[ra];
1296 int old_rank_v = _rank[v];
1297 if (r < old_rank_v) {
1298 // Compute the new rank of v
1299 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1300 int new_rank_v = old_rank_v;
1301 if (nrc < LargeCost(_max_rank)) {
1302 new_rank_v = r + 1 + static_cast<int>(nrc);
1305 // Change the rank of v
1306 if (new_rank_v < old_rank_v) {
1307 _rank[v] = new_rank_v;
1308 _next_out[v] = _first_out[v];
1310 // Remove v from its old bucket
1311 if (old_rank_v < _max_rank) {
1312 if (_buckets[old_rank_v] == v) {
1313 _buckets[old_rank_v] = _bucket_next[v];
1315 int pv = _bucket_prev[v], nv = _bucket_next[v];
1316 _bucket_next[pv] = nv;
1317 _bucket_prev[nv] = pv;
1321 // Insert v into its new bucket
1322 int nv = _buckets[new_rank_v];
1323 _bucket_next[v] = nv;
1324 _bucket_prev[nv] = v;
1325 _buckets[new_rank_v] = v;
1331 // Finish search if there are no more active nodes
1332 if (_excess[u] > 0) {
1333 total_excess -= _excess[u];
1334 if (total_excess <= 0) break;
1337 if (total_excess <= 0) break;
1341 for (int u = 0; u != _res_node_num; ++u) {
1342 int k = std::min(_rank[u], r);
1344 _pi[u] -= _epsilon * k;
1345 _next_out[u] = _first_out[u];
1350 /// Execute the algorithm performing augment and relabel operations
1351 void startAugment(int max_length) {
1352 // Paramters for heuristics
1353 const int PRICE_REFINEMENT_LIMIT = 2;
1354 const double GLOBAL_UPDATE_FACTOR = 1.0;
1355 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1356 (_res_node_num + _sup_node_num * _sup_node_num));
1357 int next_global_update_limit = global_update_skip;
1359 // Perform cost scaling phases
1361 BoolVector path_arc(_res_arc_num, false);
1362 int relabel_cnt = 0;
1363 int eps_phase_cnt = 0;
1364 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1365 1 : _epsilon / _alpha )
1369 // Price refinement heuristic
1370 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1371 if (priceRefinement()) continue;
1374 // Initialize current phase
1377 // Perform partial augment and relabel operations
1379 // Select an active node (FIFO selection)
1380 while (_active_nodes.size() > 0 &&
1381 _excess[_active_nodes.front()] <= 0) {
1382 _active_nodes.pop_front();
1384 if (_active_nodes.size() == 0) break;
1385 int start = _active_nodes.front();
1387 // Find an augmenting path from the start node
1389 while (int(path.size()) < max_length && _excess[tip] >= 0) {
1391 LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1392 LargeCost pi_tip = _pi[tip];
1393 int last_out = _first_out[tip+1];
1394 for (int a = _next_out[tip]; a != last_out; ++a) {
1395 if (_res_cap[a] > 0) {
1397 rc = _cost[a] + pi_tip - _pi[u];
1402 goto augment; // a cycle is found, stop path search
1408 else if (rc < min_red_cost) {
1416 int ra = _reverse[path.back()];
1418 std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1420 last_out = _next_out[tip];
1421 for (int a = _first_out[tip]; a != last_out; ++a) {
1422 if (_res_cap[a] > 0) {
1423 rc = _cost[a] + pi_tip - _pi[_target[a]];
1424 if (rc < min_red_cost) {
1429 _pi[tip] -= min_red_cost + _epsilon;
1430 _next_out[tip] = _first_out[tip];
1435 int pa = path.back();
1436 path_arc[pa] = false;
1444 // Augment along the found path (as much flow as possible)
1447 int pa, u, v = start;
1448 for (int i = 0; i != int(path.size()); ++i) {
1452 path_arc[pa] = false;
1453 delta = std::min(_res_cap[pa], _excess[u]);
1454 _res_cap[pa] -= delta;
1455 _res_cap[_reverse[pa]] += delta;
1456 _excess[u] -= delta;
1457 _excess[v] += delta;
1458 if (_excess[v] > 0 && _excess[v] <= delta) {
1459 _active_nodes.push_back(v);
1464 // Global update heuristic
1465 if (relabel_cnt >= next_global_update_limit) {
1467 next_global_update_limit += global_update_skip;
1475 /// Execute the algorithm performing push and relabel operations
1477 // Paramters for heuristics
1478 const int PRICE_REFINEMENT_LIMIT = 2;
1479 const double GLOBAL_UPDATE_FACTOR = 2.0;
1481 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1482 (_res_node_num + _sup_node_num * _sup_node_num));
1483 int next_global_update_limit = global_update_skip;
1485 // Perform cost scaling phases
1486 BoolVector hyper(_res_node_num, false);
1487 LargeCostVector hyper_cost(_res_node_num);
1488 int relabel_cnt = 0;
1489 int eps_phase_cnt = 0;
1490 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1491 1 : _epsilon / _alpha )
1495 // Price refinement heuristic
1496 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1497 if (priceRefinement()) continue;
1500 // Initialize current phase
1503 // Perform push and relabel operations
1504 while (_active_nodes.size() > 0) {
1505 LargeCost min_red_cost, rc, pi_n;
1507 int n, t, a, last_out = _res_arc_num;
1510 // Select an active node (FIFO selection)
1511 n = _active_nodes.front();
1512 last_out = _first_out[n+1];
1515 // Perform push operations if there are admissible arcs
1516 if (_excess[n] > 0) {
1517 for (a = _next_out[n]; a != last_out; ++a) {
1518 if (_res_cap[a] > 0 &&
1519 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1520 delta = std::min(_res_cap[a], _excess[n]);
1523 // Push-look-ahead heuristic
1524 Value ahead = -_excess[t];
1525 int last_out_t = _first_out[t+1];
1526 LargeCost pi_t = _pi[t];
1527 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1528 if (_res_cap[ta] > 0 &&
1529 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1530 ahead += _res_cap[ta];
1531 if (ahead >= delta) break;
1533 if (ahead < 0) ahead = 0;
1535 // Push flow along the arc
1536 if (ahead < delta && !hyper[t]) {
1537 _res_cap[a] -= ahead;
1538 _res_cap[_reverse[a]] += ahead;
1539 _excess[n] -= ahead;
1540 _excess[t] += ahead;
1541 _active_nodes.push_front(t);
1543 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1547 _res_cap[a] -= delta;
1548 _res_cap[_reverse[a]] += delta;
1549 _excess[n] -= delta;
1550 _excess[t] += delta;
1551 if (_excess[t] > 0 && _excess[t] <= delta)
1552 _active_nodes.push_back(t);
1555 if (_excess[n] == 0) {
1564 // Relabel the node if it is still active (or hyper)
1565 if (_excess[n] > 0 || hyper[n]) {
1566 min_red_cost = hyper[n] ? -hyper_cost[n] :
1567 std::numeric_limits<LargeCost>::max();
1568 for (int a = _first_out[n]; a != last_out; ++a) {
1569 if (_res_cap[a] > 0) {
1570 rc = _cost[a] + pi_n - _pi[_target[a]];
1571 if (rc < min_red_cost) {
1576 _pi[n] -= min_red_cost + _epsilon;
1577 _next_out[n] = _first_out[n];
1582 // Remove nodes that are not active nor hyper
1584 while ( _active_nodes.size() > 0 &&
1585 _excess[_active_nodes.front()] <= 0 &&
1586 !hyper[_active_nodes.front()] ) {
1587 _active_nodes.pop_front();
1590 // Global update heuristic
1591 if (relabel_cnt >= next_global_update_limit) {
1593 for (int u = 0; u != _res_node_num; ++u)
1595 next_global_update_limit += global_update_skip;
1601 }; //class CostScaling
1607 #endif //LEMON_COST_SCALING_H