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.
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 number types must be signed and all input data must
118 /// \warning This algorithm does not support negative costs for such
119 /// arcs that have infinite upper bound.
121 /// \note %CostScaling provides three different internal methods,
122 /// from which the most efficient one is used by default.
123 /// For more information, see \ref Method.
125 template <typename GR, typename V, typename C, typename TR>
127 template < typename GR, typename V = int, typename C = V,
128 typename TR = CostScalingDefaultTraits<GR, V, C> >
134 /// The type of the digraph
135 typedef typename TR::Digraph Digraph;
136 /// The type of the flow amounts, capacity bounds and supply values
137 typedef typename TR::Value Value;
138 /// The type of the arc costs
139 typedef typename TR::Cost Cost;
141 /// \brief The large cost type
143 /// The large cost type used for internal computations.
144 /// By default, it is \c long \c long if the \c Cost type is integer,
145 /// otherwise it is \c double.
146 typedef typename TR::LargeCost LargeCost;
148 /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
153 /// \brief Problem type constants for the \c run() function.
155 /// Enum type containing the problem type constants that can be
156 /// returned by the \ref run() function of the algorithm.
158 /// The problem has no feasible solution (flow).
160 /// The problem has optimal solution (i.e. it is feasible and
161 /// bounded), and the algorithm has found optimal flow and node
162 /// potentials (primal and dual solutions).
164 /// The digraph contains an arc of negative cost and infinite
165 /// upper bound. It means that the objective function is unbounded
166 /// on that arc, however, note that it could actually be bounded
167 /// over the feasible flows, but this algroithm cannot handle
172 /// \brief Constants for selecting the internal method.
174 /// Enum type containing constants for selecting the internal method
175 /// for the \ref run() function.
177 /// \ref CostScaling provides three internal methods that differ mainly
178 /// in their base operations, which are used in conjunction with the
179 /// relabel operation.
180 /// By default, the so called \ref PARTIAL_AUGMENT
181 /// "Partial Augment-Relabel" method is used, which proved to be
182 /// the most efficient and the most robust on various test inputs.
183 /// However, the other methods can be selected using the \ref run()
184 /// function with the proper parameter.
186 /// Local push operations are used, i.e. flow is moved only on one
187 /// admissible arc at once.
189 /// Augment operations are used, i.e. flow is moved on admissible
190 /// paths from a node with excess to a node with deficit.
192 /// Partial augment operations are used, i.e. flow is moved on
193 /// admissible paths started from a node with excess, but the
194 /// lengths of these paths are limited. This method can be viewed
195 /// as a combined version of the previous two operations.
201 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
203 typedef std::vector<int> IntVector;
204 typedef std::vector<char> BoolVector;
205 typedef std::vector<Value> ValueVector;
206 typedef std::vector<Cost> CostVector;
207 typedef std::vector<LargeCost> LargeCostVector;
211 template <typename KT, typename VT>
212 class StaticVectorMap {
217 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
219 const Value& operator[](const Key& key) const {
220 return _v[StaticDigraph::id(key)];
223 Value& operator[](const Key& key) {
224 return _v[StaticDigraph::id(key)];
227 void set(const Key& key, const Value& val) {
228 _v[StaticDigraph::id(key)] = val;
232 std::vector<Value>& _v;
235 typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
236 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
240 // Data related to the underlying digraph
248 // Parameters of the problem
252 // Data structures for storing the digraph
256 IntVector _first_out;
268 ValueVector _res_cap;
269 LargeCostVector _cost;
273 std::deque<int> _active_nodes;
279 // Data for a StaticDigraph structure
280 typedef std::pair<int, int> IntPair;
282 std::vector<IntPair> _arc_vec;
283 std::vector<LargeCost> _cost_vec;
284 LargeCostArcMap _cost_map;
285 LargeCostNodeMap _pi_map;
289 /// \brief Constant for infinite upper bounds (capacities).
291 /// Constant for infinite upper bounds (capacities).
292 /// It is \c std::numeric_limits<Value>::infinity() if available,
293 /// \c std::numeric_limits<Value>::max() otherwise.
298 /// \name Named Template Parameters
301 template <typename T>
302 struct SetLargeCostTraits : public Traits {
306 /// \brief \ref named-templ-param "Named parameter" for setting
307 /// \c LargeCost type.
309 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
310 /// type, which is used for internal computations in the algorithm.
311 /// \c Cost must be convertible to \c LargeCost.
312 template <typename T>
314 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
315 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
322 /// \brief Constructor.
324 /// The constructor of the class.
326 /// \param graph The digraph the algorithm runs on.
327 CostScaling(const GR& graph) :
328 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
329 _cost_map(_cost_vec), _pi_map(_pi),
330 INF(std::numeric_limits<Value>::has_infinity ?
331 std::numeric_limits<Value>::infinity() :
332 std::numeric_limits<Value>::max())
334 // Check the number types
335 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
336 "The flow type of CostScaling must be signed");
337 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
338 "The cost type of CostScaling must be signed");
341 _node_num = countNodes(_graph);
342 _arc_num = countArcs(_graph);
343 _res_node_num = _node_num + 1;
344 _res_arc_num = 2 * (_arc_num + _node_num);
347 _first_out.resize(_res_node_num + 1);
348 _forward.resize(_res_arc_num);
349 _source.resize(_res_arc_num);
350 _target.resize(_res_arc_num);
351 _reverse.resize(_res_arc_num);
353 _lower.resize(_res_arc_num);
354 _upper.resize(_res_arc_num);
355 _scost.resize(_res_arc_num);
356 _supply.resize(_res_node_num);
358 _res_cap.resize(_res_arc_num);
359 _cost.resize(_res_arc_num);
360 _pi.resize(_res_node_num);
361 _excess.resize(_res_node_num);
362 _next_out.resize(_res_node_num);
364 _arc_vec.reserve(_res_arc_num);
365 _cost_vec.reserve(_res_arc_num);
368 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
369 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
373 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
375 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
379 _target[j] = _node_id[_graph.runningNode(a)];
381 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
385 _target[j] = _node_id[_graph.runningNode(a)];
398 _first_out[_res_node_num] = k;
399 for (ArcIt a(_graph); a != INVALID; ++a) {
400 int fi = _arc_idf[a];
401 int bi = _arc_idb[a];
411 /// The parameters of the algorithm can be specified using these
416 /// \brief Set the lower bounds on the arcs.
418 /// This function sets the lower bounds on the arcs.
419 /// If it is not used before calling \ref run(), the lower bounds
420 /// will be set to zero on all arcs.
422 /// \param map An arc map storing the lower bounds.
423 /// Its \c Value type must be convertible to the \c Value type
424 /// of the algorithm.
426 /// \return <tt>(*this)</tt>
427 template <typename LowerMap>
428 CostScaling& lowerMap(const LowerMap& map) {
430 for (ArcIt a(_graph); a != INVALID; ++a) {
431 _lower[_arc_idf[a]] = map[a];
432 _lower[_arc_idb[a]] = map[a];
437 /// \brief Set the upper bounds (capacities) on the arcs.
439 /// This function sets the upper bounds (capacities) on the arcs.
440 /// If it is not used before calling \ref run(), the upper bounds
441 /// will be set to \ref INF on all arcs (i.e. the flow value will be
442 /// unbounded from above).
444 /// \param map An arc map storing the upper bounds.
445 /// Its \c Value type must be convertible to the \c Value type
446 /// of the algorithm.
448 /// \return <tt>(*this)</tt>
449 template<typename UpperMap>
450 CostScaling& upperMap(const UpperMap& map) {
451 for (ArcIt a(_graph); a != INVALID; ++a) {
452 _upper[_arc_idf[a]] = map[a];
457 /// \brief Set the costs of the arcs.
459 /// This function sets the costs of the arcs.
460 /// If it is not used before calling \ref run(), the costs
461 /// will be set to \c 1 on all arcs.
463 /// \param map An arc map storing the costs.
464 /// Its \c Value type must be convertible to the \c Cost type
465 /// of the algorithm.
467 /// \return <tt>(*this)</tt>
468 template<typename CostMap>
469 CostScaling& costMap(const CostMap& map) {
470 for (ArcIt a(_graph); a != INVALID; ++a) {
471 _scost[_arc_idf[a]] = map[a];
472 _scost[_arc_idb[a]] = -map[a];
477 /// \brief Set the supply values of the nodes.
479 /// This function sets the supply values of the nodes.
480 /// If neither this function nor \ref stSupply() is used before
481 /// calling \ref run(), the supply of each node will be set to zero.
483 /// \param map A node map storing the supply values.
484 /// Its \c Value type must be convertible to the \c Value type
485 /// of the algorithm.
487 /// \return <tt>(*this)</tt>
488 template<typename SupplyMap>
489 CostScaling& supplyMap(const SupplyMap& map) {
490 for (NodeIt n(_graph); n != INVALID; ++n) {
491 _supply[_node_id[n]] = map[n];
496 /// \brief Set single source and target nodes and a supply value.
498 /// This function sets a single source node and a single target node
499 /// and the required flow value.
500 /// If neither this function nor \ref supplyMap() is used before
501 /// calling \ref run(), the supply of each node will be set to zero.
503 /// Using this function has the same effect as using \ref supplyMap()
504 /// with such a map in which \c k is assigned to \c s, \c -k is
505 /// assigned to \c t and all other nodes have zero supply value.
507 /// \param s The source node.
508 /// \param t The target node.
509 /// \param k The required amount of flow from node \c s to node \c t
510 /// (i.e. the supply of \c s and the demand of \c t).
512 /// \return <tt>(*this)</tt>
513 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
514 for (int i = 0; i != _res_node_num; ++i) {
517 _supply[_node_id[s]] = k;
518 _supply[_node_id[t]] = -k;
524 /// \name Execution control
525 /// The algorithm can be executed using \ref run().
529 /// \brief Run the algorithm.
531 /// This function runs the algorithm.
532 /// The paramters can be specified using functions \ref lowerMap(),
533 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
536 /// CostScaling<ListDigraph> cs(graph);
537 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
538 /// .supplyMap(sup).run();
541 /// This function can be called more than once. All the parameters
542 /// that have been given are kept for the next call, unless
543 /// \ref reset() is called, thus only the modified parameters
544 /// have to be set again. See \ref reset() for examples.
545 /// However, the underlying digraph must not be modified after this
546 /// class have been constructed, since it copies and extends the graph.
548 /// \param method The internal method that will be used in the
549 /// algorithm. For more information, see \ref Method.
550 /// \param factor The cost scaling factor. It must be larger than one.
552 /// \return \c INFEASIBLE if no feasible flow exists,
553 /// \n \c OPTIMAL if the problem has optimal solution
554 /// (i.e. it is feasible and bounded), and the algorithm has found
555 /// optimal flow and node potentials (primal and dual solutions),
556 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
557 /// and infinite upper bound. It means that the objective function
558 /// is unbounded on that arc, however, note that it could actually be
559 /// bounded over the feasible flows, but this algroithm cannot handle
562 /// \see ProblemType, Method
563 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
565 ProblemType pt = init();
566 if (pt != OPTIMAL) return pt;
571 /// \brief Reset all the parameters that have been given before.
573 /// This function resets all the paramaters that have been given
574 /// before using functions \ref lowerMap(), \ref upperMap(),
575 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
577 /// It is useful for multiple run() calls. If this function is not
578 /// used, all the parameters given before are kept for the next
580 /// However, the underlying digraph must not be modified after this
581 /// class have been constructed, since it copies and extends the graph.
585 /// CostScaling<ListDigraph> cs(graph);
588 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
589 /// .supplyMap(sup).run();
591 /// // Run again with modified cost map (reset() is not called,
592 /// // so only the cost map have to be set again)
594 /// cs.costMap(cost).run();
596 /// // Run again from scratch using reset()
597 /// // (the lower bounds will be set to zero on all arcs)
599 /// cs.upperMap(capacity).costMap(cost)
600 /// .supplyMap(sup).run();
603 /// \return <tt>(*this)</tt>
604 CostScaling& reset() {
605 for (int i = 0; i != _res_node_num; ++i) {
608 int limit = _first_out[_root];
609 for (int j = 0; j != limit; ++j) {
612 _scost[j] = _forward[j] ? 1 : -1;
614 for (int j = limit; j != _res_arc_num; ++j) {
618 _scost[_reverse[j]] = 0;
626 /// \name Query Functions
627 /// The results of the algorithm can be obtained using these
629 /// The \ref run() function must be called before using them.
633 /// \brief Return the total cost of the found flow.
635 /// This function returns the total cost of the found flow.
636 /// Its complexity is O(e).
638 /// \note The return type of the function can be specified as a
639 /// template parameter. For example,
641 /// cs.totalCost<double>();
643 /// It is useful if the total cost cannot be stored in the \c Cost
644 /// type of the algorithm, which is the default return type of the
647 /// \pre \ref run() must be called before using this function.
648 template <typename Number>
649 Number totalCost() const {
651 for (ArcIt a(_graph); a != INVALID; ++a) {
653 c += static_cast<Number>(_res_cap[i]) *
654 (-static_cast<Number>(_scost[i]));
660 Cost totalCost() const {
661 return totalCost<Cost>();
665 /// \brief Return the flow on the given arc.
667 /// This function returns the flow on the given arc.
669 /// \pre \ref run() must be called before using this function.
670 Value flow(const Arc& a) const {
671 return _res_cap[_arc_idb[a]];
674 /// \brief Return the flow map (the primal solution).
676 /// This function copies the flow value on each arc into the given
677 /// map. The \c Value type of the algorithm must be convertible to
678 /// the \c Value type of the map.
680 /// \pre \ref run() must be called before using this function.
681 template <typename FlowMap>
682 void flowMap(FlowMap &map) const {
683 for (ArcIt a(_graph); a != INVALID; ++a) {
684 map.set(a, _res_cap[_arc_idb[a]]);
688 /// \brief Return the potential (dual value) of the given node.
690 /// This function returns the potential (dual value) of the
693 /// \pre \ref run() must be called before using this function.
694 Cost potential(const Node& n) const {
695 return static_cast<Cost>(_pi[_node_id[n]]);
698 /// \brief Return the potential map (the dual solution).
700 /// This function copies the potential (dual value) of each node
701 /// into the given map.
702 /// The \c Cost type of the algorithm must be convertible to the
703 /// \c Value type of the map.
705 /// \pre \ref run() must be called before using this function.
706 template <typename PotentialMap>
707 void potentialMap(PotentialMap &map) const {
708 for (NodeIt n(_graph); n != INVALID; ++n) {
709 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
717 // Initialize the algorithm
719 if (_res_node_num <= 1) return INFEASIBLE;
721 // Check the sum of supply values
723 for (int i = 0; i != _root; ++i) {
724 _sum_supply += _supply[i];
726 if (_sum_supply > 0) return INFEASIBLE;
729 // Initialize vectors
730 for (int i = 0; i != _res_node_num; ++i) {
732 _excess[i] = _supply[i];
735 // Remove infinite upper bounds and check negative arcs
736 const Value MAX = std::numeric_limits<Value>::max();
739 for (int i = 0; i != _root; ++i) {
740 last_out = _first_out[i+1];
741 for (int j = _first_out[i]; j != last_out; ++j) {
743 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
744 if (c >= MAX) return UNBOUNDED;
746 _excess[_target[j]] += c;
751 for (int i = 0; i != _root; ++i) {
752 last_out = _first_out[i+1];
753 for (int j = _first_out[i]; j != last_out; ++j) {
754 if (_forward[j] && _scost[j] < 0) {
756 if (c >= MAX) return UNBOUNDED;
758 _excess[_target[j]] += c;
763 Value ex, max_cap = 0;
764 for (int i = 0; i != _res_node_num; ++i) {
767 if (ex < 0) max_cap -= ex;
769 for (int j = 0; j != _res_arc_num; ++j) {
770 if (_upper[j] >= MAX) _upper[j] = max_cap;
773 // Initialize the large cost vector and the epsilon parameter
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) {
779 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
781 if (lc > _epsilon) _epsilon = lc;
786 // Initialize maps for Circulation and remove non-zero lower bounds
787 ConstMap<Arc, Value> low(0);
788 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
789 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
790 ValueArcMap cap(_graph), flow(_graph);
791 ValueNodeMap sup(_graph);
792 for (NodeIt n(_graph); n != INVALID; ++n) {
793 sup[n] = _supply[_node_id[n]];
796 for (ArcIt a(_graph); a != INVALID; ++a) {
799 cap[a] = _upper[j] - c;
800 sup[_graph.source(a)] -= c;
801 sup[_graph.target(a)] += c;
804 for (ArcIt a(_graph); a != INVALID; ++a) {
805 cap[a] = _upper[_arc_idf[a]];
809 // Find a feasible flow using Circulation
810 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
811 circ(_graph, low, cap, sup);
812 if (!circ.flowMap(flow).run()) return INFEASIBLE;
814 // Set residual capacities and handle GEQ supply type
815 if (_sum_supply < 0) {
816 for (ArcIt a(_graph); a != INVALID; ++a) {
818 _res_cap[_arc_idf[a]] = cap[a] - fa;
819 _res_cap[_arc_idb[a]] = fa;
820 sup[_graph.source(a)] -= fa;
821 sup[_graph.target(a)] += fa;
823 for (NodeIt n(_graph); n != INVALID; ++n) {
824 _excess[_node_id[n]] = sup[n];
826 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
828 int ra = _reverse[a];
829 _res_cap[a] = -_sum_supply + 1;
830 _res_cap[ra] = -_excess[u];
836 for (ArcIt a(_graph); a != INVALID; ++a) {
838 _res_cap[_arc_idf[a]] = cap[a] - fa;
839 _res_cap[_arc_idb[a]] = fa;
841 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
842 int ra = _reverse[a];
853 // Execute the algorithm and transform the results
854 void start(Method method) {
855 // Maximum path length for partial augment
856 const int MAX_PATH_LENGTH = 4;
858 // Execute the algorithm
866 case PARTIAL_AUGMENT:
867 startAugment(MAX_PATH_LENGTH);
871 // Compute node potentials for the original costs
874 for (int j = 0; j != _res_arc_num; ++j) {
875 if (_res_cap[j] > 0) {
876 _arc_vec.push_back(IntPair(_source[j], _target[j]));
877 _cost_vec.push_back(_scost[j]);
880 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
882 typename BellmanFord<StaticDigraph, LargeCostArcMap>
883 ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
888 // Handle non-zero lower bounds
890 int limit = _first_out[_root];
891 for (int j = 0; j != limit; ++j) {
892 if (!_forward[j]) _res_cap[j] += _lower[j];
897 /// Execute the algorithm performing augment and relabel operations
898 void startAugment(int max_length = std::numeric_limits<int>::max()) {
899 // Paramters for heuristics
900 const int BF_HEURISTIC_EPSILON_BOUND = 1000;
901 const int BF_HEURISTIC_BOUND_FACTOR = 3;
903 // Perform cost scaling phases
904 IntVector pred_arc(_res_node_num);
905 std::vector<int> path_nodes;
906 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
907 1 : _epsilon / _alpha )
909 // "Early Termination" heuristic: use Bellman-Ford algorithm
910 // to check if the current flow is optimal
911 if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
914 for (int j = 0; j != _res_arc_num; ++j) {
915 if (_res_cap[j] > 0) {
916 _arc_vec.push_back(IntPair(_source[j], _target[j]));
917 _cost_vec.push_back(_cost[j] + 1);
920 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
922 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
925 int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(_res_node_num));
926 for (int i = 0; i < K && !done; ++i)
927 done = bf.processNextWeakRound();
931 // Saturate arcs not satisfying the optimality condition
932 for (int a = 0; a != _res_arc_num; ++a) {
933 if (_res_cap[a] > 0 &&
934 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
935 Value delta = _res_cap[a];
936 _excess[_source[a]] -= delta;
937 _excess[_target[a]] += delta;
939 _res_cap[_reverse[a]] += delta;
943 // Find active nodes (i.e. nodes with positive excess)
944 for (int u = 0; u != _res_node_num; ++u) {
945 if (_excess[u] > 0) _active_nodes.push_back(u);
948 // Initialize the next arcs
949 for (int u = 0; u != _res_node_num; ++u) {
950 _next_out[u] = _first_out[u];
953 // Perform partial augment and relabel operations
955 // Select an active node (FIFO selection)
956 while (_active_nodes.size() > 0 &&
957 _excess[_active_nodes.front()] <= 0) {
958 _active_nodes.pop_front();
960 if (_active_nodes.size() == 0) break;
961 int start = _active_nodes.front();
963 path_nodes.push_back(start);
965 // Find an augmenting path from the start node
967 while (_excess[tip] >= 0 &&
968 int(path_nodes.size()) <= max_length) {
970 LargeCost min_red_cost, rc;
971 int last_out = _sum_supply < 0 ?
972 _first_out[tip+1] : _first_out[tip+1] - 1;
973 for (int a = _next_out[tip]; a != last_out; ++a) {
974 if (_res_cap[a] > 0 &&
975 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
980 path_nodes.push_back(tip);
986 min_red_cost = std::numeric_limits<LargeCost>::max() / 2;
987 for (int a = _first_out[tip]; a != last_out; ++a) {
988 rc = _cost[a] + _pi[_source[a]] - _pi[_target[a]];
989 if (_res_cap[a] > 0 && rc < min_red_cost) {
993 _pi[tip] -= min_red_cost + _epsilon;
995 // Reset the next arc of tip
996 _next_out[tip] = _first_out[tip];
1000 path_nodes.pop_back();
1001 tip = path_nodes.back();
1007 // Augment along the found path (as much flow as possible)
1009 int u, v = path_nodes.front(), pa;
1010 for (int i = 1; i < int(path_nodes.size()); ++i) {
1014 delta = std::min(_res_cap[pa], _excess[u]);
1015 _res_cap[pa] -= delta;
1016 _res_cap[_reverse[pa]] += delta;
1017 _excess[u] -= delta;
1018 _excess[v] += delta;
1019 if (_excess[v] > 0 && _excess[v] <= delta)
1020 _active_nodes.push_back(v);
1026 /// Execute the algorithm performing push and relabel operations
1028 // Paramters for heuristics
1029 const int BF_HEURISTIC_EPSILON_BOUND = 1000;
1030 const int BF_HEURISTIC_BOUND_FACTOR = 3;
1032 // Perform cost scaling phases
1033 BoolVector hyper(_res_node_num, false);
1034 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1035 1 : _epsilon / _alpha )
1037 // "Early Termination" heuristic: use Bellman-Ford algorithm
1038 // to check if the current flow is optimal
1039 if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
1042 for (int j = 0; j != _res_arc_num; ++j) {
1043 if (_res_cap[j] > 0) {
1044 _arc_vec.push_back(IntPair(_source[j], _target[j]));
1045 _cost_vec.push_back(_cost[j] + 1);
1048 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
1050 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
1053 int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(_res_node_num));
1054 for (int i = 0; i < K && !done; ++i)
1055 done = bf.processNextWeakRound();
1059 // Saturate arcs not satisfying the optimality condition
1060 for (int a = 0; a != _res_arc_num; ++a) {
1061 if (_res_cap[a] > 0 &&
1062 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
1063 Value delta = _res_cap[a];
1064 _excess[_source[a]] -= delta;
1065 _excess[_target[a]] += delta;
1067 _res_cap[_reverse[a]] += delta;
1071 // Find active nodes (i.e. nodes with positive excess)
1072 for (int u = 0; u != _res_node_num; ++u) {
1073 if (_excess[u] > 0) _active_nodes.push_back(u);
1076 // Initialize the next arcs
1077 for (int u = 0; u != _res_node_num; ++u) {
1078 _next_out[u] = _first_out[u];
1081 // Perform push and relabel operations
1082 while (_active_nodes.size() > 0) {
1083 LargeCost min_red_cost, rc;
1085 int n, t, a, last_out = _res_arc_num;
1087 // Select an active node (FIFO selection)
1089 n = _active_nodes.front();
1090 last_out = _sum_supply < 0 ?
1091 _first_out[n+1] : _first_out[n+1] - 1;
1093 // Perform push operations if there are admissible arcs
1094 if (_excess[n] > 0) {
1095 for (a = _next_out[n]; a != last_out; ++a) {
1096 if (_res_cap[a] > 0 &&
1097 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
1098 delta = std::min(_res_cap[a], _excess[n]);
1101 // Push-look-ahead heuristic
1102 Value ahead = -_excess[t];
1103 int last_out_t = _sum_supply < 0 ?
1104 _first_out[t+1] : _first_out[t+1] - 1;
1105 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1106 if (_res_cap[ta] > 0 &&
1107 _cost[ta] + _pi[_source[ta]] - _pi[_target[ta]] < 0)
1108 ahead += _res_cap[ta];
1109 if (ahead >= delta) break;
1111 if (ahead < 0) ahead = 0;
1113 // Push flow along the arc
1114 if (ahead < delta) {
1115 _res_cap[a] -= ahead;
1116 _res_cap[_reverse[a]] += ahead;
1117 _excess[n] -= ahead;
1118 _excess[t] += ahead;
1119 _active_nodes.push_front(t);
1124 _res_cap[a] -= delta;
1125 _res_cap[_reverse[a]] += delta;
1126 _excess[n] -= delta;
1127 _excess[t] += delta;
1128 if (_excess[t] > 0 && _excess[t] <= delta)
1129 _active_nodes.push_back(t);
1132 if (_excess[n] == 0) {
1141 // Relabel the node if it is still active (or hyper)
1142 if (_excess[n] > 0 || hyper[n]) {
1143 min_red_cost = std::numeric_limits<LargeCost>::max() / 2;
1144 for (int a = _first_out[n]; a != last_out; ++a) {
1145 rc = _cost[a] + _pi[_source[a]] - _pi[_target[a]];
1146 if (_res_cap[a] > 0 && rc < min_red_cost) {
1150 _pi[n] -= min_red_cost + _epsilon;
1153 // Reset the next arc
1154 _next_out[n] = _first_out[n];
1157 // Remove nodes that are not active nor hyper
1159 while ( _active_nodes.size() > 0 &&
1160 _excess[_active_nodes.front()] <= 0 &&
1161 !hyper[_active_nodes.front()] ) {
1162 _active_nodes.pop_front();
1168 }; //class CostScaling
1174 #endif //LEMON_COST_SCALING_H