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 /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
101 /// implementations available in LEMON for this problem.
103 /// Most of the parameters of the problem (except for the digraph)
104 /// can be given using separate functions, and the algorithm can be
105 /// executed using the \ref run() function. If some parameters are not
106 /// specified, then default values will be used.
108 /// \tparam GR The digraph type the algorithm runs on.
109 /// \tparam V The number type used for flow amounts, capacity bounds
110 /// and supply values in the algorithm. By default, it is \c int.
111 /// \tparam C The number type used for costs and potentials in the
112 /// algorithm. By default, it is the same as \c V.
113 /// \tparam TR The traits class that defines various types used by the
114 /// algorithm. By default, it is \ref CostScalingDefaultTraits
115 /// "CostScalingDefaultTraits<GR, V, C>".
116 /// In most cases, this parameter should not be set directly,
117 /// consider to use the named template parameters instead.
119 /// \warning Both number types must be signed and all input data must
121 /// \warning This algorithm does not support negative costs for
122 /// arcs having infinite upper bound.
124 /// \note %CostScaling provides three different internal methods,
125 /// from which the most efficient one is used by default.
126 /// For more information, see \ref Method.
128 template <typename GR, typename V, typename C, typename TR>
130 template < typename GR, typename V = int, typename C = V,
131 typename TR = CostScalingDefaultTraits<GR, V, C> >
137 /// The type of the digraph
138 typedef typename TR::Digraph Digraph;
139 /// The type of the flow amounts, capacity bounds and supply values
140 typedef typename TR::Value Value;
141 /// The type of the arc costs
142 typedef typename TR::Cost Cost;
144 /// \brief The large cost type
146 /// The large cost type used for internal computations.
147 /// By default, it is \c long \c long if the \c Cost type is integer,
148 /// otherwise it is \c double.
149 typedef typename TR::LargeCost LargeCost;
151 /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
156 /// \brief Problem type constants for the \c run() function.
158 /// Enum type containing the problem type constants that can be
159 /// returned by the \ref run() function of the algorithm.
161 /// The problem has no feasible solution (flow).
163 /// The problem has optimal solution (i.e. it is feasible and
164 /// bounded), and the algorithm has found optimal flow and node
165 /// potentials (primal and dual solutions).
167 /// The digraph contains an arc of negative cost and infinite
168 /// upper bound. It means that the objective function is unbounded
169 /// on that arc, however, note that it could actually be bounded
170 /// over the feasible flows, but this algroithm cannot handle
175 /// \brief Constants for selecting the internal method.
177 /// Enum type containing constants for selecting the internal method
178 /// for the \ref run() function.
180 /// \ref CostScaling provides three internal methods that differ mainly
181 /// in their base operations, which are used in conjunction with the
182 /// relabel operation.
183 /// By default, the so called \ref PARTIAL_AUGMENT
184 /// "Partial Augment-Relabel" method is used, which turned out to be
185 /// the most efficient and the most robust on various test inputs.
186 /// However, the other methods can be selected using the \ref run()
187 /// function with the proper parameter.
189 /// Local push operations are used, i.e. flow is moved only on one
190 /// admissible arc at once.
192 /// Augment operations are used, i.e. flow is moved on admissible
193 /// paths from a node with excess to a node with deficit.
195 /// Partial augment operations are used, i.e. flow is moved on
196 /// admissible paths started from a node with excess, but the
197 /// lengths of these paths are limited. This method can be viewed
198 /// as a combined version of the previous two operations.
204 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
206 typedef std::vector<int> IntVector;
207 typedef std::vector<Value> ValueVector;
208 typedef std::vector<Cost> CostVector;
209 typedef std::vector<LargeCost> LargeCostVector;
210 typedef std::vector<char> BoolVector;
211 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
215 template <typename KT, typename VT>
216 class StaticVectorMap {
221 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
223 const Value& operator[](const Key& key) const {
224 return _v[StaticDigraph::id(key)];
227 Value& operator[](const Key& key) {
228 return _v[StaticDigraph::id(key)];
231 void set(const Key& key, const Value& val) {
232 _v[StaticDigraph::id(key)] = val;
236 std::vector<Value>& _v;
239 typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
240 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
244 // Data related to the underlying digraph
252 // Parameters of the problem
257 // Data structures for storing the digraph
261 IntVector _first_out;
273 ValueVector _res_cap;
274 LargeCostVector _cost;
278 std::deque<int> _active_nodes;
285 IntVector _bucket_next;
286 IntVector _bucket_prev;
290 // Data for a StaticDigraph structure
291 typedef std::pair<int, int> IntPair;
293 std::vector<IntPair> _arc_vec;
294 std::vector<LargeCost> _cost_vec;
295 LargeCostArcMap _cost_map;
296 LargeCostNodeMap _pi_map;
300 /// \brief Constant for infinite upper bounds (capacities).
302 /// Constant for infinite upper bounds (capacities).
303 /// It is \c std::numeric_limits<Value>::infinity() if available,
304 /// \c std::numeric_limits<Value>::max() otherwise.
309 /// \name Named Template Parameters
312 template <typename T>
313 struct SetLargeCostTraits : public Traits {
317 /// \brief \ref named-templ-param "Named parameter" for setting
318 /// \c LargeCost type.
320 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
321 /// type, which is used for internal computations in the algorithm.
322 /// \c Cost must be convertible to \c LargeCost.
323 template <typename T>
325 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
326 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
337 /// \brief Constructor.
339 /// The constructor of the class.
341 /// \param graph The digraph the algorithm runs on.
342 CostScaling(const GR& graph) :
343 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
344 _cost_map(_cost_vec), _pi_map(_pi),
345 INF(std::numeric_limits<Value>::has_infinity ?
346 std::numeric_limits<Value>::infinity() :
347 std::numeric_limits<Value>::max())
349 // Check the number types
350 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
351 "The flow type of CostScaling must be signed");
352 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
353 "The cost type of CostScaling must be signed");
355 // Reset data structures
360 /// The parameters of the algorithm can be specified using these
365 /// \brief Set the lower bounds on the arcs.
367 /// This function sets the lower bounds on the arcs.
368 /// If it is not used before calling \ref run(), the lower bounds
369 /// will be set to zero on all arcs.
371 /// \param map An arc map storing the lower bounds.
372 /// Its \c Value type must be convertible to the \c Value type
373 /// of the algorithm.
375 /// \return <tt>(*this)</tt>
376 template <typename LowerMap>
377 CostScaling& lowerMap(const LowerMap& map) {
379 for (ArcIt a(_graph); a != INVALID; ++a) {
380 _lower[_arc_idf[a]] = map[a];
381 _lower[_arc_idb[a]] = map[a];
386 /// \brief Set the upper bounds (capacities) on the arcs.
388 /// This function sets the upper bounds (capacities) on the arcs.
389 /// If it is not used before calling \ref run(), the upper bounds
390 /// will be set to \ref INF on all arcs (i.e. the flow value will be
391 /// unbounded from above).
393 /// \param map An arc map storing the upper bounds.
394 /// Its \c Value type must be convertible to the \c Value type
395 /// of the algorithm.
397 /// \return <tt>(*this)</tt>
398 template<typename UpperMap>
399 CostScaling& upperMap(const UpperMap& map) {
400 for (ArcIt a(_graph); a != INVALID; ++a) {
401 _upper[_arc_idf[a]] = map[a];
406 /// \brief Set the costs of the arcs.
408 /// This function sets the costs of the arcs.
409 /// If it is not used before calling \ref run(), the costs
410 /// will be set to \c 1 on all arcs.
412 /// \param map An arc map storing the costs.
413 /// Its \c Value type must be convertible to the \c Cost type
414 /// of the algorithm.
416 /// \return <tt>(*this)</tt>
417 template<typename CostMap>
418 CostScaling& costMap(const CostMap& map) {
419 for (ArcIt a(_graph); a != INVALID; ++a) {
420 _scost[_arc_idf[a]] = map[a];
421 _scost[_arc_idb[a]] = -map[a];
426 /// \brief Set the supply values of the nodes.
428 /// This function sets the supply values of the nodes.
429 /// If neither this function nor \ref stSupply() is used before
430 /// calling \ref run(), the supply of each node will be set to zero.
432 /// \param map A node map storing the supply values.
433 /// Its \c Value type must be convertible to the \c Value type
434 /// of the algorithm.
436 /// \return <tt>(*this)</tt>
437 template<typename SupplyMap>
438 CostScaling& supplyMap(const SupplyMap& map) {
439 for (NodeIt n(_graph); n != INVALID; ++n) {
440 _supply[_node_id[n]] = map[n];
445 /// \brief Set single source and target nodes and a supply value.
447 /// This function sets a single source node and a single target node
448 /// and the required flow value.
449 /// If neither this function nor \ref supplyMap() is used before
450 /// calling \ref run(), the supply of each node will be set to zero.
452 /// Using this function has the same effect as using \ref supplyMap()
453 /// with a map in which \c k is assigned to \c s, \c -k is
454 /// assigned to \c t and all other nodes have zero supply value.
456 /// \param s The source node.
457 /// \param t The target node.
458 /// \param k The required amount of flow from node \c s to node \c t
459 /// (i.e. the supply of \c s and the demand of \c t).
461 /// \return <tt>(*this)</tt>
462 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
463 for (int i = 0; i != _res_node_num; ++i) {
466 _supply[_node_id[s]] = k;
467 _supply[_node_id[t]] = -k;
473 /// \name Execution control
474 /// The algorithm can be executed using \ref run().
478 /// \brief Run the algorithm.
480 /// This function runs the algorithm.
481 /// The paramters can be specified using functions \ref lowerMap(),
482 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
485 /// CostScaling<ListDigraph> cs(graph);
486 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
487 /// .supplyMap(sup).run();
490 /// This function can be called more than once. All the given parameters
491 /// are kept for the next call, unless \ref resetParams() or \ref reset()
492 /// is used, thus only the modified parameters have to be set again.
493 /// If the underlying digraph was also modified after the construction
494 /// of the class (or the last \ref reset() call), then the \ref reset()
495 /// function must be called.
497 /// \param method The internal method that will be used in the
498 /// algorithm. For more information, see \ref Method.
499 /// \param factor The cost scaling factor. It must be larger than one.
501 /// \return \c INFEASIBLE if no feasible flow exists,
502 /// \n \c OPTIMAL if the problem has optimal solution
503 /// (i.e. it is feasible and bounded), and the algorithm has found
504 /// optimal flow and node potentials (primal and dual solutions),
505 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
506 /// and infinite upper bound. It means that the objective function
507 /// is unbounded on that arc, however, note that it could actually be
508 /// bounded over the feasible flows, but this algroithm cannot handle
511 /// \see ProblemType, Method
512 /// \see resetParams(), reset()
513 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
515 ProblemType pt = init();
516 if (pt != OPTIMAL) return pt;
521 /// \brief Reset all the parameters that have been given before.
523 /// This function resets all the paramaters that have been given
524 /// before using functions \ref lowerMap(), \ref upperMap(),
525 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
527 /// It is useful for multiple \ref run() calls. Basically, all the given
528 /// parameters are kept for the next \ref run() call, unless
529 /// \ref resetParams() or \ref reset() is used.
530 /// If the underlying digraph was also modified after the construction
531 /// of the class or the last \ref reset() call, then the \ref reset()
532 /// function must be used, otherwise \ref resetParams() is sufficient.
536 /// CostScaling<ListDigraph> cs(graph);
539 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
540 /// .supplyMap(sup).run();
542 /// // Run again with modified cost map (resetParams() is not called,
543 /// // so only the cost map have to be set again)
545 /// cs.costMap(cost).run();
547 /// // Run again from scratch using resetParams()
548 /// // (the lower bounds will be set to zero on all arcs)
549 /// cs.resetParams();
550 /// cs.upperMap(capacity).costMap(cost)
551 /// .supplyMap(sup).run();
554 /// \return <tt>(*this)</tt>
556 /// \see reset(), run()
557 CostScaling& resetParams() {
558 for (int i = 0; i != _res_node_num; ++i) {
561 int limit = _first_out[_root];
562 for (int j = 0; j != limit; ++j) {
565 _scost[j] = _forward[j] ? 1 : -1;
567 for (int j = limit; j != _res_arc_num; ++j) {
571 _scost[_reverse[j]] = 0;
577 /// \brief Reset all the parameters that have been given before.
579 /// This function resets all the paramaters that have been given
580 /// before using functions \ref lowerMap(), \ref upperMap(),
581 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
583 /// It is useful for multiple run() calls. If this function is not
584 /// used, all the parameters given before are kept for the next
586 /// However, the underlying digraph must not be modified after this
587 /// class have been constructed, since it copies and extends the graph.
588 /// \return <tt>(*this)</tt>
589 CostScaling& reset() {
591 _node_num = countNodes(_graph);
592 _arc_num = countArcs(_graph);
593 _res_node_num = _node_num + 1;
594 _res_arc_num = 2 * (_arc_num + _node_num);
597 _first_out.resize(_res_node_num + 1);
598 _forward.resize(_res_arc_num);
599 _source.resize(_res_arc_num);
600 _target.resize(_res_arc_num);
601 _reverse.resize(_res_arc_num);
603 _lower.resize(_res_arc_num);
604 _upper.resize(_res_arc_num);
605 _scost.resize(_res_arc_num);
606 _supply.resize(_res_node_num);
608 _res_cap.resize(_res_arc_num);
609 _cost.resize(_res_arc_num);
610 _pi.resize(_res_node_num);
611 _excess.resize(_res_node_num);
612 _next_out.resize(_res_node_num);
614 _arc_vec.reserve(_res_arc_num);
615 _cost_vec.reserve(_res_arc_num);
618 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
619 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
623 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
625 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
629 _target[j] = _node_id[_graph.runningNode(a)];
631 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
635 _target[j] = _node_id[_graph.runningNode(a)];
648 _first_out[_res_node_num] = k;
649 for (ArcIt a(_graph); a != INVALID; ++a) {
650 int fi = _arc_idf[a];
651 int bi = _arc_idb[a];
663 /// \name Query Functions
664 /// The results of the algorithm can be obtained using these
666 /// The \ref run() function must be called before using them.
670 /// \brief Return the total cost of the found flow.
672 /// This function returns the total cost of the found flow.
673 /// Its complexity is O(e).
675 /// \note The return type of the function can be specified as a
676 /// template parameter. For example,
678 /// cs.totalCost<double>();
680 /// It is useful if the total cost cannot be stored in the \c Cost
681 /// type of the algorithm, which is the default return type of the
684 /// \pre \ref run() must be called before using this function.
685 template <typename Number>
686 Number totalCost() const {
688 for (ArcIt a(_graph); a != INVALID; ++a) {
690 c += static_cast<Number>(_res_cap[i]) *
691 (-static_cast<Number>(_scost[i]));
697 Cost totalCost() const {
698 return totalCost<Cost>();
702 /// \brief Return the flow on the given arc.
704 /// This function returns the flow on the given arc.
706 /// \pre \ref run() must be called before using this function.
707 Value flow(const Arc& a) const {
708 return _res_cap[_arc_idb[a]];
711 /// \brief Return the flow map (the primal solution).
713 /// This function copies the flow value on each arc into the given
714 /// map. The \c Value type of the algorithm must be convertible to
715 /// the \c Value type of the map.
717 /// \pre \ref run() must be called before using this function.
718 template <typename FlowMap>
719 void flowMap(FlowMap &map) const {
720 for (ArcIt a(_graph); a != INVALID; ++a) {
721 map.set(a, _res_cap[_arc_idb[a]]);
725 /// \brief Return the potential (dual value) of the given node.
727 /// This function returns the potential (dual value) of the
730 /// \pre \ref run() must be called before using this function.
731 Cost potential(const Node& n) const {
732 return static_cast<Cost>(_pi[_node_id[n]]);
735 /// \brief Return the potential map (the dual solution).
737 /// This function copies the potential (dual value) of each node
738 /// into the given map.
739 /// The \c Cost type of the algorithm must be convertible to the
740 /// \c Value type of the map.
742 /// \pre \ref run() must be called before using this function.
743 template <typename PotentialMap>
744 void potentialMap(PotentialMap &map) const {
745 for (NodeIt n(_graph); n != INVALID; ++n) {
746 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
754 // Initialize the algorithm
756 if (_res_node_num <= 1) return INFEASIBLE;
758 // Check the sum of supply values
760 for (int i = 0; i != _root; ++i) {
761 _sum_supply += _supply[i];
763 if (_sum_supply > 0) return INFEASIBLE;
766 // Initialize vectors
767 for (int i = 0; i != _res_node_num; ++i) {
769 _excess[i] = _supply[i];
772 // Remove infinite upper bounds and check negative arcs
773 const Value MAX = std::numeric_limits<Value>::max();
776 for (int i = 0; i != _root; ++i) {
777 last_out = _first_out[i+1];
778 for (int j = _first_out[i]; j != last_out; ++j) {
780 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
781 if (c >= MAX) return UNBOUNDED;
783 _excess[_target[j]] += c;
788 for (int i = 0; i != _root; ++i) {
789 last_out = _first_out[i+1];
790 for (int j = _first_out[i]; j != last_out; ++j) {
791 if (_forward[j] && _scost[j] < 0) {
793 if (c >= MAX) return UNBOUNDED;
795 _excess[_target[j]] += c;
800 Value ex, max_cap = 0;
801 for (int i = 0; i != _res_node_num; ++i) {
804 if (ex < 0) max_cap -= ex;
806 for (int j = 0; j != _res_arc_num; ++j) {
807 if (_upper[j] >= MAX) _upper[j] = max_cap;
810 // Initialize the large cost vector and the epsilon parameter
813 for (int i = 0; i != _root; ++i) {
814 last_out = _first_out[i+1];
815 for (int j = _first_out[i]; j != last_out; ++j) {
816 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
818 if (lc > _epsilon) _epsilon = lc;
823 // Initialize maps for Circulation and remove non-zero lower bounds
824 ConstMap<Arc, Value> low(0);
825 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
826 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
827 ValueArcMap cap(_graph), flow(_graph);
828 ValueNodeMap sup(_graph);
829 for (NodeIt n(_graph); n != INVALID; ++n) {
830 sup[n] = _supply[_node_id[n]];
833 for (ArcIt a(_graph); a != INVALID; ++a) {
836 cap[a] = _upper[j] - c;
837 sup[_graph.source(a)] -= c;
838 sup[_graph.target(a)] += c;
841 for (ArcIt a(_graph); a != INVALID; ++a) {
842 cap[a] = _upper[_arc_idf[a]];
847 for (NodeIt n(_graph); n != INVALID; ++n) {
848 if (sup[n] > 0) ++_sup_node_num;
851 // Find a feasible flow using Circulation
852 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
853 circ(_graph, low, cap, sup);
854 if (!circ.flowMap(flow).run()) return INFEASIBLE;
856 // Set residual capacities and handle GEQ supply type
857 if (_sum_supply < 0) {
858 for (ArcIt a(_graph); a != INVALID; ++a) {
860 _res_cap[_arc_idf[a]] = cap[a] - fa;
861 _res_cap[_arc_idb[a]] = fa;
862 sup[_graph.source(a)] -= fa;
863 sup[_graph.target(a)] += fa;
865 for (NodeIt n(_graph); n != INVALID; ++n) {
866 _excess[_node_id[n]] = sup[n];
868 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
870 int ra = _reverse[a];
871 _res_cap[a] = -_sum_supply + 1;
872 _res_cap[ra] = -_excess[u];
878 for (ArcIt a(_graph); a != INVALID; ++a) {
880 _res_cap[_arc_idf[a]] = cap[a] - fa;
881 _res_cap[_arc_idb[a]] = fa;
883 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
884 int ra = _reverse[a];
895 // Execute the algorithm and transform the results
896 void start(Method method) {
897 // Maximum path length for partial augment
898 const int MAX_PATH_LENGTH = 4;
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);
907 // Execute the algorithm
915 case PARTIAL_AUGMENT:
916 startAugment(MAX_PATH_LENGTH);
920 // Compute node potentials for the original costs
923 for (int j = 0; j != _res_arc_num; ++j) {
924 if (_res_cap[j] > 0) {
925 _arc_vec.push_back(IntPair(_source[j], _target[j]));
926 _cost_vec.push_back(_scost[j]);
929 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
931 typename BellmanFord<StaticDigraph, LargeCostArcMap>
932 ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
937 // Handle non-zero lower bounds
939 int limit = _first_out[_root];
940 for (int j = 0; j != limit; ++j) {
941 if (!_forward[j]) _res_cap[j] += _lower[j];
946 // Initialize a cost scaling phase
948 // Saturate arcs not satisfying the optimality condition
949 for (int u = 0; u != _res_node_num; ++u) {
950 int last_out = _first_out[u+1];
951 LargeCost pi_u = _pi[u];
952 for (int a = _first_out[u]; a != last_out; ++a) {
954 if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) {
955 Value delta = _res_cap[a];
959 _res_cap[_reverse[a]] += delta;
964 // Find active nodes (i.e. nodes with positive excess)
965 for (int u = 0; u != _res_node_num; ++u) {
966 if (_excess[u] > 0) _active_nodes.push_back(u);
969 // Initialize the next arcs
970 for (int u = 0; u != _res_node_num; ++u) {
971 _next_out[u] = _first_out[u];
975 // Early termination heuristic
976 bool earlyTermination() {
977 const double EARLY_TERM_FACTOR = 3.0;
979 // Build a static residual graph
982 for (int j = 0; j != _res_arc_num; ++j) {
983 if (_res_cap[j] > 0) {
984 _arc_vec.push_back(IntPair(_source[j], _target[j]));
985 _cost_vec.push_back(_cost[j] + 1);
988 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
990 // Run Bellman-Ford algorithm to check if the current flow is optimal
991 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
994 int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num)));
995 for (int i = 0; i < K && !done; ++i) {
996 done = bf.processNextWeakRound();
1001 // Global potential update heuristic
1002 void globalUpdate() {
1003 int bucket_end = _root + 1;
1005 // Initialize buckets
1006 for (int r = 0; r != _max_rank; ++r) {
1007 _buckets[r] = bucket_end;
1009 Value total_excess = 0;
1010 for (int i = 0; i != _res_node_num; ++i) {
1011 if (_excess[i] < 0) {
1013 _bucket_next[i] = _buckets[0];
1014 _bucket_prev[_buckets[0]] = i;
1017 total_excess += _excess[i];
1018 _rank[i] = _max_rank;
1021 if (total_excess == 0) return;
1023 // Search the buckets
1025 for ( ; r != _max_rank; ++r) {
1026 while (_buckets[r] != bucket_end) {
1027 // Remove the first node from the current bucket
1028 int u = _buckets[r];
1029 _buckets[r] = _bucket_next[u];
1031 // Search the incomming arcs of u
1032 LargeCost pi_u = _pi[u];
1033 int last_out = _first_out[u+1];
1034 for (int a = _first_out[u]; a != last_out; ++a) {
1035 int ra = _reverse[a];
1036 if (_res_cap[ra] > 0) {
1037 int v = _source[ra];
1038 int old_rank_v = _rank[v];
1039 if (r < old_rank_v) {
1040 // Compute the new rank of v
1041 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1042 int new_rank_v = old_rank_v;
1043 if (nrc < LargeCost(_max_rank))
1044 new_rank_v = r + 1 + int(nrc);
1046 // Change the rank of v
1047 if (new_rank_v < old_rank_v) {
1048 _rank[v] = new_rank_v;
1049 _next_out[v] = _first_out[v];
1051 // Remove v from its old bucket
1052 if (old_rank_v < _max_rank) {
1053 if (_buckets[old_rank_v] == v) {
1054 _buckets[old_rank_v] = _bucket_next[v];
1056 _bucket_next[_bucket_prev[v]] = _bucket_next[v];
1057 _bucket_prev[_bucket_next[v]] = _bucket_prev[v];
1061 // Insert v to its new bucket
1062 _bucket_next[v] = _buckets[new_rank_v];
1063 _bucket_prev[_buckets[new_rank_v]] = v;
1064 _buckets[new_rank_v] = v;
1070 // Finish search if there are no more active nodes
1071 if (_excess[u] > 0) {
1072 total_excess -= _excess[u];
1073 if (total_excess <= 0) break;
1076 if (total_excess <= 0) break;
1080 for (int u = 0; u != _res_node_num; ++u) {
1081 int k = std::min(_rank[u], r);
1083 _pi[u] -= _epsilon * k;
1084 _next_out[u] = _first_out[u];
1089 /// Execute the algorithm performing augment and relabel operations
1090 void startAugment(int max_length = std::numeric_limits<int>::max()) {
1091 // Paramters for heuristics
1092 const int EARLY_TERM_EPSILON_LIMIT = 1000;
1093 const double GLOBAL_UPDATE_FACTOR = 3.0;
1095 const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1096 (_res_node_num + _sup_node_num * _sup_node_num));
1097 int next_update_limit = global_update_freq;
1099 int relabel_cnt = 0;
1101 // Perform cost scaling phases
1102 std::vector<int> path;
1103 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1104 1 : _epsilon / _alpha )
1106 // Early termination heuristic
1107 if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1108 if (earlyTermination()) break;
1111 // Initialize current phase
1114 // Perform partial augment and relabel operations
1116 // Select an active node (FIFO selection)
1117 while (_active_nodes.size() > 0 &&
1118 _excess[_active_nodes.front()] <= 0) {
1119 _active_nodes.pop_front();
1121 if (_active_nodes.size() == 0) break;
1122 int start = _active_nodes.front();
1124 // Find an augmenting path from the start node
1127 while (_excess[tip] >= 0 && int(path.size()) < max_length) {
1129 LargeCost min_red_cost, rc, pi_tip = _pi[tip];
1130 int last_out = _first_out[tip+1];
1131 for (int a = _next_out[tip]; a != last_out; ++a) {
1133 if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) {
1142 min_red_cost = std::numeric_limits<LargeCost>::max();
1144 int ra = _reverse[path.back()];
1145 min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]];
1147 for (int a = _first_out[tip]; a != last_out; ++a) {
1148 rc = _cost[a] + pi_tip - _pi[_target[a]];
1149 if (_res_cap[a] > 0 && rc < min_red_cost) {
1153 _pi[tip] -= min_red_cost + _epsilon;
1154 _next_out[tip] = _first_out[tip];
1159 tip = _source[path.back()];
1166 // Augment along the found path (as much flow as possible)
1168 int pa, u, v = start;
1169 for (int i = 0; i != int(path.size()); ++i) {
1173 delta = std::min(_res_cap[pa], _excess[u]);
1174 _res_cap[pa] -= delta;
1175 _res_cap[_reverse[pa]] += delta;
1176 _excess[u] -= delta;
1177 _excess[v] += delta;
1178 if (_excess[v] > 0 && _excess[v] <= delta)
1179 _active_nodes.push_back(v);
1182 // Global update heuristic
1183 if (relabel_cnt >= next_update_limit) {
1185 next_update_limit += global_update_freq;
1191 /// Execute the algorithm performing push and relabel operations
1193 // Paramters for heuristics
1194 const int EARLY_TERM_EPSILON_LIMIT = 1000;
1195 const double GLOBAL_UPDATE_FACTOR = 2.0;
1197 const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1198 (_res_node_num + _sup_node_num * _sup_node_num));
1199 int next_update_limit = global_update_freq;
1201 int relabel_cnt = 0;
1203 // Perform cost scaling phases
1204 BoolVector hyper(_res_node_num, false);
1205 LargeCostVector hyper_cost(_res_node_num);
1206 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1207 1 : _epsilon / _alpha )
1209 // Early termination heuristic
1210 if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1211 if (earlyTermination()) break;
1214 // Initialize current phase
1217 // Perform push and relabel operations
1218 while (_active_nodes.size() > 0) {
1219 LargeCost min_red_cost, rc, pi_n;
1221 int n, t, a, last_out = _res_arc_num;
1224 // Select an active node (FIFO selection)
1225 n = _active_nodes.front();
1226 last_out = _first_out[n+1];
1229 // Perform push operations if there are admissible arcs
1230 if (_excess[n] > 0) {
1231 for (a = _next_out[n]; a != last_out; ++a) {
1232 if (_res_cap[a] > 0 &&
1233 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1234 delta = std::min(_res_cap[a], _excess[n]);
1237 // Push-look-ahead heuristic
1238 Value ahead = -_excess[t];
1239 int last_out_t = _first_out[t+1];
1240 LargeCost pi_t = _pi[t];
1241 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1242 if (_res_cap[ta] > 0 &&
1243 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1244 ahead += _res_cap[ta];
1245 if (ahead >= delta) break;
1247 if (ahead < 0) ahead = 0;
1249 // Push flow along the arc
1250 if (ahead < delta && !hyper[t]) {
1251 _res_cap[a] -= ahead;
1252 _res_cap[_reverse[a]] += ahead;
1253 _excess[n] -= ahead;
1254 _excess[t] += ahead;
1255 _active_nodes.push_front(t);
1257 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1261 _res_cap[a] -= delta;
1262 _res_cap[_reverse[a]] += delta;
1263 _excess[n] -= delta;
1264 _excess[t] += delta;
1265 if (_excess[t] > 0 && _excess[t] <= delta)
1266 _active_nodes.push_back(t);
1269 if (_excess[n] == 0) {
1278 // Relabel the node if it is still active (or hyper)
1279 if (_excess[n] > 0 || hyper[n]) {
1280 min_red_cost = hyper[n] ? -hyper_cost[n] :
1281 std::numeric_limits<LargeCost>::max();
1282 for (int a = _first_out[n]; a != last_out; ++a) {
1283 rc = _cost[a] + pi_n - _pi[_target[a]];
1284 if (_res_cap[a] > 0 && rc < min_red_cost) {
1288 _pi[n] -= min_red_cost + _epsilon;
1289 _next_out[n] = _first_out[n];
1294 // Remove nodes that are not active nor hyper
1296 while ( _active_nodes.size() > 0 &&
1297 _excess[_active_nodes.front()] <= 0 &&
1298 !hyper[_active_nodes.front()] ) {
1299 _active_nodes.pop_front();
1302 // Global update heuristic
1303 if (relabel_cnt >= next_update_limit) {
1305 for (int u = 0; u != _res_node_num; ++u)
1307 next_update_limit += global_update_freq;
1313 }; //class CostScaling
1319 #endif //LEMON_COST_SCALING_H