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" \ref amo93networkflows, \ref goldberg90approximation,
95 /// \ref goldberg97efficient, \ref 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.
100 /// Most of the parameters of the problem (except for the digraph)
101 /// can be given using separate functions, and the algorithm can be
102 /// executed using the \ref run() function. If some parameters are not
103 /// specified, then default values will be used.
105 /// \tparam GR The digraph type the algorithm runs on.
106 /// \tparam V The number type used for flow amounts, capacity bounds
107 /// and supply values in the algorithm. By default, it is \c int.
108 /// \tparam C The number type used for costs and potentials in the
109 /// algorithm. By default, it is the same as \c V.
110 /// \tparam TR The traits class that defines various types used by the
111 /// algorithm. By default, it is \ref CostScalingDefaultTraits
112 /// "CostScalingDefaultTraits<GR, V, C>".
113 /// In most cases, this parameter should not be set directly,
114 /// consider to use the named template parameters instead.
116 /// \warning Both \c V and \c C must be signed number types.
117 /// \warning All input data (capacities, supply values, and costs) must
119 /// \warning This algorithm does not support negative costs for such
120 /// arcs that have infinite upper bound.
122 /// \note %CostScaling provides three different internal methods,
123 /// from which the most efficient one is used by default.
124 /// For more information, see \ref Method.
126 template <typename GR, typename V, typename C, typename TR>
128 template < typename GR, typename V = int, typename C = V,
129 typename TR = CostScalingDefaultTraits<GR, V, C> >
135 /// The type of the digraph
136 typedef typename TR::Digraph Digraph;
137 /// The type of the flow amounts, capacity bounds and supply values
138 typedef typename TR::Value Value;
139 /// The type of the arc costs
140 typedef typename TR::Cost Cost;
142 /// \brief The large cost type
144 /// The large cost type used for internal computations.
145 /// By default, it is \c long \c long if the \c Cost type is integer,
146 /// otherwise it is \c double.
147 typedef typename TR::LargeCost LargeCost;
149 /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
154 /// \brief Problem type constants for the \c run() function.
156 /// Enum type containing the problem type constants that can be
157 /// returned by the \ref run() function of the algorithm.
159 /// The problem has no feasible solution (flow).
161 /// The problem has optimal solution (i.e. it is feasible and
162 /// bounded), and the algorithm has found optimal flow and node
163 /// potentials (primal and dual solutions).
165 /// The digraph contains an arc of negative cost and infinite
166 /// upper bound. It means that the objective function is unbounded
167 /// on that arc, however, note that it could actually be bounded
168 /// over the feasible flows, but this algroithm cannot handle
173 /// \brief Constants for selecting the internal method.
175 /// Enum type containing constants for selecting the internal method
176 /// for the \ref run() function.
178 /// \ref CostScaling provides three internal methods that differ mainly
179 /// in their base operations, which are used in conjunction with the
180 /// relabel operation.
181 /// By default, the so called \ref PARTIAL_AUGMENT
182 /// "Partial Augment-Relabel" method is used, which proved to be
183 /// the most efficient and the most robust on various test inputs.
184 /// However, the other methods can be selected using the \ref run()
185 /// function with the proper parameter.
187 /// Local push operations are used, i.e. flow is moved only on one
188 /// admissible arc at once.
190 /// Augment operations are used, i.e. flow is moved on admissible
191 /// paths from a node with excess to a node with deficit.
193 /// Partial augment operations are used, i.e. flow is moved on
194 /// admissible paths started from a node with excess, but the
195 /// lengths of these paths are limited. This method can be viewed
196 /// as a combined version of the previous two operations.
202 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
204 typedef std::vector<int> IntVector;
205 typedef std::vector<Value> ValueVector;
206 typedef std::vector<Cost> CostVector;
207 typedef std::vector<LargeCost> LargeCostVector;
208 typedef std::vector<char> BoolVector;
209 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
213 template <typename KT, typename VT>
214 class StaticVectorMap {
219 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
221 const Value& operator[](const Key& key) const {
222 return _v[StaticDigraph::id(key)];
225 Value& operator[](const Key& key) {
226 return _v[StaticDigraph::id(key)];
229 void set(const Key& key, const Value& val) {
230 _v[StaticDigraph::id(key)] = val;
234 std::vector<Value>& _v;
237 typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
238 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
242 // Data related to the underlying digraph
250 // Parameters of the problem
255 // Data structures for storing the digraph
259 IntVector _first_out;
271 ValueVector _res_cap;
272 LargeCostVector _cost;
276 std::deque<int> _active_nodes;
283 IntVector _bucket_next;
284 IntVector _bucket_prev;
288 // Data for a StaticDigraph structure
289 typedef std::pair<int, int> IntPair;
291 std::vector<IntPair> _arc_vec;
292 std::vector<LargeCost> _cost_vec;
293 LargeCostArcMap _cost_map;
294 LargeCostNodeMap _pi_map;
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 _cost_map(_cost_vec), _pi_map(_pi),
343 INF(std::numeric_limits<Value>::has_infinity ?
344 std::numeric_limits<Value>::infinity() :
345 std::numeric_limits<Value>::max())
347 // Check the number types
348 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
349 "The flow type of CostScaling must be signed");
350 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
351 "The cost type of CostScaling must be signed");
353 // Reset data structures
358 /// The parameters of the algorithm can be specified using these
363 /// \brief Set the lower bounds on the arcs.
365 /// This function sets the lower bounds on the arcs.
366 /// If it is not used before calling \ref run(), the lower bounds
367 /// will be set to zero on all arcs.
369 /// \param map An arc map storing the lower bounds.
370 /// Its \c Value type must be convertible to the \c Value type
371 /// of the algorithm.
373 /// \return <tt>(*this)</tt>
374 template <typename LowerMap>
375 CostScaling& lowerMap(const LowerMap& map) {
377 for (ArcIt a(_graph); a != INVALID; ++a) {
378 _lower[_arc_idf[a]] = map[a];
379 _lower[_arc_idb[a]] = map[a];
384 /// \brief Set the upper bounds (capacities) on the arcs.
386 /// This function sets the upper bounds (capacities) on the arcs.
387 /// If it is not used before calling \ref run(), the upper bounds
388 /// will be set to \ref INF on all arcs (i.e. the flow value will be
389 /// unbounded from above).
391 /// \param map An arc map storing the upper bounds.
392 /// Its \c Value type must be convertible to the \c Value type
393 /// of the algorithm.
395 /// \return <tt>(*this)</tt>
396 template<typename UpperMap>
397 CostScaling& upperMap(const UpperMap& map) {
398 for (ArcIt a(_graph); a != INVALID; ++a) {
399 _upper[_arc_idf[a]] = map[a];
404 /// \brief Set the costs of the arcs.
406 /// This function sets the costs of the arcs.
407 /// If it is not used before calling \ref run(), the costs
408 /// will be set to \c 1 on all arcs.
410 /// \param map An arc map storing the costs.
411 /// Its \c Value type must be convertible to the \c Cost type
412 /// of the algorithm.
414 /// \return <tt>(*this)</tt>
415 template<typename CostMap>
416 CostScaling& costMap(const CostMap& map) {
417 for (ArcIt a(_graph); a != INVALID; ++a) {
418 _scost[_arc_idf[a]] = map[a];
419 _scost[_arc_idb[a]] = -map[a];
424 /// \brief Set the supply values of the nodes.
426 /// This function sets the supply values of the nodes.
427 /// If neither this function nor \ref stSupply() is used before
428 /// calling \ref run(), the supply of each node will be set to zero.
430 /// \param map A node map storing the supply values.
431 /// Its \c Value type must be convertible to the \c Value type
432 /// of the algorithm.
434 /// \return <tt>(*this)</tt>
435 template<typename SupplyMap>
436 CostScaling& supplyMap(const SupplyMap& map) {
437 for (NodeIt n(_graph); n != INVALID; ++n) {
438 _supply[_node_id[n]] = map[n];
443 /// \brief Set single source and target nodes and a supply value.
445 /// This function sets a single source node and a single target node
446 /// and the required flow value.
447 /// If neither this function nor \ref supplyMap() is used before
448 /// calling \ref run(), the supply of each node will be set to zero.
450 /// Using this function has the same effect as using \ref supplyMap()
451 /// with such a map in which \c k is assigned to \c s, \c -k is
452 /// assigned to \c t and all other nodes have zero supply value.
454 /// \param s The source node.
455 /// \param t The target node.
456 /// \param k The required amount of flow from node \c s to node \c t
457 /// (i.e. the supply of \c s and the demand of \c t).
459 /// \return <tt>(*this)</tt>
460 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
461 for (int i = 0; i != _res_node_num; ++i) {
464 _supply[_node_id[s]] = k;
465 _supply[_node_id[t]] = -k;
471 /// \name Execution control
472 /// The algorithm can be executed using \ref run().
476 /// \brief Run the algorithm.
478 /// This function runs the algorithm.
479 /// The paramters can be specified using functions \ref lowerMap(),
480 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
483 /// CostScaling<ListDigraph> cs(graph);
484 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
485 /// .supplyMap(sup).run();
488 /// This function can be called more than once. All the given parameters
489 /// are kept for the next call, unless \ref resetParams() or \ref reset()
490 /// is used, thus only the modified parameters have to be set again.
491 /// If the underlying digraph was also modified after the construction
492 /// of the class (or the last \ref reset() call), then the \ref reset()
493 /// function must be called.
495 /// \param method The internal method that will be used in the
496 /// algorithm. For more information, see \ref Method.
497 /// \param factor The cost scaling factor. It must be larger than one.
499 /// \return \c INFEASIBLE if no feasible flow exists,
500 /// \n \c OPTIMAL if the problem has optimal solution
501 /// (i.e. it is feasible and bounded), and the algorithm has found
502 /// optimal flow and node potentials (primal and dual solutions),
503 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
504 /// and infinite upper bound. It means that the objective function
505 /// is unbounded on that arc, however, note that it could actually be
506 /// bounded over the feasible flows, but this algroithm cannot handle
509 /// \see ProblemType, Method
510 /// \see resetParams(), reset()
511 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
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 all the parameters that have been given before.
577 /// This function resets all the paramaters that have been given
578 /// before using functions \ref lowerMap(), \ref upperMap(),
579 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
581 /// It is useful for multiple run() calls. If this function is not
582 /// used, all the parameters given before are kept for the next
584 /// However, the underlying digraph must not be modified after this
585 /// class have been constructed, since it copies and extends the graph.
586 /// \return <tt>(*this)</tt>
587 CostScaling& reset() {
589 _node_num = countNodes(_graph);
590 _arc_num = countArcs(_graph);
591 _res_node_num = _node_num + 1;
592 _res_arc_num = 2 * (_arc_num + _node_num);
595 _first_out.resize(_res_node_num + 1);
596 _forward.resize(_res_arc_num);
597 _source.resize(_res_arc_num);
598 _target.resize(_res_arc_num);
599 _reverse.resize(_res_arc_num);
601 _lower.resize(_res_arc_num);
602 _upper.resize(_res_arc_num);
603 _scost.resize(_res_arc_num);
604 _supply.resize(_res_node_num);
606 _res_cap.resize(_res_arc_num);
607 _cost.resize(_res_arc_num);
608 _pi.resize(_res_node_num);
609 _excess.resize(_res_node_num);
610 _next_out.resize(_res_node_num);
612 _arc_vec.reserve(_res_arc_num);
613 _cost_vec.reserve(_res_arc_num);
616 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
617 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
621 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
623 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
627 _target[j] = _node_id[_graph.runningNode(a)];
629 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
633 _target[j] = _node_id[_graph.runningNode(a)];
646 _first_out[_res_node_num] = k;
647 for (ArcIt a(_graph); a != INVALID; ++a) {
648 int fi = _arc_idf[a];
649 int bi = _arc_idb[a];
661 /// \name Query Functions
662 /// The results of the algorithm can be obtained using these
664 /// The \ref run() function must be called before using them.
668 /// \brief Return the total cost of the found flow.
670 /// This function returns the total cost of the found flow.
671 /// Its complexity is O(e).
673 /// \note The return type of the function can be specified as a
674 /// template parameter. For example,
676 /// cs.totalCost<double>();
678 /// It is useful if the total cost cannot be stored in the \c Cost
679 /// type of the algorithm, which is the default return type of the
682 /// \pre \ref run() must be called before using this function.
683 template <typename Number>
684 Number totalCost() const {
686 for (ArcIt a(_graph); a != INVALID; ++a) {
688 c += static_cast<Number>(_res_cap[i]) *
689 (-static_cast<Number>(_scost[i]));
695 Cost totalCost() const {
696 return totalCost<Cost>();
700 /// \brief Return the flow on the given arc.
702 /// This function returns the flow on the given arc.
704 /// \pre \ref run() must be called before using this function.
705 Value flow(const Arc& a) const {
706 return _res_cap[_arc_idb[a]];
709 /// \brief Return the flow map (the primal solution).
711 /// This function copies the flow value on each arc into the given
712 /// map. The \c Value type of the algorithm must be convertible to
713 /// the \c Value type of the map.
715 /// \pre \ref run() must be called before using this function.
716 template <typename FlowMap>
717 void flowMap(FlowMap &map) const {
718 for (ArcIt a(_graph); a != INVALID; ++a) {
719 map.set(a, _res_cap[_arc_idb[a]]);
723 /// \brief Return the potential (dual value) of the given node.
725 /// This function returns the potential (dual value) of the
728 /// \pre \ref run() must be called before using this function.
729 Cost potential(const Node& n) const {
730 return static_cast<Cost>(_pi[_node_id[n]]);
733 /// \brief Return the potential map (the dual solution).
735 /// This function copies the potential (dual value) of each node
736 /// into the given map.
737 /// The \c Cost type of the algorithm must be convertible to the
738 /// \c Value type of the map.
740 /// \pre \ref run() must be called before using this function.
741 template <typename PotentialMap>
742 void potentialMap(PotentialMap &map) const {
743 for (NodeIt n(_graph); n != INVALID; ++n) {
744 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
752 // Initialize the algorithm
754 if (_res_node_num <= 1) return INFEASIBLE;
756 // Check the sum of supply values
758 for (int i = 0; i != _root; ++i) {
759 _sum_supply += _supply[i];
761 if (_sum_supply > 0) return INFEASIBLE;
764 // Initialize vectors
765 for (int i = 0; i != _res_node_num; ++i) {
767 _excess[i] = _supply[i];
770 // Remove infinite upper bounds and check negative arcs
771 const Value MAX = std::numeric_limits<Value>::max();
774 for (int i = 0; i != _root; ++i) {
775 last_out = _first_out[i+1];
776 for (int j = _first_out[i]; j != last_out; ++j) {
778 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
779 if (c >= MAX) return UNBOUNDED;
781 _excess[_target[j]] += c;
786 for (int i = 0; i != _root; ++i) {
787 last_out = _first_out[i+1];
788 for (int j = _first_out[i]; j != last_out; ++j) {
789 if (_forward[j] && _scost[j] < 0) {
791 if (c >= MAX) return UNBOUNDED;
793 _excess[_target[j]] += c;
798 Value ex, max_cap = 0;
799 for (int i = 0; i != _res_node_num; ++i) {
802 if (ex < 0) max_cap -= ex;
804 for (int j = 0; j != _res_arc_num; ++j) {
805 if (_upper[j] >= MAX) _upper[j] = max_cap;
808 // Initialize the large cost vector and the epsilon parameter
811 for (int i = 0; i != _root; ++i) {
812 last_out = _first_out[i+1];
813 for (int j = _first_out[i]; j != last_out; ++j) {
814 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
816 if (lc > _epsilon) _epsilon = lc;
821 // Initialize maps for Circulation and remove non-zero lower bounds
822 ConstMap<Arc, Value> low(0);
823 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
824 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
825 ValueArcMap cap(_graph), flow(_graph);
826 ValueNodeMap sup(_graph);
827 for (NodeIt n(_graph); n != INVALID; ++n) {
828 sup[n] = _supply[_node_id[n]];
831 for (ArcIt a(_graph); a != INVALID; ++a) {
834 cap[a] = _upper[j] - c;
835 sup[_graph.source(a)] -= c;
836 sup[_graph.target(a)] += c;
839 for (ArcIt a(_graph); a != INVALID; ++a) {
840 cap[a] = _upper[_arc_idf[a]];
845 for (NodeIt n(_graph); n != INVALID; ++n) {
846 if (sup[n] > 0) ++_sup_node_num;
849 // Find a feasible flow using Circulation
850 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
851 circ(_graph, low, cap, sup);
852 if (!circ.flowMap(flow).run()) return INFEASIBLE;
854 // Set residual capacities and handle GEQ supply type
855 if (_sum_supply < 0) {
856 for (ArcIt a(_graph); a != INVALID; ++a) {
858 _res_cap[_arc_idf[a]] = cap[a] - fa;
859 _res_cap[_arc_idb[a]] = fa;
860 sup[_graph.source(a)] -= fa;
861 sup[_graph.target(a)] += fa;
863 for (NodeIt n(_graph); n != INVALID; ++n) {
864 _excess[_node_id[n]] = sup[n];
866 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
868 int ra = _reverse[a];
869 _res_cap[a] = -_sum_supply + 1;
870 _res_cap[ra] = -_excess[u];
876 for (ArcIt a(_graph); a != INVALID; ++a) {
878 _res_cap[_arc_idf[a]] = cap[a] - fa;
879 _res_cap[_arc_idb[a]] = fa;
881 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
882 int ra = _reverse[a];
893 // Execute the algorithm and transform the results
894 void start(Method method) {
895 // Maximum path length for partial augment
896 const int MAX_PATH_LENGTH = 4;
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);
905 // Execute the algorithm
913 case PARTIAL_AUGMENT:
914 startAugment(MAX_PATH_LENGTH);
918 // Compute node potentials for the original costs
921 for (int j = 0; j != _res_arc_num; ++j) {
922 if (_res_cap[j] > 0) {
923 _arc_vec.push_back(IntPair(_source[j], _target[j]));
924 _cost_vec.push_back(_scost[j]);
927 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
929 typename BellmanFord<StaticDigraph, LargeCostArcMap>
930 ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
935 // Handle non-zero lower bounds
937 int limit = _first_out[_root];
938 for (int j = 0; j != limit; ++j) {
939 if (!_forward[j]) _res_cap[j] += _lower[j];
944 // Initialize a cost scaling phase
946 // Saturate arcs not satisfying the optimality condition
947 for (int u = 0; u != _res_node_num; ++u) {
948 int last_out = _first_out[u+1];
949 LargeCost pi_u = _pi[u];
950 for (int a = _first_out[u]; a != last_out; ++a) {
952 if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) {
953 Value delta = _res_cap[a];
957 _res_cap[_reverse[a]] += delta;
962 // Find active nodes (i.e. nodes with positive excess)
963 for (int u = 0; u != _res_node_num; ++u) {
964 if (_excess[u] > 0) _active_nodes.push_back(u);
967 // Initialize the next arcs
968 for (int u = 0; u != _res_node_num; ++u) {
969 _next_out[u] = _first_out[u];
973 // Early termination heuristic
974 bool earlyTermination() {
975 const double EARLY_TERM_FACTOR = 3.0;
977 // Build a static residual graph
980 for (int j = 0; j != _res_arc_num; ++j) {
981 if (_res_cap[j] > 0) {
982 _arc_vec.push_back(IntPair(_source[j], _target[j]));
983 _cost_vec.push_back(_cost[j] + 1);
986 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
988 // Run Bellman-Ford algorithm to check if the current flow is optimal
989 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
992 int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num)));
993 for (int i = 0; i < K && !done; ++i) {
994 done = bf.processNextWeakRound();
999 // Global potential update heuristic
1000 void globalUpdate() {
1001 int bucket_end = _root + 1;
1003 // Initialize buckets
1004 for (int r = 0; r != _max_rank; ++r) {
1005 _buckets[r] = bucket_end;
1007 Value total_excess = 0;
1008 for (int i = 0; i != _res_node_num; ++i) {
1009 if (_excess[i] < 0) {
1011 _bucket_next[i] = _buckets[0];
1012 _bucket_prev[_buckets[0]] = i;
1015 total_excess += _excess[i];
1016 _rank[i] = _max_rank;
1019 if (total_excess == 0) return;
1021 // Search the buckets
1023 for ( ; r != _max_rank; ++r) {
1024 while (_buckets[r] != bucket_end) {
1025 // Remove the first node from the current bucket
1026 int u = _buckets[r];
1027 _buckets[r] = _bucket_next[u];
1029 // Search the incomming arcs of u
1030 LargeCost pi_u = _pi[u];
1031 int last_out = _first_out[u+1];
1032 for (int a = _first_out[u]; a != last_out; ++a) {
1033 int ra = _reverse[a];
1034 if (_res_cap[ra] > 0) {
1035 int v = _source[ra];
1036 int old_rank_v = _rank[v];
1037 if (r < old_rank_v) {
1038 // Compute the new rank of v
1039 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1040 int new_rank_v = old_rank_v;
1041 if (nrc < LargeCost(_max_rank))
1042 new_rank_v = r + 1 + int(nrc);
1044 // Change the rank of v
1045 if (new_rank_v < old_rank_v) {
1046 _rank[v] = new_rank_v;
1047 _next_out[v] = _first_out[v];
1049 // Remove v from its old bucket
1050 if (old_rank_v < _max_rank) {
1051 if (_buckets[old_rank_v] == v) {
1052 _buckets[old_rank_v] = _bucket_next[v];
1054 _bucket_next[_bucket_prev[v]] = _bucket_next[v];
1055 _bucket_prev[_bucket_next[v]] = _bucket_prev[v];
1059 // Insert v to its new bucket
1060 _bucket_next[v] = _buckets[new_rank_v];
1061 _bucket_prev[_buckets[new_rank_v]] = v;
1062 _buckets[new_rank_v] = v;
1068 // Finish search if there are no more active nodes
1069 if (_excess[u] > 0) {
1070 total_excess -= _excess[u];
1071 if (total_excess <= 0) break;
1074 if (total_excess <= 0) break;
1078 for (int u = 0; u != _res_node_num; ++u) {
1079 int k = std::min(_rank[u], r);
1081 _pi[u] -= _epsilon * k;
1082 _next_out[u] = _first_out[u];
1087 /// Execute the algorithm performing augment and relabel operations
1088 void startAugment(int max_length = std::numeric_limits<int>::max()) {
1089 // Paramters for heuristics
1090 const int EARLY_TERM_EPSILON_LIMIT = 1000;
1091 const double GLOBAL_UPDATE_FACTOR = 3.0;
1093 const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1094 (_res_node_num + _sup_node_num * _sup_node_num));
1095 int next_update_limit = global_update_freq;
1097 int relabel_cnt = 0;
1099 // Perform cost scaling phases
1100 std::vector<int> path;
1101 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1102 1 : _epsilon / _alpha )
1104 // Early termination heuristic
1105 if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1106 if (earlyTermination()) break;
1109 // Initialize current phase
1112 // Perform partial augment and relabel operations
1114 // Select an active node (FIFO selection)
1115 while (_active_nodes.size() > 0 &&
1116 _excess[_active_nodes.front()] <= 0) {
1117 _active_nodes.pop_front();
1119 if (_active_nodes.size() == 0) break;
1120 int start = _active_nodes.front();
1122 // Find an augmenting path from the start node
1125 while (_excess[tip] >= 0 && int(path.size()) < max_length) {
1127 LargeCost min_red_cost, rc, pi_tip = _pi[tip];
1128 int last_out = _first_out[tip+1];
1129 for (int a = _next_out[tip]; a != last_out; ++a) {
1131 if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) {
1140 min_red_cost = std::numeric_limits<LargeCost>::max();
1142 int ra = _reverse[path.back()];
1143 min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]];
1145 for (int a = _first_out[tip]; a != last_out; ++a) {
1146 rc = _cost[a] + pi_tip - _pi[_target[a]];
1147 if (_res_cap[a] > 0 && rc < min_red_cost) {
1151 _pi[tip] -= min_red_cost + _epsilon;
1152 _next_out[tip] = _first_out[tip];
1157 tip = _source[path.back()];
1164 // Augment along the found path (as much flow as possible)
1166 int pa, u, v = start;
1167 for (int i = 0; i != int(path.size()); ++i) {
1171 delta = std::min(_res_cap[pa], _excess[u]);
1172 _res_cap[pa] -= delta;
1173 _res_cap[_reverse[pa]] += delta;
1174 _excess[u] -= delta;
1175 _excess[v] += delta;
1176 if (_excess[v] > 0 && _excess[v] <= delta)
1177 _active_nodes.push_back(v);
1180 // Global update heuristic
1181 if (relabel_cnt >= next_update_limit) {
1183 next_update_limit += global_update_freq;
1189 /// Execute the algorithm performing push and relabel operations
1191 // Paramters for heuristics
1192 const int EARLY_TERM_EPSILON_LIMIT = 1000;
1193 const double GLOBAL_UPDATE_FACTOR = 2.0;
1195 const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1196 (_res_node_num + _sup_node_num * _sup_node_num));
1197 int next_update_limit = global_update_freq;
1199 int relabel_cnt = 0;
1201 // Perform cost scaling phases
1202 BoolVector hyper(_res_node_num, false);
1203 LargeCostVector hyper_cost(_res_node_num);
1204 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1205 1 : _epsilon / _alpha )
1207 // Early termination heuristic
1208 if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1209 if (earlyTermination()) break;
1212 // Initialize current phase
1215 // Perform push and relabel operations
1216 while (_active_nodes.size() > 0) {
1217 LargeCost min_red_cost, rc, pi_n;
1219 int n, t, a, last_out = _res_arc_num;
1222 // Select an active node (FIFO selection)
1223 n = _active_nodes.front();
1224 last_out = _first_out[n+1];
1227 // Perform push operations if there are admissible arcs
1228 if (_excess[n] > 0) {
1229 for (a = _next_out[n]; a != last_out; ++a) {
1230 if (_res_cap[a] > 0 &&
1231 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1232 delta = std::min(_res_cap[a], _excess[n]);
1235 // Push-look-ahead heuristic
1236 Value ahead = -_excess[t];
1237 int last_out_t = _first_out[t+1];
1238 LargeCost pi_t = _pi[t];
1239 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1240 if (_res_cap[ta] > 0 &&
1241 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1242 ahead += _res_cap[ta];
1243 if (ahead >= delta) break;
1245 if (ahead < 0) ahead = 0;
1247 // Push flow along the arc
1248 if (ahead < delta && !hyper[t]) {
1249 _res_cap[a] -= ahead;
1250 _res_cap[_reverse[a]] += ahead;
1251 _excess[n] -= ahead;
1252 _excess[t] += ahead;
1253 _active_nodes.push_front(t);
1255 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1259 _res_cap[a] -= delta;
1260 _res_cap[_reverse[a]] += delta;
1261 _excess[n] -= delta;
1262 _excess[t] += delta;
1263 if (_excess[t] > 0 && _excess[t] <= delta)
1264 _active_nodes.push_back(t);
1267 if (_excess[n] == 0) {
1276 // Relabel the node if it is still active (or hyper)
1277 if (_excess[n] > 0 || hyper[n]) {
1278 min_red_cost = hyper[n] ? -hyper_cost[n] :
1279 std::numeric_limits<LargeCost>::max();
1280 for (int a = _first_out[n]; a != last_out; ++a) {
1281 rc = _cost[a] + pi_n - _pi[_target[a]];
1282 if (_res_cap[a] > 0 && rc < min_red_cost) {
1286 _pi[n] -= min_red_cost + _epsilon;
1287 _next_out[n] = _first_out[n];
1292 // Remove nodes that are not active nor hyper
1294 while ( _active_nodes.size() > 0 &&
1295 _excess[_active_nodes.front()] <= 0 &&
1296 !hyper[_active_nodes.front()] ) {
1297 _active_nodes.pop_front();
1300 // Global update heuristic
1301 if (relabel_cnt >= next_update_limit) {
1303 for (int u = 0; u != _res_node_num; ++u)
1305 next_update_limit += global_update_freq;
1311 }; //class CostScaling
1317 #endif //LEMON_COST_SCALING_H