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");
340 // Reset data structures
345 /// The parameters of the algorithm can be specified using these
350 /// \brief Set the lower bounds on the arcs.
352 /// This function sets the lower bounds on the arcs.
353 /// If it is not used before calling \ref run(), the lower bounds
354 /// will be set to zero on all arcs.
356 /// \param map An arc map storing the lower bounds.
357 /// Its \c Value type must be convertible to the \c Value type
358 /// of the algorithm.
360 /// \return <tt>(*this)</tt>
361 template <typename LowerMap>
362 CostScaling& lowerMap(const LowerMap& map) {
364 for (ArcIt a(_graph); a != INVALID; ++a) {
365 _lower[_arc_idf[a]] = map[a];
366 _lower[_arc_idb[a]] = map[a];
371 /// \brief Set the upper bounds (capacities) on the arcs.
373 /// This function sets the upper bounds (capacities) on the arcs.
374 /// If it is not used before calling \ref run(), the upper bounds
375 /// will be set to \ref INF on all arcs (i.e. the flow value will be
376 /// unbounded from above).
378 /// \param map An arc map storing the upper bounds.
379 /// Its \c Value type must be convertible to the \c Value type
380 /// of the algorithm.
382 /// \return <tt>(*this)</tt>
383 template<typename UpperMap>
384 CostScaling& upperMap(const UpperMap& map) {
385 for (ArcIt a(_graph); a != INVALID; ++a) {
386 _upper[_arc_idf[a]] = map[a];
391 /// \brief Set the costs of the arcs.
393 /// This function sets the costs of the arcs.
394 /// If it is not used before calling \ref run(), the costs
395 /// will be set to \c 1 on all arcs.
397 /// \param map An arc map storing the costs.
398 /// Its \c Value type must be convertible to the \c Cost type
399 /// of the algorithm.
401 /// \return <tt>(*this)</tt>
402 template<typename CostMap>
403 CostScaling& costMap(const CostMap& map) {
404 for (ArcIt a(_graph); a != INVALID; ++a) {
405 _scost[_arc_idf[a]] = map[a];
406 _scost[_arc_idb[a]] = -map[a];
411 /// \brief Set the supply values of the nodes.
413 /// This function sets the supply values of the nodes.
414 /// If neither this function nor \ref stSupply() is used before
415 /// calling \ref run(), the supply of each node will be set to zero.
417 /// \param map A node map storing the supply values.
418 /// Its \c Value type must be convertible to the \c Value type
419 /// of the algorithm.
421 /// \return <tt>(*this)</tt>
422 template<typename SupplyMap>
423 CostScaling& supplyMap(const SupplyMap& map) {
424 for (NodeIt n(_graph); n != INVALID; ++n) {
425 _supply[_node_id[n]] = map[n];
430 /// \brief Set single source and target nodes and a supply value.
432 /// This function sets a single source node and a single target node
433 /// and the required flow value.
434 /// If neither this function nor \ref supplyMap() is used before
435 /// calling \ref run(), the supply of each node will be set to zero.
437 /// Using this function has the same effect as using \ref supplyMap()
438 /// with such a map in which \c k is assigned to \c s, \c -k is
439 /// assigned to \c t and all other nodes have zero supply value.
441 /// \param s The source node.
442 /// \param t The target node.
443 /// \param k The required amount of flow from node \c s to node \c t
444 /// (i.e. the supply of \c s and the demand of \c t).
446 /// \return <tt>(*this)</tt>
447 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
448 for (int i = 0; i != _res_node_num; ++i) {
451 _supply[_node_id[s]] = k;
452 _supply[_node_id[t]] = -k;
458 /// \name Execution control
459 /// The algorithm can be executed using \ref run().
463 /// \brief Run the algorithm.
465 /// This function runs the algorithm.
466 /// The paramters can be specified using functions \ref lowerMap(),
467 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
470 /// CostScaling<ListDigraph> cs(graph);
471 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
472 /// .supplyMap(sup).run();
475 /// This function can be called more than once. All the given parameters
476 /// are kept for the next call, unless \ref resetParams() or \ref reset()
477 /// is used, thus only the modified parameters have to be set again.
478 /// If the underlying digraph was also modified after the construction
479 /// of the class (or the last \ref reset() call), then the \ref reset()
480 /// function must be called.
482 /// \param method The internal method that will be used in the
483 /// algorithm. For more information, see \ref Method.
484 /// \param factor The cost scaling factor. It must be larger than one.
486 /// \return \c INFEASIBLE if no feasible flow exists,
487 /// \n \c OPTIMAL if the problem has optimal solution
488 /// (i.e. it is feasible and bounded), and the algorithm has found
489 /// optimal flow and node potentials (primal and dual solutions),
490 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
491 /// and infinite upper bound. It means that the objective function
492 /// is unbounded on that arc, however, note that it could actually be
493 /// bounded over the feasible flows, but this algroithm cannot handle
496 /// \see ProblemType, Method
497 /// \see resetParams(), reset()
498 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
500 ProblemType pt = init();
501 if (pt != OPTIMAL) return pt;
506 /// \brief Reset all the parameters that have been given before.
508 /// This function resets all the paramaters that have been given
509 /// before using functions \ref lowerMap(), \ref upperMap(),
510 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
512 /// It is useful for multiple \ref run() calls. Basically, all the given
513 /// parameters are kept for the next \ref run() call, unless
514 /// \ref resetParams() or \ref reset() is used.
515 /// If the underlying digraph was also modified after the construction
516 /// of the class or the last \ref reset() call, then the \ref reset()
517 /// function must be used, otherwise \ref resetParams() is sufficient.
521 /// CostScaling<ListDigraph> cs(graph);
524 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
525 /// .supplyMap(sup).run();
527 /// // Run again with modified cost map (resetParams() is not called,
528 /// // so only the cost map have to be set again)
530 /// cs.costMap(cost).run();
532 /// // Run again from scratch using resetParams()
533 /// // (the lower bounds will be set to zero on all arcs)
534 /// cs.resetParams();
535 /// cs.upperMap(capacity).costMap(cost)
536 /// .supplyMap(sup).run();
539 /// \return <tt>(*this)</tt>
541 /// \see reset(), run()
542 CostScaling& resetParams() {
543 for (int i = 0; i != _res_node_num; ++i) {
546 int limit = _first_out[_root];
547 for (int j = 0; j != limit; ++j) {
550 _scost[j] = _forward[j] ? 1 : -1;
552 for (int j = limit; j != _res_arc_num; ++j) {
556 _scost[_reverse[j]] = 0;
562 /// \brief Reset all the parameters that have been given before.
564 /// This function resets all the paramaters that have been given
565 /// before using functions \ref lowerMap(), \ref upperMap(),
566 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
568 /// It is useful for multiple run() calls. If this function is not
569 /// used, all the parameters given before are kept for the next
571 /// However, the underlying digraph must not be modified after this
572 /// class have been constructed, since it copies and extends the graph.
573 /// \return <tt>(*this)</tt>
574 CostScaling& reset() {
576 _node_num = countNodes(_graph);
577 _arc_num = countArcs(_graph);
578 _res_node_num = _node_num + 1;
579 _res_arc_num = 2 * (_arc_num + _node_num);
582 _first_out.resize(_res_node_num + 1);
583 _forward.resize(_res_arc_num);
584 _source.resize(_res_arc_num);
585 _target.resize(_res_arc_num);
586 _reverse.resize(_res_arc_num);
588 _lower.resize(_res_arc_num);
589 _upper.resize(_res_arc_num);
590 _scost.resize(_res_arc_num);
591 _supply.resize(_res_node_num);
593 _res_cap.resize(_res_arc_num);
594 _cost.resize(_res_arc_num);
595 _pi.resize(_res_node_num);
596 _excess.resize(_res_node_num);
597 _next_out.resize(_res_node_num);
599 _arc_vec.reserve(_res_arc_num);
600 _cost_vec.reserve(_res_arc_num);
603 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
604 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
608 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
610 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
614 _target[j] = _node_id[_graph.runningNode(a)];
616 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
620 _target[j] = _node_id[_graph.runningNode(a)];
633 _first_out[_res_node_num] = k;
634 for (ArcIt a(_graph); a != INVALID; ++a) {
635 int fi = _arc_idf[a];
636 int bi = _arc_idb[a];
648 /// \name Query Functions
649 /// The results of the algorithm can be obtained using these
651 /// The \ref run() function must be called before using them.
655 /// \brief Return the total cost of the found flow.
657 /// This function returns the total cost of the found flow.
658 /// Its complexity is O(e).
660 /// \note The return type of the function can be specified as a
661 /// template parameter. For example,
663 /// cs.totalCost<double>();
665 /// It is useful if the total cost cannot be stored in the \c Cost
666 /// type of the algorithm, which is the default return type of the
669 /// \pre \ref run() must be called before using this function.
670 template <typename Number>
671 Number totalCost() const {
673 for (ArcIt a(_graph); a != INVALID; ++a) {
675 c += static_cast<Number>(_res_cap[i]) *
676 (-static_cast<Number>(_scost[i]));
682 Cost totalCost() const {
683 return totalCost<Cost>();
687 /// \brief Return the flow on the given arc.
689 /// This function returns the flow on the given arc.
691 /// \pre \ref run() must be called before using this function.
692 Value flow(const Arc& a) const {
693 return _res_cap[_arc_idb[a]];
696 /// \brief Return the flow map (the primal solution).
698 /// This function copies the flow value on each arc into the given
699 /// map. The \c Value type of the algorithm must be convertible to
700 /// the \c Value type of the map.
702 /// \pre \ref run() must be called before using this function.
703 template <typename FlowMap>
704 void flowMap(FlowMap &map) const {
705 for (ArcIt a(_graph); a != INVALID; ++a) {
706 map.set(a, _res_cap[_arc_idb[a]]);
710 /// \brief Return the potential (dual value) of the given node.
712 /// This function returns the potential (dual value) of the
715 /// \pre \ref run() must be called before using this function.
716 Cost potential(const Node& n) const {
717 return static_cast<Cost>(_pi[_node_id[n]]);
720 /// \brief Return the potential map (the dual solution).
722 /// This function copies the potential (dual value) of each node
723 /// into the given map.
724 /// The \c Cost type of the algorithm must be convertible to the
725 /// \c Value type of the map.
727 /// \pre \ref run() must be called before using this function.
728 template <typename PotentialMap>
729 void potentialMap(PotentialMap &map) const {
730 for (NodeIt n(_graph); n != INVALID; ++n) {
731 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
739 // Initialize the algorithm
741 if (_res_node_num <= 1) return INFEASIBLE;
743 // Check the sum of supply values
745 for (int i = 0; i != _root; ++i) {
746 _sum_supply += _supply[i];
748 if (_sum_supply > 0) return INFEASIBLE;
751 // Initialize vectors
752 for (int i = 0; i != _res_node_num; ++i) {
754 _excess[i] = _supply[i];
757 // Remove infinite upper bounds and check negative arcs
758 const Value MAX = std::numeric_limits<Value>::max();
761 for (int i = 0; i != _root; ++i) {
762 last_out = _first_out[i+1];
763 for (int j = _first_out[i]; j != last_out; ++j) {
765 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
766 if (c >= MAX) return UNBOUNDED;
768 _excess[_target[j]] += c;
773 for (int i = 0; i != _root; ++i) {
774 last_out = _first_out[i+1];
775 for (int j = _first_out[i]; j != last_out; ++j) {
776 if (_forward[j] && _scost[j] < 0) {
778 if (c >= MAX) return UNBOUNDED;
780 _excess[_target[j]] += c;
785 Value ex, max_cap = 0;
786 for (int i = 0; i != _res_node_num; ++i) {
789 if (ex < 0) max_cap -= ex;
791 for (int j = 0; j != _res_arc_num; ++j) {
792 if (_upper[j] >= MAX) _upper[j] = max_cap;
795 // Initialize the large cost vector and the epsilon parameter
798 for (int i = 0; i != _root; ++i) {
799 last_out = _first_out[i+1];
800 for (int j = _first_out[i]; j != last_out; ++j) {
801 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
803 if (lc > _epsilon) _epsilon = lc;
808 // Initialize maps for Circulation and remove non-zero lower bounds
809 ConstMap<Arc, Value> low(0);
810 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
811 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
812 ValueArcMap cap(_graph), flow(_graph);
813 ValueNodeMap sup(_graph);
814 for (NodeIt n(_graph); n != INVALID; ++n) {
815 sup[n] = _supply[_node_id[n]];
818 for (ArcIt a(_graph); a != INVALID; ++a) {
821 cap[a] = _upper[j] - c;
822 sup[_graph.source(a)] -= c;
823 sup[_graph.target(a)] += c;
826 for (ArcIt a(_graph); a != INVALID; ++a) {
827 cap[a] = _upper[_arc_idf[a]];
831 // Find a feasible flow using Circulation
832 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
833 circ(_graph, low, cap, sup);
834 if (!circ.flowMap(flow).run()) return INFEASIBLE;
836 // Set residual capacities and handle GEQ supply type
837 if (_sum_supply < 0) {
838 for (ArcIt a(_graph); a != INVALID; ++a) {
840 _res_cap[_arc_idf[a]] = cap[a] - fa;
841 _res_cap[_arc_idb[a]] = fa;
842 sup[_graph.source(a)] -= fa;
843 sup[_graph.target(a)] += fa;
845 for (NodeIt n(_graph); n != INVALID; ++n) {
846 _excess[_node_id[n]] = sup[n];
848 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
850 int ra = _reverse[a];
851 _res_cap[a] = -_sum_supply + 1;
852 _res_cap[ra] = -_excess[u];
858 for (ArcIt a(_graph); a != INVALID; ++a) {
860 _res_cap[_arc_idf[a]] = cap[a] - fa;
861 _res_cap[_arc_idb[a]] = fa;
863 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
864 int ra = _reverse[a];
875 // Execute the algorithm and transform the results
876 void start(Method method) {
877 // Maximum path length for partial augment
878 const int MAX_PATH_LENGTH = 4;
880 // Execute the algorithm
888 case PARTIAL_AUGMENT:
889 startAugment(MAX_PATH_LENGTH);
893 // Compute node potentials for the original costs
896 for (int j = 0; j != _res_arc_num; ++j) {
897 if (_res_cap[j] > 0) {
898 _arc_vec.push_back(IntPair(_source[j], _target[j]));
899 _cost_vec.push_back(_scost[j]);
902 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
904 typename BellmanFord<StaticDigraph, LargeCostArcMap>
905 ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
910 // Handle non-zero lower bounds
912 int limit = _first_out[_root];
913 for (int j = 0; j != limit; ++j) {
914 if (!_forward[j]) _res_cap[j] += _lower[j];
919 /// Execute the algorithm performing augment and relabel operations
920 void startAugment(int max_length = std::numeric_limits<int>::max()) {
921 // Paramters for heuristics
922 const int BF_HEURISTIC_EPSILON_BOUND = 1000;
923 const int BF_HEURISTIC_BOUND_FACTOR = 3;
925 // Perform cost scaling phases
926 IntVector pred_arc(_res_node_num);
927 std::vector<int> path_nodes;
928 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
929 1 : _epsilon / _alpha )
931 // "Early Termination" heuristic: use Bellman-Ford algorithm
932 // to check if the current flow is optimal
933 if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
936 for (int j = 0; j != _res_arc_num; ++j) {
937 if (_res_cap[j] > 0) {
938 _arc_vec.push_back(IntPair(_source[j], _target[j]));
939 _cost_vec.push_back(_cost[j] + 1);
942 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
944 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
947 int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(_res_node_num));
948 for (int i = 0; i < K && !done; ++i)
949 done = bf.processNextWeakRound();
953 // Saturate arcs not satisfying the optimality condition
954 for (int a = 0; a != _res_arc_num; ++a) {
955 if (_res_cap[a] > 0 &&
956 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
957 Value delta = _res_cap[a];
958 _excess[_source[a]] -= delta;
959 _excess[_target[a]] += delta;
961 _res_cap[_reverse[a]] += delta;
965 // Find active nodes (i.e. nodes with positive excess)
966 for (int u = 0; u != _res_node_num; ++u) {
967 if (_excess[u] > 0) _active_nodes.push_back(u);
970 // Initialize the next arcs
971 for (int u = 0; u != _res_node_num; ++u) {
972 _next_out[u] = _first_out[u];
975 // Perform partial augment and relabel operations
977 // Select an active node (FIFO selection)
978 while (_active_nodes.size() > 0 &&
979 _excess[_active_nodes.front()] <= 0) {
980 _active_nodes.pop_front();
982 if (_active_nodes.size() == 0) break;
983 int start = _active_nodes.front();
985 path_nodes.push_back(start);
987 // Find an augmenting path from the start node
989 while (_excess[tip] >= 0 &&
990 int(path_nodes.size()) <= max_length) {
992 LargeCost min_red_cost, rc;
993 int last_out = _sum_supply < 0 ?
994 _first_out[tip+1] : _first_out[tip+1] - 1;
995 for (int a = _next_out[tip]; a != last_out; ++a) {
996 if (_res_cap[a] > 0 &&
997 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
1002 path_nodes.push_back(tip);
1008 min_red_cost = std::numeric_limits<LargeCost>::max() / 2;
1009 for (int a = _first_out[tip]; a != last_out; ++a) {
1010 rc = _cost[a] + _pi[_source[a]] - _pi[_target[a]];
1011 if (_res_cap[a] > 0 && rc < min_red_cost) {
1015 _pi[tip] -= min_red_cost + _epsilon;
1017 // Reset the next arc of tip
1018 _next_out[tip] = _first_out[tip];
1022 path_nodes.pop_back();
1023 tip = path_nodes.back();
1029 // Augment along the found path (as much flow as possible)
1031 int u, v = path_nodes.front(), pa;
1032 for (int i = 1; i < int(path_nodes.size()); ++i) {
1036 delta = std::min(_res_cap[pa], _excess[u]);
1037 _res_cap[pa] -= delta;
1038 _res_cap[_reverse[pa]] += delta;
1039 _excess[u] -= delta;
1040 _excess[v] += delta;
1041 if (_excess[v] > 0 && _excess[v] <= delta)
1042 _active_nodes.push_back(v);
1048 /// Execute the algorithm performing push and relabel operations
1050 // Paramters for heuristics
1051 const int BF_HEURISTIC_EPSILON_BOUND = 1000;
1052 const int BF_HEURISTIC_BOUND_FACTOR = 3;
1054 // Perform cost scaling phases
1055 BoolVector hyper(_res_node_num, false);
1056 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1057 1 : _epsilon / _alpha )
1059 // "Early Termination" heuristic: use Bellman-Ford algorithm
1060 // to check if the current flow is optimal
1061 if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
1064 for (int j = 0; j != _res_arc_num; ++j) {
1065 if (_res_cap[j] > 0) {
1066 _arc_vec.push_back(IntPair(_source[j], _target[j]));
1067 _cost_vec.push_back(_cost[j] + 1);
1070 _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
1072 BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
1075 int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(_res_node_num));
1076 for (int i = 0; i < K && !done; ++i)
1077 done = bf.processNextWeakRound();
1081 // Saturate arcs not satisfying the optimality condition
1082 for (int a = 0; a != _res_arc_num; ++a) {
1083 if (_res_cap[a] > 0 &&
1084 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
1085 Value delta = _res_cap[a];
1086 _excess[_source[a]] -= delta;
1087 _excess[_target[a]] += delta;
1089 _res_cap[_reverse[a]] += delta;
1093 // Find active nodes (i.e. nodes with positive excess)
1094 for (int u = 0; u != _res_node_num; ++u) {
1095 if (_excess[u] > 0) _active_nodes.push_back(u);
1098 // Initialize the next arcs
1099 for (int u = 0; u != _res_node_num; ++u) {
1100 _next_out[u] = _first_out[u];
1103 // Perform push and relabel operations
1104 while (_active_nodes.size() > 0) {
1105 LargeCost min_red_cost, rc;
1107 int n, t, a, last_out = _res_arc_num;
1109 // Select an active node (FIFO selection)
1111 n = _active_nodes.front();
1112 last_out = _sum_supply < 0 ?
1113 _first_out[n+1] : _first_out[n+1] - 1;
1115 // Perform push operations if there are admissible arcs
1116 if (_excess[n] > 0) {
1117 for (a = _next_out[n]; a != last_out; ++a) {
1118 if (_res_cap[a] > 0 &&
1119 _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
1120 delta = std::min(_res_cap[a], _excess[n]);
1123 // Push-look-ahead heuristic
1124 Value ahead = -_excess[t];
1125 int last_out_t = _sum_supply < 0 ?
1126 _first_out[t+1] : _first_out[t+1] - 1;
1127 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1128 if (_res_cap[ta] > 0 &&
1129 _cost[ta] + _pi[_source[ta]] - _pi[_target[ta]] < 0)
1130 ahead += _res_cap[ta];
1131 if (ahead >= delta) break;
1133 if (ahead < 0) ahead = 0;
1135 // Push flow along the arc
1136 if (ahead < delta) {
1137 _res_cap[a] -= ahead;
1138 _res_cap[_reverse[a]] += ahead;
1139 _excess[n] -= ahead;
1140 _excess[t] += ahead;
1141 _active_nodes.push_front(t);
1146 _res_cap[a] -= delta;
1147 _res_cap[_reverse[a]] += delta;
1148 _excess[n] -= delta;
1149 _excess[t] += delta;
1150 if (_excess[t] > 0 && _excess[t] <= delta)
1151 _active_nodes.push_back(t);
1154 if (_excess[n] == 0) {
1163 // Relabel the node if it is still active (or hyper)
1164 if (_excess[n] > 0 || hyper[n]) {
1165 min_red_cost = std::numeric_limits<LargeCost>::max() / 2;
1166 for (int a = _first_out[n]; a != last_out; ++a) {
1167 rc = _cost[a] + _pi[_source[a]] - _pi[_target[a]];
1168 if (_res_cap[a] > 0 && rc < min_red_cost) {
1172 _pi[n] -= min_red_cost + _epsilon;
1175 // Reset the next arc
1176 _next_out[n] = _first_out[n];
1179 // Remove nodes that are not active nor hyper
1181 while ( _active_nodes.size() > 0 &&
1182 _excess[_active_nodes.front()] <= 0 &&
1183 !hyper[_active_nodes.front()] ) {
1184 _active_nodes.pop_front();
1190 }; //class CostScaling
1196 #endif //LEMON_COST_SCALING_H