1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2010
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_COST_SCALING_H
20 #define LEMON_COST_SCALING_H
22 /// \ingroup min_cost_flow_algs
24 /// \brief Cost scaling algorithm for finding a minimum cost flow.
30 #include <lemon/core.h>
31 #include <lemon/maps.h>
32 #include <lemon/math.h>
33 #include <lemon/static_graph.h>
34 #include <lemon/circulation.h>
35 #include <lemon/bellman_ford.h>
39 /// \brief Default traits class of CostScaling algorithm.
41 /// Default traits class of CostScaling algorithm.
42 /// \tparam GR Digraph type.
43 /// \tparam V The number type used for flow amounts, capacity bounds
44 /// and supply values. By default it is \c int.
45 /// \tparam C The number type used for costs and potentials.
46 /// By default it is the same as \c V.
48 template <typename GR, typename V = int, typename C = V>
50 template < typename GR, typename V = int, typename C = V,
51 bool integer = std::numeric_limits<C>::is_integer >
53 struct CostScalingDefaultTraits
55 /// The type of the digraph
57 /// The type of the flow amounts, capacity bounds and supply values
59 /// The type of the arc costs
62 /// \brief The large cost type used for internal computations
64 /// The large cost type used for internal computations.
65 /// It is \c long \c long if the \c Cost type is integer,
66 /// otherwise it is \c double.
67 /// \c Cost must be convertible to \c LargeCost.
68 typedef double LargeCost;
71 // Default traits class for integer cost types
72 template <typename GR, typename V, typename C>
73 struct CostScalingDefaultTraits<GR, V, C, true>
78 #ifdef LEMON_HAVE_LONG_LONG
79 typedef long long LargeCost;
81 typedef long LargeCost;
86 /// \addtogroup min_cost_flow_algs
89 /// \brief Implementation of the Cost Scaling algorithm for
90 /// finding a \ref min_cost_flow "minimum cost flow".
92 /// \ref CostScaling implements a cost scaling algorithm that performs
93 /// push/augment and relabel operations for finding a \ref min_cost_flow
94 /// "minimum cost flow" \cite amo93networkflows, \cite goldberg90approximation,
95 /// \cite goldberg97efficient, \cite 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.
99 /// It is a polynomial algorithm, its running time complexity is
100 /// \f$O(n^2e\log(nK))\f$, where <i>K</i> denotes the maximum arc cost.
102 /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
103 /// implementations available in LEMON for solving this problem.
104 /// (For more information, see \ref min_cost_flow_algs "the module page".)
106 /// Most of the parameters of the problem (except for the digraph)
107 /// can be given using separate functions, and the algorithm can be
108 /// executed using the \ref run() function. If some parameters are not
109 /// specified, then default values will be used.
111 /// \tparam GR The digraph type the algorithm runs on.
112 /// \tparam V The number type used for flow amounts, capacity bounds
113 /// and supply values in the algorithm. By default, it is \c int.
114 /// \tparam C The number type used for costs and potentials in the
115 /// algorithm. By default, it is the same as \c V.
116 /// \tparam TR The traits class that defines various types used by the
117 /// algorithm. By default, it is \ref CostScalingDefaultTraits
118 /// "CostScalingDefaultTraits<GR, V, C>".
119 /// In most cases, this parameter should not be set directly,
120 /// consider to use the named template parameters instead.
122 /// \warning Both \c V and \c C must be signed number types.
123 /// \warning All input data (capacities, supply values, and costs) must
125 /// \warning This algorithm does not support negative costs for
126 /// arcs having infinite upper bound.
128 /// \note %CostScaling provides three different internal methods,
129 /// from which the most efficient one is used by default.
130 /// For more information, see \ref Method.
132 template <typename GR, typename V, typename C, typename TR>
134 template < typename GR, typename V = int, typename C = V,
135 typename TR = CostScalingDefaultTraits<GR, V, C> >
141 /// The type of the digraph
142 typedef typename TR::Digraph Digraph;
143 /// The type of the flow amounts, capacity bounds and supply values
144 typedef typename TR::Value Value;
145 /// The type of the arc costs
146 typedef typename TR::Cost Cost;
148 /// \brief The large cost type
150 /// The large cost type used for internal computations.
151 /// By default, it is \c long \c long if the \c Cost type is integer,
152 /// otherwise it is \c double.
153 typedef typename TR::LargeCost LargeCost;
155 /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
160 /// \brief Problem type constants for the \c run() function.
162 /// Enum type containing the problem type constants that can be
163 /// returned by the \ref run() function of the algorithm.
165 /// The problem has no feasible solution (flow).
167 /// The problem has optimal solution (i.e. it is feasible and
168 /// bounded), and the algorithm has found optimal flow and node
169 /// potentials (primal and dual solutions).
171 /// The digraph contains an arc of negative cost and infinite
172 /// upper bound. It means that the objective function is unbounded
173 /// on that arc, however, note that it could actually be bounded
174 /// over the feasible flows, but this algroithm cannot handle
179 /// \brief Constants for selecting the internal method.
181 /// Enum type containing constants for selecting the internal method
182 /// for the \ref run() function.
184 /// \ref CostScaling provides three internal methods that differ mainly
185 /// in their base operations, which are used in conjunction with the
186 /// relabel operation.
187 /// By default, the so called \ref PARTIAL_AUGMENT
188 /// "Partial Augment-Relabel" method is used, which turned out to be
189 /// the most efficient and the most robust on various test inputs.
190 /// However, the other methods can be selected using the \ref run()
191 /// function with the proper parameter.
193 /// Local push operations are used, i.e. flow is moved only on one
194 /// admissible arc at once.
196 /// Augment operations are used, i.e. flow is moved on admissible
197 /// paths from a node with excess to a node with deficit.
199 /// Partial augment operations are used, i.e. flow is moved on
200 /// admissible paths started from a node with excess, but the
201 /// lengths of these paths are limited. This method can be viewed
202 /// as a combined version of the previous two operations.
208 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
210 typedef std::vector<int> IntVector;
211 typedef std::vector<Value> ValueVector;
212 typedef std::vector<Cost> CostVector;
213 typedef std::vector<LargeCost> LargeCostVector;
214 typedef std::vector<char> BoolVector;
215 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
219 template <typename KT, typename VT>
220 class StaticVectorMap {
225 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
227 const Value& operator[](const Key& key) const {
228 return _v[StaticDigraph::id(key)];
231 Value& operator[](const Key& key) {
232 return _v[StaticDigraph::id(key)];
235 void set(const Key& key, const Value& val) {
236 _v[StaticDigraph::id(key)] = val;
240 std::vector<Value>& _v;
243 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
247 // Data related to the underlying digraph
255 // Parameters of the problem
260 // Data structures for storing the digraph
264 IntVector _first_out;
276 ValueVector _res_cap;
277 LargeCostVector _cost;
281 std::deque<int> _active_nodes;
288 IntVector _bucket_next;
289 IntVector _bucket_prev;
295 /// \brief Constant for infinite upper bounds (capacities).
297 /// Constant for infinite upper bounds (capacities).
298 /// It is \c std::numeric_limits<Value>::infinity() if available,
299 /// \c std::numeric_limits<Value>::max() otherwise.
304 /// \name Named Template Parameters
307 template <typename T>
308 struct SetLargeCostTraits : public Traits {
312 /// \brief \ref named-templ-param "Named parameter" for setting
313 /// \c LargeCost type.
315 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
316 /// type, which is used for internal computations in the algorithm.
317 /// \c Cost must be convertible to \c LargeCost.
318 template <typename T>
320 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
321 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
332 /// \brief Constructor.
334 /// The constructor of the class.
336 /// \param graph The digraph the algorithm runs on.
337 CostScaling(const GR& graph) :
338 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
339 INF(std::numeric_limits<Value>::has_infinity ?
340 std::numeric_limits<Value>::infinity() :
341 std::numeric_limits<Value>::max())
343 // Check the number types
344 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
345 "The flow type of CostScaling must be signed");
346 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
347 "The cost type of CostScaling must be signed");
349 // Reset data structures
354 /// The parameters of the algorithm can be specified using these
359 /// \brief Set the lower bounds on the arcs.
361 /// This function sets the lower bounds on the arcs.
362 /// If it is not used before calling \ref run(), the lower bounds
363 /// will be set to zero on all arcs.
365 /// \param map An arc map storing the lower bounds.
366 /// Its \c Value type must be convertible to the \c Value type
367 /// of the algorithm.
369 /// \return <tt>(*this)</tt>
370 template <typename LowerMap>
371 CostScaling& lowerMap(const LowerMap& map) {
373 for (ArcIt a(_graph); a != INVALID; ++a) {
374 _lower[_arc_idf[a]] = map[a];
375 _lower[_arc_idb[a]] = map[a];
380 /// \brief Set the upper bounds (capacities) on the arcs.
382 /// This function sets the upper bounds (capacities) on the arcs.
383 /// If it is not used before calling \ref run(), the upper bounds
384 /// will be set to \ref INF on all arcs (i.e. the flow value will be
385 /// unbounded from above).
387 /// \param map An arc map storing the upper bounds.
388 /// Its \c Value type must be convertible to the \c Value type
389 /// of the algorithm.
391 /// \return <tt>(*this)</tt>
392 template<typename UpperMap>
393 CostScaling& upperMap(const UpperMap& map) {
394 for (ArcIt a(_graph); a != INVALID; ++a) {
395 _upper[_arc_idf[a]] = map[a];
400 /// \brief Set the costs of the arcs.
402 /// This function sets the costs of the arcs.
403 /// If it is not used before calling \ref run(), the costs
404 /// will be set to \c 1 on all arcs.
406 /// \param map An arc map storing the costs.
407 /// Its \c Value type must be convertible to the \c Cost type
408 /// of the algorithm.
410 /// \return <tt>(*this)</tt>
411 template<typename CostMap>
412 CostScaling& costMap(const CostMap& map) {
413 for (ArcIt a(_graph); a != INVALID; ++a) {
414 _scost[_arc_idf[a]] = map[a];
415 _scost[_arc_idb[a]] = -map[a];
420 /// \brief Set the supply values of the nodes.
422 /// This function sets the supply values of the nodes.
423 /// If neither this function nor \ref stSupply() is used before
424 /// calling \ref run(), the supply of each node will be set to zero.
426 /// \param map A node map storing the supply values.
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 SupplyMap>
432 CostScaling& supplyMap(const SupplyMap& map) {
433 for (NodeIt n(_graph); n != INVALID; ++n) {
434 _supply[_node_id[n]] = map[n];
439 /// \brief Set single source and target nodes and a supply value.
441 /// This function sets a single source node and a single target node
442 /// and the required flow value.
443 /// If neither this function nor \ref supplyMap() is used before
444 /// calling \ref run(), the supply of each node will be set to zero.
446 /// Using this function has the same effect as using \ref supplyMap()
447 /// with a map in which \c k is assigned to \c s, \c -k is
448 /// assigned to \c t and all other nodes have zero supply value.
450 /// \param s The source node.
451 /// \param t The target node.
452 /// \param k The required amount of flow from node \c s to node \c t
453 /// (i.e. the supply of \c s and the demand of \c t).
455 /// \return <tt>(*this)</tt>
456 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
457 for (int i = 0; i != _res_node_num; ++i) {
460 _supply[_node_id[s]] = k;
461 _supply[_node_id[t]] = -k;
467 /// \name Execution control
468 /// The algorithm can be executed using \ref run().
472 /// \brief Run the algorithm.
474 /// This function runs the algorithm.
475 /// The paramters can be specified using functions \ref lowerMap(),
476 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
479 /// CostScaling<ListDigraph> cs(graph);
480 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
481 /// .supplyMap(sup).run();
484 /// This function can be called more than once. All the given parameters
485 /// are kept for the next call, unless \ref resetParams() or \ref reset()
486 /// is used, thus only the modified parameters have to be set again.
487 /// If the underlying digraph was also modified after the construction
488 /// of the class (or the last \ref reset() call), then the \ref reset()
489 /// function must be called.
491 /// \param method The internal method that will be used in the
492 /// algorithm. For more information, see \ref Method.
493 /// \param factor The cost scaling factor. It must be at least two.
495 /// \return \c INFEASIBLE if no feasible flow exists,
496 /// \n \c OPTIMAL if the problem has optimal solution
497 /// (i.e. it is feasible and bounded), and the algorithm has found
498 /// optimal flow and node potentials (primal and dual solutions),
499 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
500 /// and infinite upper bound. It means that the objective function
501 /// is unbounded on that arc, however, note that it could actually be
502 /// bounded over the feasible flows, but this algroithm cannot handle
505 /// \see ProblemType, Method
506 /// \see resetParams(), reset()
507 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
508 LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
510 ProblemType pt = init();
511 if (pt != OPTIMAL) return pt;
516 /// \brief Reset all the parameters that have been given before.
518 /// This function resets all the paramaters that have been given
519 /// before using functions \ref lowerMap(), \ref upperMap(),
520 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
522 /// It is useful for multiple \ref run() calls. Basically, all the given
523 /// parameters are kept for the next \ref run() call, unless
524 /// \ref resetParams() or \ref reset() is used.
525 /// If the underlying digraph was also modified after the construction
526 /// of the class or the last \ref reset() call, then the \ref reset()
527 /// function must be used, otherwise \ref resetParams() is sufficient.
531 /// CostScaling<ListDigraph> cs(graph);
534 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
535 /// .supplyMap(sup).run();
537 /// // Run again with modified cost map (resetParams() is not called,
538 /// // so only the cost map have to be set again)
540 /// cs.costMap(cost).run();
542 /// // Run again from scratch using resetParams()
543 /// // (the lower bounds will be set to zero on all arcs)
544 /// cs.resetParams();
545 /// cs.upperMap(capacity).costMap(cost)
546 /// .supplyMap(sup).run();
549 /// \return <tt>(*this)</tt>
551 /// \see reset(), run()
552 CostScaling& resetParams() {
553 for (int i = 0; i != _res_node_num; ++i) {
556 int limit = _first_out[_root];
557 for (int j = 0; j != limit; ++j) {
560 _scost[j] = _forward[j] ? 1 : -1;
562 for (int j = limit; j != _res_arc_num; ++j) {
566 _scost[_reverse[j]] = 0;
572 /// \brief Reset the internal data structures and all the parameters
573 /// that have been given before.
575 /// This function resets the internal data structures and all the
576 /// paramaters that have been given before using functions \ref lowerMap(),
577 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
579 /// It is useful for multiple \ref run() calls. By default, all the given
580 /// parameters are kept for the next \ref run() call, unless
581 /// \ref resetParams() or \ref reset() is used.
582 /// If the underlying digraph was also modified after the construction
583 /// of the class or the last \ref reset() call, then the \ref reset()
584 /// function must be used, otherwise \ref resetParams() is sufficient.
586 /// See \ref resetParams() for examples.
588 /// \return <tt>(*this)</tt>
590 /// \see resetParams(), run()
591 CostScaling& reset() {
593 _node_num = countNodes(_graph);
594 _arc_num = countArcs(_graph);
595 _res_node_num = _node_num + 1;
596 _res_arc_num = 2 * (_arc_num + _node_num);
599 _first_out.resize(_res_node_num + 1);
600 _forward.resize(_res_arc_num);
601 _source.resize(_res_arc_num);
602 _target.resize(_res_arc_num);
603 _reverse.resize(_res_arc_num);
605 _lower.resize(_res_arc_num);
606 _upper.resize(_res_arc_num);
607 _scost.resize(_res_arc_num);
608 _supply.resize(_res_node_num);
610 _res_cap.resize(_res_arc_num);
611 _cost.resize(_res_arc_num);
612 _pi.resize(_res_node_num);
613 _excess.resize(_res_node_num);
614 _next_out.resize(_res_node_num);
617 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
618 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
622 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
624 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
628 _target[j] = _node_id[_graph.runningNode(a)];
630 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
634 _target[j] = _node_id[_graph.runningNode(a)];
647 _first_out[_res_node_num] = k;
648 for (ArcIt a(_graph); a != INVALID; ++a) {
649 int fi = _arc_idf[a];
650 int bi = _arc_idb[a];
662 /// \name Query Functions
663 /// The results of the algorithm can be obtained using these
665 /// The \ref run() function must be called before using them.
669 /// \brief Return the total cost of the found flow.
671 /// This function returns the total cost of the found flow.
672 /// Its complexity is O(e).
674 /// \note The return type of the function can be specified as a
675 /// template parameter. For example,
677 /// cs.totalCost<double>();
679 /// It is useful if the total cost cannot be stored in the \c Cost
680 /// type of the algorithm, which is the default return type of the
683 /// \pre \ref run() must be called before using this function.
684 template <typename Number>
685 Number totalCost() const {
687 for (ArcIt a(_graph); a != INVALID; ++a) {
689 c += static_cast<Number>(_res_cap[i]) *
690 (-static_cast<Number>(_scost[i]));
696 Cost totalCost() const {
697 return totalCost<Cost>();
701 /// \brief Return the flow on the given arc.
703 /// This function returns the flow on the given arc.
705 /// \pre \ref run() must be called before using this function.
706 Value flow(const Arc& a) const {
707 return _res_cap[_arc_idb[a]];
710 /// \brief Copy the flow values (the primal solution) into the
713 /// This function copies the flow value on each arc into the given
714 /// map. The \c Value type of the algorithm must be convertible to
715 /// the \c Value type of the map.
717 /// \pre \ref run() must be called before using this function.
718 template <typename FlowMap>
719 void flowMap(FlowMap &map) const {
720 for (ArcIt a(_graph); a != INVALID; ++a) {
721 map.set(a, _res_cap[_arc_idb[a]]);
725 /// \brief Return the potential (dual value) of the given node.
727 /// This function returns the potential (dual value) of the
730 /// \pre \ref run() must be called before using this function.
731 Cost potential(const Node& n) const {
732 return static_cast<Cost>(_pi[_node_id[n]]);
735 /// \brief Copy the potential values (the dual solution) into the
738 /// This function copies the potential (dual value) of each node
739 /// into the given map.
740 /// The \c Cost type of the algorithm must be convertible to the
741 /// \c Value type of the map.
743 /// \pre \ref run() must be called before using this function.
744 template <typename PotentialMap>
745 void potentialMap(PotentialMap &map) const {
746 for (NodeIt n(_graph); n != INVALID; ++n) {
747 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
755 // Initialize the algorithm
757 if (_res_node_num <= 1) return INFEASIBLE;
759 // Check the sum of supply values
761 for (int i = 0; i != _root; ++i) {
762 _sum_supply += _supply[i];
764 if (_sum_supply > 0) return INFEASIBLE;
766 // Check lower and upper bounds
767 LEMON_DEBUG(checkBoundMaps(),
768 "Upper bounds must be greater or equal to the lower bounds");
771 // Initialize vectors
772 for (int i = 0; i != _res_node_num; ++i) {
774 _excess[i] = _supply[i];
777 // Remove infinite upper bounds and check negative arcs
778 const Value MAX = std::numeric_limits<Value>::max();
781 for (int i = 0; i != _root; ++i) {
782 last_out = _first_out[i+1];
783 for (int j = _first_out[i]; j != last_out; ++j) {
785 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
786 if (c >= MAX) return UNBOUNDED;
788 _excess[_target[j]] += c;
793 for (int i = 0; i != _root; ++i) {
794 last_out = _first_out[i+1];
795 for (int j = _first_out[i]; j != last_out; ++j) {
796 if (_forward[j] && _scost[j] < 0) {
798 if (c >= MAX) return UNBOUNDED;
800 _excess[_target[j]] += c;
805 Value ex, max_cap = 0;
806 for (int i = 0; i != _res_node_num; ++i) {
809 if (ex < 0) max_cap -= ex;
811 for (int j = 0; j != _res_arc_num; ++j) {
812 if (_upper[j] >= MAX) _upper[j] = max_cap;
815 // Initialize the large cost vector and the epsilon parameter
818 for (int i = 0; i != _root; ++i) {
819 last_out = _first_out[i+1];
820 for (int j = _first_out[i]; j != last_out; ++j) {
821 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
823 if (lc > _epsilon) _epsilon = lc;
828 // Initialize maps for Circulation and remove non-zero lower bounds
829 ConstMap<Arc, Value> low(0);
830 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
831 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
832 ValueArcMap cap(_graph), flow(_graph);
833 ValueNodeMap sup(_graph);
834 for (NodeIt n(_graph); n != INVALID; ++n) {
835 sup[n] = _supply[_node_id[n]];
838 for (ArcIt a(_graph); a != INVALID; ++a) {
841 cap[a] = _upper[j] - c;
842 sup[_graph.source(a)] -= c;
843 sup[_graph.target(a)] += c;
846 for (ArcIt a(_graph); a != INVALID; ++a) {
847 cap[a] = _upper[_arc_idf[a]];
852 for (NodeIt n(_graph); n != INVALID; ++n) {
853 if (sup[n] > 0) ++_sup_node_num;
856 // Find a feasible flow using Circulation
857 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
858 circ(_graph, low, cap, sup);
859 if (!circ.flowMap(flow).run()) return INFEASIBLE;
861 // Set residual capacities and handle GEQ supply type
862 if (_sum_supply < 0) {
863 for (ArcIt a(_graph); a != INVALID; ++a) {
865 _res_cap[_arc_idf[a]] = cap[a] - fa;
866 _res_cap[_arc_idb[a]] = fa;
867 sup[_graph.source(a)] -= fa;
868 sup[_graph.target(a)] += fa;
870 for (NodeIt n(_graph); n != INVALID; ++n) {
871 _excess[_node_id[n]] = sup[n];
873 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
875 int ra = _reverse[a];
876 _res_cap[a] = -_sum_supply + 1;
877 _res_cap[ra] = -_excess[u];
883 for (ArcIt a(_graph); a != INVALID; ++a) {
885 _res_cap[_arc_idf[a]] = cap[a] - fa;
886 _res_cap[_arc_idb[a]] = fa;
888 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
889 int ra = _reverse[a];
897 // Initialize data structures for buckets
898 _max_rank = _alpha * _res_node_num;
899 _buckets.resize(_max_rank);
900 _bucket_next.resize(_res_node_num + 1);
901 _bucket_prev.resize(_res_node_num + 1);
902 _rank.resize(_res_node_num + 1);
907 // Check if the upper bound is greater or equal to the lower bound
909 bool checkBoundMaps() {
910 for (int j = 0; j != _res_arc_num; ++j) {
911 if (_upper[j] < _lower[j]) return false;
916 // Execute the algorithm and transform the results
917 void start(Method method) {
918 const int MAX_PARTIAL_PATH_LENGTH = 4;
925 startAugment(_res_node_num - 1);
927 case PARTIAL_AUGMENT:
928 startAugment(MAX_PARTIAL_PATH_LENGTH);
932 // Compute node potentials (dual solution)
933 for (int i = 0; i != _res_node_num; ++i) {
934 _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
937 for (int i = 0; optimal && i != _res_node_num; ++i) {
938 LargeCost pi_i = _pi[i];
939 int last_out = _first_out[i+1];
940 for (int j = _first_out[i]; j != last_out; ++j) {
941 if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
949 // Compute node potentials for the original costs with BellmanFord
950 // (if it is necessary)
951 typedef std::pair<int, int> IntPair;
953 std::vector<IntPair> arc_vec;
954 std::vector<LargeCost> cost_vec;
955 LargeCostArcMap cost_map(cost_vec);
959 for (int j = 0; j != _res_arc_num; ++j) {
960 if (_res_cap[j] > 0) {
961 int u = _source[j], v = _target[j];
962 arc_vec.push_back(IntPair(u, v));
963 cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
966 sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
968 typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
973 for (int i = 0; i != _res_node_num; ++i) {
974 _pi[i] += bf.dist(sgr.node(i));
978 // Shift potentials to meet the requirements of the GEQ type
979 // optimality conditions
980 LargeCost max_pot = _pi[_root];
981 for (int i = 0; i != _res_node_num; ++i) {
982 if (_pi[i] > max_pot) max_pot = _pi[i];
985 for (int i = 0; i != _res_node_num; ++i) {
990 // Handle non-zero lower bounds
992 int limit = _first_out[_root];
993 for (int j = 0; j != limit; ++j) {
994 if (!_forward[j]) _res_cap[j] += _lower[j];
999 // Initialize a cost scaling phase
1001 // Saturate arcs not satisfying the optimality condition
1002 for (int u = 0; u != _res_node_num; ++u) {
1003 int last_out = _first_out[u+1];
1004 LargeCost pi_u = _pi[u];
1005 for (int a = _first_out[u]; a != last_out; ++a) {
1006 Value delta = _res_cap[a];
1009 if (_cost[a] + pi_u - _pi[v] < 0) {
1010 _excess[u] -= delta;
1011 _excess[v] += delta;
1013 _res_cap[_reverse[a]] += delta;
1019 // Find active nodes (i.e. nodes with positive excess)
1020 for (int u = 0; u != _res_node_num; ++u) {
1021 if (_excess[u] > 0) _active_nodes.push_back(u);
1024 // Initialize the next arcs
1025 for (int u = 0; u != _res_node_num; ++u) {
1026 _next_out[u] = _first_out[u];
1030 // Price (potential) refinement heuristic
1031 bool priceRefinement() {
1033 // Stack for stroing the topological order
1034 IntVector stack(_res_node_num);
1038 while (topologicalSort(stack, stack_top)) {
1040 // Compute node ranks in the acyclic admissible network and
1041 // store the nodes in buckets
1042 for (int i = 0; i != _res_node_num; ++i) {
1045 const int bucket_end = _root + 1;
1046 for (int r = 0; r != _max_rank; ++r) {
1047 _buckets[r] = bucket_end;
1050 for ( ; stack_top >= 0; --stack_top) {
1051 int u = stack[stack_top], v;
1052 int rank_u = _rank[u];
1054 LargeCost rc, pi_u = _pi[u];
1055 int last_out = _first_out[u+1];
1056 for (int a = _first_out[u]; a != last_out; ++a) {
1057 if (_res_cap[a] > 0) {
1059 rc = _cost[a] + pi_u - _pi[v];
1061 LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1062 if (nrc < LargeCost(_max_rank)) {
1063 int new_rank_v = rank_u + static_cast<int>(nrc);
1064 if (new_rank_v > _rank[v]) {
1065 _rank[v] = new_rank_v;
1073 top_rank = std::max(top_rank, rank_u);
1074 int bfirst = _buckets[rank_u];
1075 _bucket_next[u] = bfirst;
1076 _bucket_prev[bfirst] = u;
1077 _buckets[rank_u] = u;
1081 // Check if the current flow is epsilon-optimal
1082 if (top_rank == 0) {
1086 // Process buckets in top-down order
1087 for (int rank = top_rank; rank > 0; --rank) {
1088 while (_buckets[rank] != bucket_end) {
1089 // Remove the first node from the current bucket
1090 int u = _buckets[rank];
1091 _buckets[rank] = _bucket_next[u];
1093 // Search the outgoing arcs of u
1094 LargeCost rc, pi_u = _pi[u];
1095 int last_out = _first_out[u+1];
1096 int v, old_rank_v, new_rank_v;
1097 for (int a = _first_out[u]; a != last_out; ++a) {
1098 if (_res_cap[a] > 0) {
1100 old_rank_v = _rank[v];
1102 if (old_rank_v < rank) {
1104 // Compute the new rank of node v
1105 rc = _cost[a] + pi_u - _pi[v];
1109 LargeCost nrc = rc / _epsilon;
1111 if (nrc < LargeCost(_max_rank)) {
1112 new_rank_v = rank - 1 - static_cast<int>(nrc);
1116 // Change the rank of node v
1117 if (new_rank_v > old_rank_v) {
1118 _rank[v] = new_rank_v;
1120 // Remove v from its old bucket
1121 if (old_rank_v > 0) {
1122 if (_buckets[old_rank_v] == v) {
1123 _buckets[old_rank_v] = _bucket_next[v];
1125 int pv = _bucket_prev[v], nv = _bucket_next[v];
1126 _bucket_next[pv] = nv;
1127 _bucket_prev[nv] = pv;
1131 // Insert v into its new bucket
1132 int nv = _buckets[new_rank_v];
1133 _bucket_next[v] = nv;
1134 _bucket_prev[nv] = v;
1135 _buckets[new_rank_v] = v;
1141 // Refine potential of node u
1142 _pi[u] -= rank * _epsilon;
1151 // Find and cancel cycles in the admissible network and
1152 // determine topological order using DFS
1153 bool topologicalSort(IntVector &stack, int &stack_top) {
1154 const int MAX_CYCLE_CANCEL = 1;
1156 BoolVector reached(_res_node_num, false);
1157 BoolVector processed(_res_node_num, false);
1158 IntVector pred(_res_node_num);
1159 for (int i = 0; i != _res_node_num; ++i) {
1160 _next_out[i] = _first_out[i];
1165 for (int start = 0; start != _res_node_num; ++start) {
1166 if (reached[start]) continue;
1168 // Start DFS search from this start node
1172 // Check the outgoing arcs of the current tip node
1173 reached[tip] = true;
1174 LargeCost pi_tip = _pi[tip];
1175 int a, last_out = _first_out[tip+1];
1176 for (a = _next_out[tip]; a != last_out; ++a) {
1177 if (_res_cap[a] > 0) {
1179 if (_cost[a] + pi_tip - _pi[v] < 0) {
1181 // A new node is reached
1187 last_out = _first_out[tip+1];
1190 else if (!processed[v]) {
1195 // Find the minimum residual capacity along the cycle
1196 Value d, delta = _res_cap[a];
1197 int u, delta_node = tip;
1198 for (u = tip; u != v; ) {
1200 d = _res_cap[_next_out[u]];
1207 // Augment along the cycle
1208 _res_cap[a] -= delta;
1209 _res_cap[_reverse[a]] += delta;
1210 for (u = tip; u != v; ) {
1212 int ca = _next_out[u];
1213 _res_cap[ca] -= delta;
1214 _res_cap[_reverse[ca]] += delta;
1217 // Check the maximum number of cycle canceling
1218 if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1222 // Roll back search to delta_node
1223 if (delta_node != tip) {
1224 for (u = tip; u != delta_node; u = pred[u]) {
1228 a = _next_out[tip] + 1;
1229 last_out = _first_out[tip+1];
1237 // Step back to the previous node
1238 if (a == last_out) {
1239 processed[tip] = true;
1240 stack[++stack_top] = tip;
1243 // Finish DFS from the current start node
1252 return (cycle_cnt == 0);
1255 // Global potential update heuristic
1256 void globalUpdate() {
1257 const int bucket_end = _root + 1;
1259 // Initialize buckets
1260 for (int r = 0; r != _max_rank; ++r) {
1261 _buckets[r] = bucket_end;
1263 Value total_excess = 0;
1264 int b0 = bucket_end;
1265 for (int i = 0; i != _res_node_num; ++i) {
1266 if (_excess[i] < 0) {
1268 _bucket_next[i] = b0;
1269 _bucket_prev[b0] = i;
1272 total_excess += _excess[i];
1273 _rank[i] = _max_rank;
1276 if (total_excess == 0) return;
1279 // Search the buckets
1281 for ( ; r != _max_rank; ++r) {
1282 while (_buckets[r] != bucket_end) {
1283 // Remove the first node from the current bucket
1284 int u = _buckets[r];
1285 _buckets[r] = _bucket_next[u];
1287 // Search the incoming arcs of u
1288 LargeCost pi_u = _pi[u];
1289 int last_out = _first_out[u+1];
1290 for (int a = _first_out[u]; a != last_out; ++a) {
1291 int ra = _reverse[a];
1292 if (_res_cap[ra] > 0) {
1293 int v = _source[ra];
1294 int old_rank_v = _rank[v];
1295 if (r < old_rank_v) {
1296 // Compute the new rank of v
1297 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1298 int new_rank_v = old_rank_v;
1299 if (nrc < LargeCost(_max_rank)) {
1300 new_rank_v = r + 1 + static_cast<int>(nrc);
1303 // Change the rank of v
1304 if (new_rank_v < old_rank_v) {
1305 _rank[v] = new_rank_v;
1306 _next_out[v] = _first_out[v];
1308 // Remove v from its old bucket
1309 if (old_rank_v < _max_rank) {
1310 if (_buckets[old_rank_v] == v) {
1311 _buckets[old_rank_v] = _bucket_next[v];
1313 int pv = _bucket_prev[v], nv = _bucket_next[v];
1314 _bucket_next[pv] = nv;
1315 _bucket_prev[nv] = pv;
1319 // Insert v into its new bucket
1320 int nv = _buckets[new_rank_v];
1321 _bucket_next[v] = nv;
1322 _bucket_prev[nv] = v;
1323 _buckets[new_rank_v] = v;
1329 // Finish search if there are no more active nodes
1330 if (_excess[u] > 0) {
1331 total_excess -= _excess[u];
1332 if (total_excess <= 0) break;
1335 if (total_excess <= 0) break;
1339 for (int u = 0; u != _res_node_num; ++u) {
1340 int k = std::min(_rank[u], r);
1342 _pi[u] -= _epsilon * k;
1343 _next_out[u] = _first_out[u];
1348 /// Execute the algorithm performing augment and relabel operations
1349 void startAugment(int max_length) {
1350 // Paramters for heuristics
1351 const int PRICE_REFINEMENT_LIMIT = 2;
1352 const double GLOBAL_UPDATE_FACTOR = 1.0;
1353 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1354 (_res_node_num + _sup_node_num * _sup_node_num));
1355 int next_global_update_limit = global_update_skip;
1357 // Perform cost scaling phases
1359 BoolVector path_arc(_res_arc_num, false);
1360 int relabel_cnt = 0;
1361 int eps_phase_cnt = 0;
1362 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1363 1 : _epsilon / _alpha )
1367 // Price refinement heuristic
1368 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1369 if (priceRefinement()) continue;
1372 // Initialize current phase
1375 // Perform partial augment and relabel operations
1377 // Select an active node (FIFO selection)
1378 while (_active_nodes.size() > 0 &&
1379 _excess[_active_nodes.front()] <= 0) {
1380 _active_nodes.pop_front();
1382 if (_active_nodes.size() == 0) break;
1383 int start = _active_nodes.front();
1385 // Find an augmenting path from the start node
1387 while (int(path.size()) < max_length && _excess[tip] >= 0) {
1389 LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1390 LargeCost pi_tip = _pi[tip];
1391 int last_out = _first_out[tip+1];
1392 for (int a = _next_out[tip]; a != last_out; ++a) {
1393 if (_res_cap[a] > 0) {
1395 rc = _cost[a] + pi_tip - _pi[u];
1400 goto augment; // a cycle is found, stop path search
1406 else if (rc < min_red_cost) {
1414 int ra = _reverse[path.back()];
1416 std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1418 last_out = _next_out[tip];
1419 for (int a = _first_out[tip]; a != last_out; ++a) {
1420 if (_res_cap[a] > 0) {
1421 rc = _cost[a] + pi_tip - _pi[_target[a]];
1422 if (rc < min_red_cost) {
1427 _pi[tip] -= min_red_cost + _epsilon;
1428 _next_out[tip] = _first_out[tip];
1433 int pa = path.back();
1434 path_arc[pa] = false;
1442 // Augment along the found path (as much flow as possible)
1445 int pa, u, v = start;
1446 for (int i = 0; i != int(path.size()); ++i) {
1450 path_arc[pa] = false;
1451 delta = std::min(_res_cap[pa], _excess[u]);
1452 _res_cap[pa] -= delta;
1453 _res_cap[_reverse[pa]] += delta;
1454 _excess[u] -= delta;
1455 _excess[v] += delta;
1456 if (_excess[v] > 0 && _excess[v] <= delta) {
1457 _active_nodes.push_back(v);
1462 // Global update heuristic
1463 if (relabel_cnt >= next_global_update_limit) {
1465 next_global_update_limit += global_update_skip;
1473 /// Execute the algorithm performing push and relabel operations
1475 // Paramters for heuristics
1476 const int PRICE_REFINEMENT_LIMIT = 2;
1477 const double GLOBAL_UPDATE_FACTOR = 2.0;
1479 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1480 (_res_node_num + _sup_node_num * _sup_node_num));
1481 int next_global_update_limit = global_update_skip;
1483 // Perform cost scaling phases
1484 BoolVector hyper(_res_node_num, false);
1485 LargeCostVector hyper_cost(_res_node_num);
1486 int relabel_cnt = 0;
1487 int eps_phase_cnt = 0;
1488 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1489 1 : _epsilon / _alpha )
1493 // Price refinement heuristic
1494 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1495 if (priceRefinement()) continue;
1498 // Initialize current phase
1501 // Perform push and relabel operations
1502 while (_active_nodes.size() > 0) {
1503 LargeCost min_red_cost, rc, pi_n;
1505 int n, t, a, last_out = _res_arc_num;
1508 // Select an active node (FIFO selection)
1509 n = _active_nodes.front();
1510 last_out = _first_out[n+1];
1513 // Perform push operations if there are admissible arcs
1514 if (_excess[n] > 0) {
1515 for (a = _next_out[n]; a != last_out; ++a) {
1516 if (_res_cap[a] > 0 &&
1517 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1518 delta = std::min(_res_cap[a], _excess[n]);
1521 // Push-look-ahead heuristic
1522 Value ahead = -_excess[t];
1523 int last_out_t = _first_out[t+1];
1524 LargeCost pi_t = _pi[t];
1525 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1526 if (_res_cap[ta] > 0 &&
1527 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1528 ahead += _res_cap[ta];
1529 if (ahead >= delta) break;
1531 if (ahead < 0) ahead = 0;
1533 // Push flow along the arc
1534 if (ahead < delta && !hyper[t]) {
1535 _res_cap[a] -= ahead;
1536 _res_cap[_reverse[a]] += ahead;
1537 _excess[n] -= ahead;
1538 _excess[t] += ahead;
1539 _active_nodes.push_front(t);
1541 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1545 _res_cap[a] -= delta;
1546 _res_cap[_reverse[a]] += delta;
1547 _excess[n] -= delta;
1548 _excess[t] += delta;
1549 if (_excess[t] > 0 && _excess[t] <= delta)
1550 _active_nodes.push_back(t);
1553 if (_excess[n] == 0) {
1562 // Relabel the node if it is still active (or hyper)
1563 if (_excess[n] > 0 || hyper[n]) {
1564 min_red_cost = hyper[n] ? -hyper_cost[n] :
1565 std::numeric_limits<LargeCost>::max();
1566 for (int a = _first_out[n]; a != last_out; ++a) {
1567 if (_res_cap[a] > 0) {
1568 rc = _cost[a] + pi_n - _pi[_target[a]];
1569 if (rc < min_red_cost) {
1574 _pi[n] -= min_red_cost + _epsilon;
1575 _next_out[n] = _first_out[n];
1580 // Remove nodes that are not active nor hyper
1582 while ( _active_nodes.size() > 0 &&
1583 _excess[_active_nodes.front()] <= 0 &&
1584 !hyper[_active_nodes.front()] ) {
1585 _active_nodes.pop_front();
1588 // Global update heuristic
1589 if (relabel_cnt >= next_global_update_limit) {
1591 for (int u = 0; u != _res_node_num; ++u)
1593 next_global_update_limit += global_update_skip;
1599 }; //class CostScaling
1605 #endif //LEMON_COST_SCALING_H