3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
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.
111 /// \warning Both number types must be signed and all input data must
113 /// \warning This algorithm does not support negative costs for such
114 /// arcs that have infinite upper bound.
116 /// \note %CostScaling provides three different internal methods,
117 /// from which the most efficient one is used by default.
118 /// For more information, see \ref Method.
120 template <typename GR, typename V, typename C, typename TR>
122 template < typename GR, typename V = int, typename C = V,
123 typename TR = CostScalingDefaultTraits<GR, V, C> >
129 /// The type of the digraph
130 typedef typename TR::Digraph Digraph;
131 /// The type of the flow amounts, capacity bounds and supply values
132 typedef typename TR::Value Value;
133 /// The type of the arc costs
134 typedef typename TR::Cost Cost;
136 /// \brief The large cost type
138 /// The large cost type used for internal computations.
139 /// Using the \ref CostScalingDefaultTraits "default traits class",
140 /// it is \c long \c long if the \c Cost type is integer,
141 /// otherwise it is \c double.
142 typedef typename TR::LargeCost LargeCost;
144 /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
149 /// \brief Problem type constants for the \c run() function.
151 /// Enum type containing the problem type constants that can be
152 /// returned by the \ref run() function of the algorithm.
154 /// The problem has no feasible solution (flow).
156 /// The problem has optimal solution (i.e. it is feasible and
157 /// bounded), and the algorithm has found optimal flow and node
158 /// potentials (primal and dual solutions).
160 /// The digraph contains an arc of negative cost and infinite
161 /// upper bound. It means that the objective function is unbounded
162 /// on that arc, however, note that it could actually be bounded
163 /// over the feasible flows, but this algroithm cannot handle
168 /// \brief Constants for selecting the internal method.
170 /// Enum type containing constants for selecting the internal method
171 /// for the \ref run() function.
173 /// \ref CostScaling provides three internal methods that differ mainly
174 /// in their base operations, which are used in conjunction with the
175 /// relabel operation.
176 /// By default, the so called \ref PARTIAL_AUGMENT
177 /// "Partial Augment-Relabel" method is used, which proved to be
178 /// the most efficient and the most robust on various test inputs.
179 /// However, the other methods can be selected using the \ref run()
180 /// function with the proper parameter.
182 /// Local push operations are used, i.e. flow is moved only on one
183 /// admissible arc at once.
185 /// Augment operations are used, i.e. flow is moved on admissible
186 /// paths from a node with excess to a node with deficit.
188 /// Partial augment operations are used, i.e. flow is moved on
189 /// admissible paths started from a node with excess, but the
190 /// lengths of these paths are limited. This method can be viewed
191 /// as a combined version of the previous two operations.
197 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
199 typedef std::vector<int> IntVector;
200 typedef std::vector<Value> ValueVector;
201 typedef std::vector<Cost> CostVector;
202 typedef std::vector<LargeCost> LargeCostVector;
203 typedef std::vector<char> BoolVector;
204 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
208 template <typename KT, typename VT>
209 class StaticVectorMap {
214 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
216 const Value& operator[](const Key& key) const {
217 return _v[StaticDigraph::id(key)];
220 Value& operator[](const Key& key) {
221 return _v[StaticDigraph::id(key)];
224 void set(const Key& key, const Value& val) {
225 _v[StaticDigraph::id(key)] = val;
229 std::vector<Value>& _v;
232 typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
233 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
237 // Data related to the underlying digraph
245 // Parameters of the problem
250 // Data structures for storing the digraph
254 IntVector _first_out;
266 ValueVector _res_cap;
267 LargeCostVector _cost;
271 std::deque<int> _active_nodes;
278 IntVector _bucket_next;
279 IntVector _bucket_prev;
283 // Data for a StaticDigraph structure
284 typedef std::pair<int, int> IntPair;
286 std::vector<IntPair> _arc_vec;
287 std::vector<LargeCost> _cost_vec;
288 LargeCostArcMap _cost_map;
289 LargeCostNodeMap _pi_map;
293 /// \brief Constant for infinite upper bounds (capacities).
295 /// Constant for infinite upper bounds (capacities).
296 /// It is \c std::numeric_limits<Value>::infinity() if available,
297 /// \c std::numeric_limits<Value>::max() otherwise.
302 /// \name Named Template Parameters
305 template <typename T>
306 struct SetLargeCostTraits : public Traits {
310 /// \brief \ref named-templ-param "Named parameter" for setting
311 /// \c LargeCost type.
313 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
314 /// type, which is used for internal computations in the algorithm.
315 /// \c Cost must be convertible to \c LargeCost.
316 template <typename T>
318 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
319 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
326 /// \brief Constructor.
328 /// The constructor of the class.
330 /// \param graph The digraph the algorithm runs on.
331 CostScaling(const GR& graph) :
332 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
333 _cost_map(_cost_vec), _pi_map(_pi),
334 INF(std::numeric_limits<Value>::has_infinity ?
335 std::numeric_limits<Value>::infinity() :
336 std::numeric_limits<Value>::max())
338 // Check the number types
339 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
340 "The flow type of CostScaling must be signed");
341 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
342 "The cost type of CostScaling must be signed");
345 _node_num = countNodes(_graph);
346 _arc_num = countArcs(_graph);
347 _res_node_num = _node_num + 1;
348 _res_arc_num = 2 * (_arc_num + _node_num);
351 _first_out.resize(_res_node_num + 1);
352 _forward.resize(_res_arc_num);
353 _source.resize(_res_arc_num);
354 _target.resize(_res_arc_num);
355 _reverse.resize(_res_arc_num);
357 _lower.resize(_res_arc_num);
358 _upper.resize(_res_arc_num);
359 _scost.resize(_res_arc_num);
360 _supply.resize(_res_node_num);
362 _res_cap.resize(_res_arc_num);
363 _cost.resize(_res_arc_num);
364 _pi.resize(_res_node_num);
365 _excess.resize(_res_node_num);
366 _next_out.resize(_res_node_num);
368 _arc_vec.reserve(_res_arc_num);
369 _cost_vec.reserve(_res_arc_num);
372 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
373 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
377 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
379 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
383 _target[j] = _node_id[_graph.runningNode(a)];
385 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
389 _target[j] = _node_id[_graph.runningNode(a)];
402 _first_out[_res_node_num] = k;
403 for (ArcIt a(_graph); a != INVALID; ++a) {
404 int fi = _arc_idf[a];
405 int bi = _arc_idb[a];
415 /// The parameters of the algorithm can be specified using these
420 /// \brief Set the lower bounds on the arcs.
422 /// This function sets the lower bounds on the arcs.
423 /// If it is not used before calling \ref run(), the lower bounds
424 /// will be set to zero on all arcs.
426 /// \param map An arc map storing the lower bounds.
427 /// Its \c Value type must be convertible to the \c Value type
428 /// of the algorithm.
430 /// \return <tt>(*this)</tt>
431 template <typename LowerMap>
432 CostScaling& lowerMap(const LowerMap& map) {
434 for (ArcIt a(_graph); a != INVALID; ++a) {
435 _lower[_arc_idf[a]] = map[a];
436 _lower[_arc_idb[a]] = map[a];
441 /// \brief Set the upper bounds (capacities) on the arcs.
443 /// This function sets the upper bounds (capacities) on the arcs.
444 /// If it is not used before calling \ref run(), the upper bounds
445 /// will be set to \ref INF on all arcs (i.e. the flow value will be
446 /// unbounded from above).
448 /// \param map An arc map storing the upper bounds.
449 /// Its \c Value type must be convertible to the \c Value type
450 /// of the algorithm.
452 /// \return <tt>(*this)</tt>
453 template<typename UpperMap>
454 CostScaling& upperMap(const UpperMap& map) {
455 for (ArcIt a(_graph); a != INVALID; ++a) {
456 _upper[_arc_idf[a]] = map[a];
461 /// \brief Set the costs of the arcs.
463 /// This function sets the costs of the arcs.
464 /// If it is not used before calling \ref run(), the costs
465 /// will be set to \c 1 on all arcs.
467 /// \param map An arc map storing the costs.
468 /// Its \c Value type must be convertible to the \c Cost type
469 /// of the algorithm.
471 /// \return <tt>(*this)</tt>
472 template<typename CostMap>
473 CostScaling& costMap(const CostMap& map) {
474 for (ArcIt a(_graph); a != INVALID; ++a) {
475 _scost[_arc_idf[a]] = map[a];
476 _scost[_arc_idb[a]] = -map[a];
481 /// \brief Set the supply values of the nodes.
483 /// This function sets the supply values of the nodes.
484 /// If neither this function nor \ref stSupply() is used before
485 /// calling \ref run(), the supply of each node will be set to zero.
487 /// \param map A node map storing the supply values.
488 /// Its \c Value type must be convertible to the \c Value type
489 /// of the algorithm.
491 /// \return <tt>(*this)</tt>
492 template<typename SupplyMap>
493 CostScaling& supplyMap(const SupplyMap& map) {
494 for (NodeIt n(_graph); n != INVALID; ++n) {
495 _supply[_node_id[n]] = map[n];
500 /// \brief Set single source and target nodes and a supply value.
502 /// This function sets a single source node and a single target node
503 /// and the required flow value.
504 /// If neither this function nor \ref supplyMap() is used before
505 /// calling \ref run(), the supply of each node will be set to zero.
507 /// Using this function has the same effect as using \ref supplyMap()
508 /// with such a map in which \c k is assigned to \c s, \c -k is
509 /// assigned to \c t and all other nodes have zero supply value.
511 /// \param s The source node.
512 /// \param t The target node.
513 /// \param k The required amount of flow from node \c s to node \c t
514 /// (i.e. the supply of \c s and the demand of \c t).
516 /// \return <tt>(*this)</tt>
517 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
518 for (int i = 0; i != _res_node_num; ++i) {
521 _supply[_node_id[s]] = k;
522 _supply[_node_id[t]] = -k;
528 /// \name Execution control
529 /// The algorithm can be executed using \ref run().
533 /// \brief Run the algorithm.
535 /// This function runs the algorithm.
536 /// The paramters can be specified using functions \ref lowerMap(),
537 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
540 /// CostScaling<ListDigraph> cs(graph);
541 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
542 /// .supplyMap(sup).run();
545 /// This function can be called more than once. All the parameters
546 /// that have been given are kept for the next call, unless
547 /// \ref reset() is called, thus only the modified parameters
548 /// have to be set again. See \ref reset() for examples.
549 /// However, the underlying digraph must not be modified after this
550 /// class have been constructed, since it copies and extends the graph.
552 /// \param method The internal method that will be used in the
553 /// algorithm. For more information, see \ref Method.
554 /// \param factor The cost scaling factor. It must be larger than one.
556 /// \return \c INFEASIBLE if no feasible flow exists,
557 /// \n \c OPTIMAL if the problem has optimal solution
558 /// (i.e. it is feasible and bounded), and the algorithm has found
559 /// optimal flow and node potentials (primal and dual solutions),
560 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
561 /// and infinite upper bound. It means that the objective function
562 /// is unbounded on that arc, however, note that it could actually be
563 /// bounded over the feasible flows, but this algroithm cannot handle
566 /// \see ProblemType, Method
567 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
569 ProblemType pt = init();
570 if (pt != OPTIMAL) return pt;
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.
589 /// CostScaling<ListDigraph> cs(graph);
592 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
593 /// .supplyMap(sup).run();
595 /// // Run again with modified cost map (reset() is not called,
596 /// // so only the cost map have to be set again)
598 /// cs.costMap(cost).run();
600 /// // Run again from scratch using reset()
601 /// // (the lower bounds will be set to zero on all arcs)
603 /// cs.upperMap(capacity).costMap(cost)
604 /// .supplyMap(sup).run();
607 /// \return <tt>(*this)</tt>
608 CostScaling& reset() {
609 for (int i = 0; i != _res_node_num; ++i) {
612 int limit = _first_out[_root];
613 for (int j = 0; j != limit; ++j) {
616 _scost[j] = _forward[j] ? 1 : -1;
618 for (int j = limit; j != _res_arc_num; ++j) {
622 _scost[_reverse[j]] = 0;
630 /// \name Query Functions
631 /// The results of the algorithm can be obtained using these
633 /// The \ref run() function must be called before using them.
637 /// \brief Return the total cost of the found flow.
639 /// This function returns the total cost of the found flow.
640 /// Its complexity is O(e).
642 /// \note The return type of the function can be specified as a
643 /// template parameter. For example,
645 /// cs.totalCost<double>();
647 /// It is useful if the total cost cannot be stored in the \c Cost
648 /// type of the algorithm, which is the default return type of the
651 /// \pre \ref run() must be called before using this function.
652 template <typename Number>
653 Number totalCost() const {
655 for (ArcIt a(_graph); a != INVALID; ++a) {
657 c += static_cast<Number>(_res_cap[i]) *
658 (-static_cast<Number>(_scost[i]));
664 Cost totalCost() const {
665 return totalCost<Cost>();
669 /// \brief Return the flow on the given arc.
671 /// This function returns the flow on the given arc.
673 /// \pre \ref run() must be called before using this function.
674 Value flow(const Arc& a) const {
675 return _res_cap[_arc_idb[a]];
678 /// \brief Return the flow map (the primal solution).
680 /// This function copies the flow value on each arc into the given
681 /// map. The \c Value type of the algorithm must be convertible to
682 /// the \c Value type of the map.
684 /// \pre \ref run() must be called before using this function.
685 template <typename FlowMap>
686 void flowMap(FlowMap &map) const {
687 for (ArcIt a(_graph); a != INVALID; ++a) {
688 map.set(a, _res_cap[_arc_idb[a]]);
692 /// \brief Return the potential (dual value) of the given node.
694 /// This function returns the potential (dual value) of the
697 /// \pre \ref run() must be called before using this function.
698 Cost potential(const Node& n) const {
699 return static_cast<Cost>(_pi[_node_id[n]]);
702 /// \brief Return the potential map (the dual solution).
704 /// This function copies the potential (dual value) of each node
705 /// into the given map.
706 /// The \c Cost type of the algorithm must be convertible to the
707 /// \c Value type of the map.
709 /// \pre \ref run() must be called before using this function.
710 template <typename PotentialMap>
711 void potentialMap(PotentialMap &map) const {
712 for (NodeIt n(_graph); n != INVALID; ++n) {
713 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
721 // Initialize the algorithm
723 if (_res_node_num <= 1) return INFEASIBLE;
725 // Check the sum of supply values
727 for (int i = 0; i != _root; ++i) {
728 _sum_supply += _supply[i];
730 if (_sum_supply > 0) return INFEASIBLE;
733 // Initialize vectors
734 for (int i = 0; i != _res_node_num; ++i) {
736 _excess[i] = _supply[i];
739 // Remove infinite upper bounds and check negative arcs
740 const Value MAX = std::numeric_limits<Value>::max();
743 for (int i = 0; i != _root; ++i) {
744 last_out = _first_out[i+1];
745 for (int j = _first_out[i]; j != last_out; ++j) {
747 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
748 if (c >= MAX) return UNBOUNDED;
750 _excess[_target[j]] += c;
755 for (int i = 0; i != _root; ++i) {
756 last_out = _first_out[i+1];
757 for (int j = _first_out[i]; j != last_out; ++j) {
758 if (_forward[j] && _scost[j] < 0) {
760 if (c >= MAX) return UNBOUNDED;
762 _excess[_target[j]] += c;
767 Value ex, max_cap = 0;
768 for (int i = 0; i != _res_node_num; ++i) {
771 if (ex < 0) max_cap -= ex;
773 for (int j = 0; j != _res_arc_num; ++j) {
774 if (_upper[j] >= MAX) _upper[j] = max_cap;
777 // Initialize the large cost vector and the epsilon parameter
780 for (int i = 0; i != _root; ++i) {
781 last_out = _first_out[i+1];
782 for (int j = _first_out[i]; j != last_out; ++j) {
783 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
785 if (lc > _epsilon) _epsilon = lc;
790 // Initialize maps for Circulation and remove non-zero lower bounds
791 ConstMap<Arc, Value> low(0);
792 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
793 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
794 ValueArcMap cap(_graph), flow(_graph);
795 ValueNodeMap sup(_graph);
796 for (NodeIt n(_graph); n != INVALID; ++n) {
797 sup[n] = _supply[_node_id[n]];
800 for (ArcIt a(_graph); a != INVALID; ++a) {
803 cap[a] = _upper[j] - c;
804 sup[_graph.source(a)] -= c;
805 sup[_graph.target(a)] += c;
808 for (ArcIt a(_graph); a != INVALID; ++a) {
809 cap[a] = _upper[_arc_idf[a]];
814 for (NodeIt n(_graph); n != INVALID; ++n) {
815 if (sup[n] > 0) ++_sup_node_num;
818 // Find a feasible flow using Circulation
819 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
820 circ(_graph, low, cap, sup);
821 if (!circ.flowMap(flow).run()) return INFEASIBLE;
823 // Set residual capacities and handle GEQ supply type
824 if (_sum_supply < 0) {
825 for (ArcIt a(_graph); a != INVALID; ++a) {
827 _res_cap[_arc_idf[a]] = cap[a] - fa;
828 _res_cap[_arc_idb[a]] = fa;
829 sup[_graph.source(a)] -= fa;
830 sup[_graph.target(a)] += fa;
832 for (NodeIt n(_graph); n != INVALID; ++n) {
833 _excess[_node_id[n]] = sup[n];
835 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
837 int ra = _reverse[a];
838 _res_cap[a] = -_sum_supply + 1;
839 _res_cap[ra] = -_excess[u];
845 for (ArcIt a(_graph); a != INVALID; ++a) {
847 _res_cap[_arc_idf[a]] = cap[a] - fa;
848 _res_cap[_arc_idb[a]] = fa;
850 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
851 int ra = _reverse[a];
862 // Execute the algorithm and transform the results
863 void start(Method method) {
864 // Maximum path length for partial augment
865 const int MAX_PATH_LENGTH = 4;
867 // Initialize data structures for buckets
868 _max_rank = _alpha * _res_node_num;
869 _buckets.resize(_max_rank);
870 _bucket_next.resize(_res_node_num + 1);
871 _bucket_prev.resize(_res_node_num + 1);
872 _rank.resize(_res_node_num + 1);
874 // Execute the algorithm
882 case PARTIAL_AUGMENT:
883 startAugment(MAX_PATH_LENGTH);
887 // Compute node potentials for the original costs
890 for (int j = 0; j != _res_arc_num; ++j) {
891 if (_res_cap[j] > 0) {
892 _arc_vec.push_back(IntPair(_source[j], _target[j]));
893 _cost_vec.push_back(_scost[j]);
896 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
898 typename BellmanFord<StaticDigraph, LargeCostArcMap>
899 ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
904 // Handle non-zero lower bounds
906 int limit = _first_out[_root];
907 for (int j = 0; j != limit; ++j) {
908 if (!_forward[j]) _res_cap[j] += _lower[j];
913 // Initialize a cost scaling phase
915 // Saturate arcs not satisfying the optimality condition
916 for (int u = 0; u != _res_node_num; ++u) {
917 int last_out = _first_out[u+1];
918 LargeCost pi_u = _pi[u];
919 for (int a = _first_out[u]; a != last_out; ++a) {
921 if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) {
922 Value delta = _res_cap[a];
926 _res_cap[_reverse[a]] += delta;
931 // Find active nodes (i.e. nodes with positive excess)
932 for (int u = 0; u != _res_node_num; ++u) {
933 if (_excess[u] > 0) _active_nodes.push_back(u);
936 // Initialize the next arcs
937 for (int u = 0; u != _res_node_num; ++u) {
938 _next_out[u] = _first_out[u];
942 // Early termination heuristic
943 bool earlyTermination() {
944 const double EARLY_TERM_FACTOR = 3.0;
946 // Build a static residual graph
949 for (int j = 0; j != _res_arc_num; ++j) {
950 if (_res_cap[j] > 0) {
951 _arc_vec.push_back(IntPair(_source[j], _target[j]));
952 _cost_vec.push_back(_cost[j] + 1);
955 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
957 // Run Bellman-Ford algorithm to check if the current flow is optimal
958 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
961 int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num)));
962 for (int i = 0; i < K && !done; ++i) {
963 done = bf.processNextWeakRound();
968 // Global potential update heuristic
969 void globalUpdate() {
970 int bucket_end = _root + 1;
972 // Initialize buckets
973 for (int r = 0; r != _max_rank; ++r) {
974 _buckets[r] = bucket_end;
976 Value total_excess = 0;
977 for (int i = 0; i != _res_node_num; ++i) {
978 if (_excess[i] < 0) {
980 _bucket_next[i] = _buckets[0];
981 _bucket_prev[_buckets[0]] = i;
984 total_excess += _excess[i];
985 _rank[i] = _max_rank;
988 if (total_excess == 0) return;
990 // Search the buckets
992 for ( ; r != _max_rank; ++r) {
993 while (_buckets[r] != bucket_end) {
994 // Remove the first node from the current bucket
996 _buckets[r] = _bucket_next[u];
998 // Search the incomming arcs of u
999 LargeCost pi_u = _pi[u];
1000 int last_out = _first_out[u+1];
1001 for (int a = _first_out[u]; a != last_out; ++a) {
1002 int ra = _reverse[a];
1003 if (_res_cap[ra] > 0) {
1004 int v = _source[ra];
1005 int old_rank_v = _rank[v];
1006 if (r < old_rank_v) {
1007 // Compute the new rank of v
1008 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1009 int new_rank_v = old_rank_v;
1010 if (nrc < LargeCost(_max_rank))
1011 new_rank_v = r + 1 + int(nrc);
1013 // Change the rank of v
1014 if (new_rank_v < old_rank_v) {
1015 _rank[v] = new_rank_v;
1016 _next_out[v] = _first_out[v];
1018 // Remove v from its old bucket
1019 if (old_rank_v < _max_rank) {
1020 if (_buckets[old_rank_v] == v) {
1021 _buckets[old_rank_v] = _bucket_next[v];
1023 _bucket_next[_bucket_prev[v]] = _bucket_next[v];
1024 _bucket_prev[_bucket_next[v]] = _bucket_prev[v];
1028 // Insert v to its new bucket
1029 _bucket_next[v] = _buckets[new_rank_v];
1030 _bucket_prev[_buckets[new_rank_v]] = v;
1031 _buckets[new_rank_v] = v;
1037 // Finish search if there are no more active nodes
1038 if (_excess[u] > 0) {
1039 total_excess -= _excess[u];
1040 if (total_excess <= 0) break;
1043 if (total_excess <= 0) break;
1047 for (int u = 0; u != _res_node_num; ++u) {
1048 int k = std::min(_rank[u], r);
1050 _pi[u] -= _epsilon * k;
1051 _next_out[u] = _first_out[u];
1056 /// Execute the algorithm performing augment and relabel operations
1057 void startAugment(int max_length = std::numeric_limits<int>::max()) {
1058 // Paramters for heuristics
1059 const int EARLY_TERM_EPSILON_LIMIT = 1000;
1060 const double GLOBAL_UPDATE_FACTOR = 3.0;
1062 const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1063 (_res_node_num + _sup_node_num * _sup_node_num));
1064 int next_update_limit = global_update_freq;
1066 int relabel_cnt = 0;
1068 // Perform cost scaling phases
1069 std::vector<int> path;
1070 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1071 1 : _epsilon / _alpha )
1073 // Early termination heuristic
1074 if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1075 if (earlyTermination()) break;
1078 // Initialize current phase
1081 // Perform partial augment and relabel operations
1083 // Select an active node (FIFO selection)
1084 while (_active_nodes.size() > 0 &&
1085 _excess[_active_nodes.front()] <= 0) {
1086 _active_nodes.pop_front();
1088 if (_active_nodes.size() == 0) break;
1089 int start = _active_nodes.front();
1091 // Find an augmenting path from the start node
1094 while (_excess[tip] >= 0 && int(path.size()) < max_length) {
1096 LargeCost min_red_cost, rc, pi_tip = _pi[tip];
1097 int last_out = _first_out[tip+1];
1098 for (int a = _next_out[tip]; a != last_out; ++a) {
1100 if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) {
1109 min_red_cost = std::numeric_limits<LargeCost>::max();
1111 int ra = _reverse[path.back()];
1112 min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]];
1114 for (int a = _first_out[tip]; a != last_out; ++a) {
1115 rc = _cost[a] + pi_tip - _pi[_target[a]];
1116 if (_res_cap[a] > 0 && rc < min_red_cost) {
1120 _pi[tip] -= min_red_cost + _epsilon;
1121 _next_out[tip] = _first_out[tip];
1126 tip = _source[path.back()];
1133 // Augment along the found path (as much flow as possible)
1135 int pa, u, v = start;
1136 for (int i = 0; i != int(path.size()); ++i) {
1140 delta = std::min(_res_cap[pa], _excess[u]);
1141 _res_cap[pa] -= delta;
1142 _res_cap[_reverse[pa]] += delta;
1143 _excess[u] -= delta;
1144 _excess[v] += delta;
1145 if (_excess[v] > 0 && _excess[v] <= delta)
1146 _active_nodes.push_back(v);
1149 // Global update heuristic
1150 if (relabel_cnt >= next_update_limit) {
1152 next_update_limit += global_update_freq;
1158 /// Execute the algorithm performing push and relabel operations
1160 // Paramters for heuristics
1161 const int EARLY_TERM_EPSILON_LIMIT = 1000;
1162 const double GLOBAL_UPDATE_FACTOR = 2.0;
1164 const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1165 (_res_node_num + _sup_node_num * _sup_node_num));
1166 int next_update_limit = global_update_freq;
1168 int relabel_cnt = 0;
1170 // Perform cost scaling phases
1171 BoolVector hyper(_res_node_num, false);
1172 LargeCostVector hyper_cost(_res_node_num);
1173 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1174 1 : _epsilon / _alpha )
1176 // Early termination heuristic
1177 if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1178 if (earlyTermination()) break;
1181 // Initialize current phase
1184 // Perform push and relabel operations
1185 while (_active_nodes.size() > 0) {
1186 LargeCost min_red_cost, rc, pi_n;
1188 int n, t, a, last_out = _res_arc_num;
1191 // Select an active node (FIFO selection)
1192 n = _active_nodes.front();
1193 last_out = _first_out[n+1];
1196 // Perform push operations if there are admissible arcs
1197 if (_excess[n] > 0) {
1198 for (a = _next_out[n]; a != last_out; ++a) {
1199 if (_res_cap[a] > 0 &&
1200 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1201 delta = std::min(_res_cap[a], _excess[n]);
1204 // Push-look-ahead heuristic
1205 Value ahead = -_excess[t];
1206 int last_out_t = _first_out[t+1];
1207 LargeCost pi_t = _pi[t];
1208 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1209 if (_res_cap[ta] > 0 &&
1210 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1211 ahead += _res_cap[ta];
1212 if (ahead >= delta) break;
1214 if (ahead < 0) ahead = 0;
1216 // Push flow along the arc
1217 if (ahead < delta && !hyper[t]) {
1218 _res_cap[a] -= ahead;
1219 _res_cap[_reverse[a]] += ahead;
1220 _excess[n] -= ahead;
1221 _excess[t] += ahead;
1222 _active_nodes.push_front(t);
1224 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1228 _res_cap[a] -= delta;
1229 _res_cap[_reverse[a]] += delta;
1230 _excess[n] -= delta;
1231 _excess[t] += delta;
1232 if (_excess[t] > 0 && _excess[t] <= delta)
1233 _active_nodes.push_back(t);
1236 if (_excess[n] == 0) {
1245 // Relabel the node if it is still active (or hyper)
1246 if (_excess[n] > 0 || hyper[n]) {
1247 min_red_cost = hyper[n] ? -hyper_cost[n] :
1248 std::numeric_limits<LargeCost>::max();
1249 for (int a = _first_out[n]; a != last_out; ++a) {
1250 rc = _cost[a] + pi_n - _pi[_target[a]];
1251 if (_res_cap[a] > 0 && rc < min_red_cost) {
1255 _pi[n] -= min_red_cost + _epsilon;
1256 _next_out[n] = _first_out[n];
1261 // Remove nodes that are not active nor hyper
1263 while ( _active_nodes.size() > 0 &&
1264 _excess[_active_nodes.front()] <= 0 &&
1265 !hyper[_active_nodes.front()] ) {
1266 _active_nodes.pop_front();
1269 // Global update heuristic
1270 if (relabel_cnt >= next_update_limit) {
1272 for (int u = 0; u != _res_node_num; ++u)
1274 next_update_limit += global_update_freq;
1280 }; //class CostScaling
1286 #endif //LEMON_COST_SCALING_H