1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2010
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_COST_SCALING_H
20 #define LEMON_COST_SCALING_H
22 /// \ingroup min_cost_flow_algs
24 /// \brief Cost scaling algorithm for finding a minimum cost flow.
30 #include <lemon/core.h>
31 #include <lemon/maps.h>
32 #include <lemon/math.h>
33 #include <lemon/static_graph.h>
34 #include <lemon/circulation.h>
35 #include <lemon/bellman_ford.h>
39 /// \brief Default traits class of CostScaling algorithm.
41 /// Default traits class of CostScaling algorithm.
42 /// \tparam GR Digraph type.
43 /// \tparam V The number type used for flow amounts, capacity bounds
44 /// and supply values. By default it is \c int.
45 /// \tparam C The number type used for costs and potentials.
46 /// By default it is the same as \c V.
48 template <typename GR, typename V = int, typename C = V>
50 template < typename GR, typename V = int, typename C = V,
51 bool integer = std::numeric_limits<C>::is_integer >
53 struct CostScalingDefaultTraits
55 /// The type of the digraph
57 /// The type of the flow amounts, capacity bounds and supply values
59 /// The type of the arc costs
62 /// \brief The large cost type used for internal computations
64 /// The large cost type used for internal computations.
65 /// It is \c long \c long if the \c Cost type is integer,
66 /// otherwise it is \c double.
67 /// \c Cost must be convertible to \c LargeCost.
68 typedef double LargeCost;
71 // Default traits class for integer cost types
72 template <typename GR, typename V, typename C>
73 struct CostScalingDefaultTraits<GR, V, C, true>
78 #ifdef LEMON_HAVE_LONG_LONG
79 typedef long long LargeCost;
81 typedef long LargeCost;
86 /// \addtogroup min_cost_flow_algs
89 /// \brief Implementation of the Cost Scaling algorithm for
90 /// finding a \ref min_cost_flow "minimum cost flow".
92 /// \ref CostScaling implements a cost scaling algorithm that performs
93 /// push/augment and relabel operations for finding a \ref min_cost_flow
94 /// "minimum cost flow" \ref amo93networkflows, \ref goldberg90approximation,
95 /// \ref goldberg97efficient, \ref bunnagel98efficient.
96 /// It is a highly efficient primal-dual solution method, which
97 /// can be viewed as the generalization of the \ref Preflow
98 /// "preflow push-relabel" algorithm for the maximum flow problem.
100 /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
101 /// implementations available in LEMON for solving this problem.
102 /// (For more information, see \ref min_cost_flow_algs "the module page".)
104 /// Most of the parameters of the problem (except for the digraph)
105 /// can be given using separate functions, and the algorithm can be
106 /// executed using the \ref run() function. If some parameters are not
107 /// specified, then default values will be used.
109 /// \tparam GR The digraph type the algorithm runs on.
110 /// \tparam V The number type used for flow amounts, capacity bounds
111 /// and supply values in the algorithm. By default, it is \c int.
112 /// \tparam C The number type used for costs and potentials in the
113 /// algorithm. By default, it is the same as \c V.
114 /// \tparam TR The traits class that defines various types used by the
115 /// algorithm. By default, it is \ref CostScalingDefaultTraits
116 /// "CostScalingDefaultTraits<GR, V, C>".
117 /// In most cases, this parameter should not be set directly,
118 /// consider to use the named template parameters instead.
120 /// \warning Both \c V and \c C must be signed number types.
121 /// \warning All input data (capacities, supply values, and costs) must
123 /// \warning This algorithm does not support negative costs for
124 /// arcs having infinite upper bound.
126 /// \note %CostScaling provides three different internal methods,
127 /// from which the most efficient one is used by default.
128 /// For more information, see \ref Method.
130 template <typename GR, typename V, typename C, typename TR>
132 template < typename GR, typename V = int, typename C = V,
133 typename TR = CostScalingDefaultTraits<GR, V, C> >
139 /// The type of the digraph
140 typedef typename TR::Digraph Digraph;
141 /// The type of the flow amounts, capacity bounds and supply values
142 typedef typename TR::Value Value;
143 /// The type of the arc costs
144 typedef typename TR::Cost Cost;
146 /// \brief The large cost type
148 /// The large cost type used for internal computations.
149 /// By default, it is \c long \c long if the \c Cost type is integer,
150 /// otherwise it is \c double.
151 typedef typename TR::LargeCost LargeCost;
153 /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
158 /// \brief Problem type constants for the \c run() function.
160 /// Enum type containing the problem type constants that can be
161 /// returned by the \ref run() function of the algorithm.
163 /// The problem has no feasible solution (flow).
165 /// The problem has optimal solution (i.e. it is feasible and
166 /// bounded), and the algorithm has found optimal flow and node
167 /// potentials (primal and dual solutions).
169 /// The digraph contains an arc of negative cost and infinite
170 /// upper bound. It means that the objective function is unbounded
171 /// on that arc, however, note that it could actually be bounded
172 /// over the feasible flows, but this algroithm cannot handle
177 /// \brief Constants for selecting the internal method.
179 /// Enum type containing constants for selecting the internal method
180 /// for the \ref run() function.
182 /// \ref CostScaling provides three internal methods that differ mainly
183 /// in their base operations, which are used in conjunction with the
184 /// relabel operation.
185 /// By default, the so called \ref PARTIAL_AUGMENT
186 /// "Partial Augment-Relabel" method is used, which turned out to be
187 /// the most efficient and the most robust on various test inputs.
188 /// However, the other methods can be selected using the \ref run()
189 /// function with the proper parameter.
191 /// Local push operations are used, i.e. flow is moved only on one
192 /// admissible arc at once.
194 /// Augment operations are used, i.e. flow is moved on admissible
195 /// paths from a node with excess to a node with deficit.
197 /// Partial augment operations are used, i.e. flow is moved on
198 /// admissible paths started from a node with excess, but the
199 /// lengths of these paths are limited. This method can be viewed
200 /// as a combined version of the previous two operations.
206 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
208 typedef std::vector<int> IntVector;
209 typedef std::vector<Value> ValueVector;
210 typedef std::vector<Cost> CostVector;
211 typedef std::vector<LargeCost> LargeCostVector;
212 typedef std::vector<char> BoolVector;
213 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
217 template <typename KT, typename VT>
218 class StaticVectorMap {
223 StaticVectorMap(std::vector<Value>& v) : _v(v) {}
225 const Value& operator[](const Key& key) const {
226 return _v[StaticDigraph::id(key)];
229 Value& operator[](const Key& key) {
230 return _v[StaticDigraph::id(key)];
233 void set(const Key& key, const Value& val) {
234 _v[StaticDigraph::id(key)] = val;
238 std::vector<Value>& _v;
241 typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
245 // Data related to the underlying digraph
253 // Parameters of the problem
258 // Data structures for storing the digraph
262 IntVector _first_out;
274 ValueVector _res_cap;
275 LargeCostVector _cost;
279 std::deque<int> _active_nodes;
286 IntVector _bucket_next;
287 IntVector _bucket_prev;
293 /// \brief Constant for infinite upper bounds (capacities).
295 /// Constant for infinite upper bounds (capacities).
296 /// It is \c std::numeric_limits<Value>::infinity() if available,
297 /// \c std::numeric_limits<Value>::max() otherwise.
302 /// \name Named Template Parameters
305 template <typename T>
306 struct SetLargeCostTraits : public Traits {
310 /// \brief \ref named-templ-param "Named parameter" for setting
311 /// \c LargeCost type.
313 /// \ref named-templ-param "Named parameter" for setting \c LargeCost
314 /// type, which is used for internal computations in the algorithm.
315 /// \c Cost must be convertible to \c LargeCost.
316 template <typename T>
318 : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
319 typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
330 /// \brief Constructor.
332 /// The constructor of the class.
334 /// \param graph The digraph the algorithm runs on.
335 CostScaling(const GR& graph) :
336 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
337 INF(std::numeric_limits<Value>::has_infinity ?
338 std::numeric_limits<Value>::infinity() :
339 std::numeric_limits<Value>::max())
341 // Check the number types
342 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
343 "The flow type of CostScaling must be signed");
344 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
345 "The cost type of CostScaling must be signed");
347 // Reset data structures
352 /// The parameters of the algorithm can be specified using these
357 /// \brief Set the lower bounds on the arcs.
359 /// This function sets the lower bounds on the arcs.
360 /// If it is not used before calling \ref run(), the lower bounds
361 /// will be set to zero on all arcs.
363 /// \param map An arc map storing the lower bounds.
364 /// Its \c Value type must be convertible to the \c Value type
365 /// of the algorithm.
367 /// \return <tt>(*this)</tt>
368 template <typename LowerMap>
369 CostScaling& lowerMap(const LowerMap& map) {
371 for (ArcIt a(_graph); a != INVALID; ++a) {
372 _lower[_arc_idf[a]] = map[a];
373 _lower[_arc_idb[a]] = map[a];
378 /// \brief Set the upper bounds (capacities) on the arcs.
380 /// This function sets the upper bounds (capacities) on the arcs.
381 /// If it is not used before calling \ref run(), the upper bounds
382 /// will be set to \ref INF on all arcs (i.e. the flow value will be
383 /// unbounded from above).
385 /// \param map An arc map storing the upper bounds.
386 /// Its \c Value type must be convertible to the \c Value type
387 /// of the algorithm.
389 /// \return <tt>(*this)</tt>
390 template<typename UpperMap>
391 CostScaling& upperMap(const UpperMap& map) {
392 for (ArcIt a(_graph); a != INVALID; ++a) {
393 _upper[_arc_idf[a]] = map[a];
398 /// \brief Set the costs of the arcs.
400 /// This function sets the costs of the arcs.
401 /// If it is not used before calling \ref run(), the costs
402 /// will be set to \c 1 on all arcs.
404 /// \param map An arc map storing the costs.
405 /// Its \c Value type must be convertible to the \c Cost type
406 /// of the algorithm.
408 /// \return <tt>(*this)</tt>
409 template<typename CostMap>
410 CostScaling& costMap(const CostMap& map) {
411 for (ArcIt a(_graph); a != INVALID; ++a) {
412 _scost[_arc_idf[a]] = map[a];
413 _scost[_arc_idb[a]] = -map[a];
418 /// \brief Set the supply values of the nodes.
420 /// This function sets the supply values of the nodes.
421 /// If neither this function nor \ref stSupply() is used before
422 /// calling \ref run(), the supply of each node will be set to zero.
424 /// \param map A node map storing the supply values.
425 /// Its \c Value type must be convertible to the \c Value type
426 /// of the algorithm.
428 /// \return <tt>(*this)</tt>
429 template<typename SupplyMap>
430 CostScaling& supplyMap(const SupplyMap& map) {
431 for (NodeIt n(_graph); n != INVALID; ++n) {
432 _supply[_node_id[n]] = map[n];
437 /// \brief Set single source and target nodes and a supply value.
439 /// This function sets a single source node and a single target node
440 /// and the required flow value.
441 /// If neither this function nor \ref supplyMap() is used before
442 /// calling \ref run(), the supply of each node will be set to zero.
444 /// Using this function has the same effect as using \ref supplyMap()
445 /// with a map in which \c k is assigned to \c s, \c -k is
446 /// assigned to \c t and all other nodes have zero supply value.
448 /// \param s The source node.
449 /// \param t The target node.
450 /// \param k The required amount of flow from node \c s to node \c t
451 /// (i.e. the supply of \c s and the demand of \c t).
453 /// \return <tt>(*this)</tt>
454 CostScaling& stSupply(const Node& s, const Node& t, Value k) {
455 for (int i = 0; i != _res_node_num; ++i) {
458 _supply[_node_id[s]] = k;
459 _supply[_node_id[t]] = -k;
465 /// \name Execution control
466 /// The algorithm can be executed using \ref run().
470 /// \brief Run the algorithm.
472 /// This function runs the algorithm.
473 /// The paramters can be specified using functions \ref lowerMap(),
474 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
477 /// CostScaling<ListDigraph> cs(graph);
478 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
479 /// .supplyMap(sup).run();
482 /// This function can be called more than once. All the given parameters
483 /// are kept for the next call, unless \ref resetParams() or \ref reset()
484 /// is used, thus only the modified parameters have to be set again.
485 /// If the underlying digraph was also modified after the construction
486 /// of the class (or the last \ref reset() call), then the \ref reset()
487 /// function must be called.
489 /// \param method The internal method that will be used in the
490 /// algorithm. For more information, see \ref Method.
491 /// \param factor The cost scaling factor. It must be at least two.
493 /// \return \c INFEASIBLE if no feasible flow exists,
494 /// \n \c OPTIMAL if the problem has optimal solution
495 /// (i.e. it is feasible and bounded), and the algorithm has found
496 /// optimal flow and node potentials (primal and dual solutions),
497 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
498 /// and infinite upper bound. It means that the objective function
499 /// is unbounded on that arc, however, note that it could actually be
500 /// bounded over the feasible flows, but this algroithm cannot handle
503 /// \see ProblemType, Method
504 /// \see resetParams(), reset()
505 ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
506 LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
508 ProblemType pt = init();
509 if (pt != OPTIMAL) return pt;
514 /// \brief Reset all the parameters that have been given before.
516 /// This function resets all the paramaters that have been given
517 /// before using functions \ref lowerMap(), \ref upperMap(),
518 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
520 /// It is useful for multiple \ref run() calls. Basically, all the given
521 /// parameters are kept for the next \ref run() call, unless
522 /// \ref resetParams() or \ref reset() is used.
523 /// If the underlying digraph was also modified after the construction
524 /// of the class or the last \ref reset() call, then the \ref reset()
525 /// function must be used, otherwise \ref resetParams() is sufficient.
529 /// CostScaling<ListDigraph> cs(graph);
532 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
533 /// .supplyMap(sup).run();
535 /// // Run again with modified cost map (resetParams() is not called,
536 /// // so only the cost map have to be set again)
538 /// cs.costMap(cost).run();
540 /// // Run again from scratch using resetParams()
541 /// // (the lower bounds will be set to zero on all arcs)
542 /// cs.resetParams();
543 /// cs.upperMap(capacity).costMap(cost)
544 /// .supplyMap(sup).run();
547 /// \return <tt>(*this)</tt>
549 /// \see reset(), run()
550 CostScaling& resetParams() {
551 for (int i = 0; i != _res_node_num; ++i) {
554 int limit = _first_out[_root];
555 for (int j = 0; j != limit; ++j) {
558 _scost[j] = _forward[j] ? 1 : -1;
560 for (int j = limit; j != _res_arc_num; ++j) {
564 _scost[_reverse[j]] = 0;
570 /// \brief Reset the internal data structures and all the parameters
571 /// that have been given before.
573 /// This function resets the internal data structures and all the
574 /// paramaters that have been given before using functions \ref lowerMap(),
575 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
577 /// It is useful for multiple \ref run() calls. By default, all the given
578 /// parameters are kept for the next \ref run() call, unless
579 /// \ref resetParams() or \ref reset() is used.
580 /// If the underlying digraph was also modified after the construction
581 /// of the class or the last \ref reset() call, then the \ref reset()
582 /// function must be used, otherwise \ref resetParams() is sufficient.
584 /// See \ref resetParams() for examples.
586 /// \return <tt>(*this)</tt>
588 /// \see resetParams(), run()
589 CostScaling& reset() {
591 _node_num = countNodes(_graph);
592 _arc_num = countArcs(_graph);
593 _res_node_num = _node_num + 1;
594 _res_arc_num = 2 * (_arc_num + _node_num);
597 _first_out.resize(_res_node_num + 1);
598 _forward.resize(_res_arc_num);
599 _source.resize(_res_arc_num);
600 _target.resize(_res_arc_num);
601 _reverse.resize(_res_arc_num);
603 _lower.resize(_res_arc_num);
604 _upper.resize(_res_arc_num);
605 _scost.resize(_res_arc_num);
606 _supply.resize(_res_node_num);
608 _res_cap.resize(_res_arc_num);
609 _cost.resize(_res_arc_num);
610 _pi.resize(_res_node_num);
611 _excess.resize(_res_node_num);
612 _next_out.resize(_res_node_num);
615 int i = 0, j = 0, k = 2 * _arc_num + _node_num;
616 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
620 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
622 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
626 _target[j] = _node_id[_graph.runningNode(a)];
628 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
632 _target[j] = _node_id[_graph.runningNode(a)];
645 _first_out[_res_node_num] = k;
646 for (ArcIt a(_graph); a != INVALID; ++a) {
647 int fi = _arc_idf[a];
648 int bi = _arc_idb[a];
660 /// \name Query Functions
661 /// The results of the algorithm can be obtained using these
663 /// The \ref run() function must be called before using them.
667 /// \brief Return the total cost of the found flow.
669 /// This function returns the total cost of the found flow.
670 /// Its complexity is O(e).
672 /// \note The return type of the function can be specified as a
673 /// template parameter. For example,
675 /// cs.totalCost<double>();
677 /// It is useful if the total cost cannot be stored in the \c Cost
678 /// type of the algorithm, which is the default return type of the
681 /// \pre \ref run() must be called before using this function.
682 template <typename Number>
683 Number totalCost() const {
685 for (ArcIt a(_graph); a != INVALID; ++a) {
687 c += static_cast<Number>(_res_cap[i]) *
688 (-static_cast<Number>(_scost[i]));
694 Cost totalCost() const {
695 return totalCost<Cost>();
699 /// \brief Return the flow on the given arc.
701 /// This function returns the flow on the given arc.
703 /// \pre \ref run() must be called before using this function.
704 Value flow(const Arc& a) const {
705 return _res_cap[_arc_idb[a]];
708 /// \brief Copy the flow values (the primal solution) into the
711 /// This function copies the flow value on each arc into the given
712 /// map. The \c Value type of the algorithm must be convertible to
713 /// the \c Value type of the map.
715 /// \pre \ref run() must be called before using this function.
716 template <typename FlowMap>
717 void flowMap(FlowMap &map) const {
718 for (ArcIt a(_graph); a != INVALID; ++a) {
719 map.set(a, _res_cap[_arc_idb[a]]);
723 /// \brief Return the potential (dual value) of the given node.
725 /// This function returns the potential (dual value) of the
728 /// \pre \ref run() must be called before using this function.
729 Cost potential(const Node& n) const {
730 return static_cast<Cost>(_pi[_node_id[n]]);
733 /// \brief Copy the potential values (the dual solution) into the
736 /// This function copies the potential (dual value) of each node
737 /// into the given map.
738 /// The \c Cost type of the algorithm must be convertible to the
739 /// \c Value type of the map.
741 /// \pre \ref run() must be called before using this function.
742 template <typename PotentialMap>
743 void potentialMap(PotentialMap &map) const {
744 for (NodeIt n(_graph); n != INVALID; ++n) {
745 map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
753 // Initialize the algorithm
755 if (_res_node_num <= 1) return INFEASIBLE;
757 // Check the sum of supply values
759 for (int i = 0; i != _root; ++i) {
760 _sum_supply += _supply[i];
762 if (_sum_supply > 0) return INFEASIBLE;
765 // Initialize vectors
766 for (int i = 0; i != _res_node_num; ++i) {
768 _excess[i] = _supply[i];
771 // Remove infinite upper bounds and check negative arcs
772 const Value MAX = std::numeric_limits<Value>::max();
775 for (int i = 0; i != _root; ++i) {
776 last_out = _first_out[i+1];
777 for (int j = _first_out[i]; j != last_out; ++j) {
779 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
780 if (c >= MAX) return UNBOUNDED;
782 _excess[_target[j]] += c;
787 for (int i = 0; i != _root; ++i) {
788 last_out = _first_out[i+1];
789 for (int j = _first_out[i]; j != last_out; ++j) {
790 if (_forward[j] && _scost[j] < 0) {
792 if (c >= MAX) return UNBOUNDED;
794 _excess[_target[j]] += c;
799 Value ex, max_cap = 0;
800 for (int i = 0; i != _res_node_num; ++i) {
803 if (ex < 0) max_cap -= ex;
805 for (int j = 0; j != _res_arc_num; ++j) {
806 if (_upper[j] >= MAX) _upper[j] = max_cap;
809 // Initialize the large cost vector and the epsilon parameter
812 for (int i = 0; i != _root; ++i) {
813 last_out = _first_out[i+1];
814 for (int j = _first_out[i]; j != last_out; ++j) {
815 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
817 if (lc > _epsilon) _epsilon = lc;
822 // Initialize maps for Circulation and remove non-zero lower bounds
823 ConstMap<Arc, Value> low(0);
824 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
825 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
826 ValueArcMap cap(_graph), flow(_graph);
827 ValueNodeMap sup(_graph);
828 for (NodeIt n(_graph); n != INVALID; ++n) {
829 sup[n] = _supply[_node_id[n]];
832 for (ArcIt a(_graph); a != INVALID; ++a) {
835 cap[a] = _upper[j] - c;
836 sup[_graph.source(a)] -= c;
837 sup[_graph.target(a)] += c;
840 for (ArcIt a(_graph); a != INVALID; ++a) {
841 cap[a] = _upper[_arc_idf[a]];
846 for (NodeIt n(_graph); n != INVALID; ++n) {
847 if (sup[n] > 0) ++_sup_node_num;
850 // Find a feasible flow using Circulation
851 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
852 circ(_graph, low, cap, sup);
853 if (!circ.flowMap(flow).run()) return INFEASIBLE;
855 // Set residual capacities and handle GEQ supply type
856 if (_sum_supply < 0) {
857 for (ArcIt a(_graph); a != INVALID; ++a) {
859 _res_cap[_arc_idf[a]] = cap[a] - fa;
860 _res_cap[_arc_idb[a]] = fa;
861 sup[_graph.source(a)] -= fa;
862 sup[_graph.target(a)] += fa;
864 for (NodeIt n(_graph); n != INVALID; ++n) {
865 _excess[_node_id[n]] = sup[n];
867 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
869 int ra = _reverse[a];
870 _res_cap[a] = -_sum_supply + 1;
871 _res_cap[ra] = -_excess[u];
877 for (ArcIt a(_graph); a != INVALID; ++a) {
879 _res_cap[_arc_idf[a]] = cap[a] - fa;
880 _res_cap[_arc_idb[a]] = fa;
882 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
883 int ra = _reverse[a];
891 // Initialize data structures for buckets
892 _max_rank = _alpha * _res_node_num;
893 _buckets.resize(_max_rank);
894 _bucket_next.resize(_res_node_num + 1);
895 _bucket_prev.resize(_res_node_num + 1);
896 _rank.resize(_res_node_num + 1);
901 // Execute the algorithm and transform the results
902 void start(Method method) {
903 const int MAX_PARTIAL_PATH_LENGTH = 4;
910 startAugment(_res_node_num - 1);
912 case PARTIAL_AUGMENT:
913 startAugment(MAX_PARTIAL_PATH_LENGTH);
917 // Compute node potentials (dual solution)
918 for (int i = 0; i != _res_node_num; ++i) {
919 _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
922 for (int i = 0; optimal && i != _res_node_num; ++i) {
923 LargeCost pi_i = _pi[i];
924 int last_out = _first_out[i+1];
925 for (int j = _first_out[i]; j != last_out; ++j) {
926 if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
934 // Compute node potentials for the original costs with BellmanFord
935 // (if it is necessary)
936 typedef std::pair<int, int> IntPair;
938 std::vector<IntPair> arc_vec;
939 std::vector<LargeCost> cost_vec;
940 LargeCostArcMap cost_map(cost_vec);
944 for (int j = 0; j != _res_arc_num; ++j) {
945 if (_res_cap[j] > 0) {
946 int u = _source[j], v = _target[j];
947 arc_vec.push_back(IntPair(u, v));
948 cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
951 sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
953 typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
958 for (int i = 0; i != _res_node_num; ++i) {
959 _pi[i] += bf.dist(sgr.node(i));
963 // Shift potentials to meet the requirements of the GEQ type
964 // optimality conditions
965 LargeCost max_pot = _pi[_root];
966 for (int i = 0; i != _res_node_num; ++i) {
967 if (_pi[i] > max_pot) max_pot = _pi[i];
970 for (int i = 0; i != _res_node_num; ++i) {
975 // Handle non-zero lower bounds
977 int limit = _first_out[_root];
978 for (int j = 0; j != limit; ++j) {
979 if (!_forward[j]) _res_cap[j] += _lower[j];
984 // Initialize a cost scaling phase
986 // Saturate arcs not satisfying the optimality condition
987 for (int u = 0; u != _res_node_num; ++u) {
988 int last_out = _first_out[u+1];
989 LargeCost pi_u = _pi[u];
990 for (int a = _first_out[u]; a != last_out; ++a) {
991 Value delta = _res_cap[a];
994 if (_cost[a] + pi_u - _pi[v] < 0) {
998 _res_cap[_reverse[a]] += delta;
1004 // Find active nodes (i.e. nodes with positive excess)
1005 for (int u = 0; u != _res_node_num; ++u) {
1006 if (_excess[u] > 0) _active_nodes.push_back(u);
1009 // Initialize the next arcs
1010 for (int u = 0; u != _res_node_num; ++u) {
1011 _next_out[u] = _first_out[u];
1015 // Price (potential) refinement heuristic
1016 bool priceRefinement() {
1018 // Stack for stroing the topological order
1019 IntVector stack(_res_node_num);
1023 while (topologicalSort(stack, stack_top)) {
1025 // Compute node ranks in the acyclic admissible network and
1026 // store the nodes in buckets
1027 for (int i = 0; i != _res_node_num; ++i) {
1030 const int bucket_end = _root + 1;
1031 for (int r = 0; r != _max_rank; ++r) {
1032 _buckets[r] = bucket_end;
1035 for ( ; stack_top >= 0; --stack_top) {
1036 int u = stack[stack_top], v;
1037 int rank_u = _rank[u];
1039 LargeCost rc, pi_u = _pi[u];
1040 int last_out = _first_out[u+1];
1041 for (int a = _first_out[u]; a != last_out; ++a) {
1042 if (_res_cap[a] > 0) {
1044 rc = _cost[a] + pi_u - _pi[v];
1046 LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1047 if (nrc < LargeCost(_max_rank)) {
1048 int new_rank_v = rank_u + static_cast<int>(nrc);
1049 if (new_rank_v > _rank[v]) {
1050 _rank[v] = new_rank_v;
1058 top_rank = std::max(top_rank, rank_u);
1059 int bfirst = _buckets[rank_u];
1060 _bucket_next[u] = bfirst;
1061 _bucket_prev[bfirst] = u;
1062 _buckets[rank_u] = u;
1066 // Check if the current flow is epsilon-optimal
1067 if (top_rank == 0) {
1071 // Process buckets in top-down order
1072 for (int rank = top_rank; rank > 0; --rank) {
1073 while (_buckets[rank] != bucket_end) {
1074 // Remove the first node from the current bucket
1075 int u = _buckets[rank];
1076 _buckets[rank] = _bucket_next[u];
1078 // Search the outgoing arcs of u
1079 LargeCost rc, pi_u = _pi[u];
1080 int last_out = _first_out[u+1];
1081 int v, old_rank_v, new_rank_v;
1082 for (int a = _first_out[u]; a != last_out; ++a) {
1083 if (_res_cap[a] > 0) {
1085 old_rank_v = _rank[v];
1087 if (old_rank_v < rank) {
1089 // Compute the new rank of node v
1090 rc = _cost[a] + pi_u - _pi[v];
1094 LargeCost nrc = rc / _epsilon;
1096 if (nrc < LargeCost(_max_rank)) {
1097 new_rank_v = rank - 1 - static_cast<int>(nrc);
1101 // Change the rank of node v
1102 if (new_rank_v > old_rank_v) {
1103 _rank[v] = new_rank_v;
1105 // Remove v from its old bucket
1106 if (old_rank_v > 0) {
1107 if (_buckets[old_rank_v] == v) {
1108 _buckets[old_rank_v] = _bucket_next[v];
1110 int pv = _bucket_prev[v], nv = _bucket_next[v];
1111 _bucket_next[pv] = nv;
1112 _bucket_prev[nv] = pv;
1116 // Insert v into its new bucket
1117 int nv = _buckets[new_rank_v];
1118 _bucket_next[v] = nv;
1119 _bucket_prev[nv] = v;
1120 _buckets[new_rank_v] = v;
1126 // Refine potential of node u
1127 _pi[u] -= rank * _epsilon;
1136 // Find and cancel cycles in the admissible network and
1137 // determine topological order using DFS
1138 bool topologicalSort(IntVector &stack, int &stack_top) {
1139 const int MAX_CYCLE_CANCEL = 1;
1141 BoolVector reached(_res_node_num, false);
1142 BoolVector processed(_res_node_num, false);
1143 IntVector pred(_res_node_num);
1144 for (int i = 0; i != _res_node_num; ++i) {
1145 _next_out[i] = _first_out[i];
1150 for (int start = 0; start != _res_node_num; ++start) {
1151 if (reached[start]) continue;
1153 // Start DFS search from this start node
1157 // Check the outgoing arcs of the current tip node
1158 reached[tip] = true;
1159 LargeCost pi_tip = _pi[tip];
1160 int a, last_out = _first_out[tip+1];
1161 for (a = _next_out[tip]; a != last_out; ++a) {
1162 if (_res_cap[a] > 0) {
1164 if (_cost[a] + pi_tip - _pi[v] < 0) {
1166 // A new node is reached
1172 last_out = _first_out[tip+1];
1175 else if (!processed[v]) {
1180 // Find the minimum residual capacity along the cycle
1181 Value d, delta = _res_cap[a];
1182 int u, delta_node = tip;
1183 for (u = tip; u != v; ) {
1185 d = _res_cap[_next_out[u]];
1192 // Augment along the cycle
1193 _res_cap[a] -= delta;
1194 _res_cap[_reverse[a]] += delta;
1195 for (u = tip; u != v; ) {
1197 int ca = _next_out[u];
1198 _res_cap[ca] -= delta;
1199 _res_cap[_reverse[ca]] += delta;
1202 // Check the maximum number of cycle canceling
1203 if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1207 // Roll back search to delta_node
1208 if (delta_node != tip) {
1209 for (u = tip; u != delta_node; u = pred[u]) {
1213 a = _next_out[tip] + 1;
1214 last_out = _first_out[tip+1];
1222 // Step back to the previous node
1223 if (a == last_out) {
1224 processed[tip] = true;
1225 stack[++stack_top] = tip;
1228 // Finish DFS from the current start node
1237 return (cycle_cnt == 0);
1240 // Global potential update heuristic
1241 void globalUpdate() {
1242 const int bucket_end = _root + 1;
1244 // Initialize buckets
1245 for (int r = 0; r != _max_rank; ++r) {
1246 _buckets[r] = bucket_end;
1248 Value total_excess = 0;
1249 int b0 = bucket_end;
1250 for (int i = 0; i != _res_node_num; ++i) {
1251 if (_excess[i] < 0) {
1253 _bucket_next[i] = b0;
1254 _bucket_prev[b0] = i;
1257 total_excess += _excess[i];
1258 _rank[i] = _max_rank;
1261 if (total_excess == 0) return;
1264 // Search the buckets
1266 for ( ; r != _max_rank; ++r) {
1267 while (_buckets[r] != bucket_end) {
1268 // Remove the first node from the current bucket
1269 int u = _buckets[r];
1270 _buckets[r] = _bucket_next[u];
1272 // Search the incomming arcs of u
1273 LargeCost pi_u = _pi[u];
1274 int last_out = _first_out[u+1];
1275 for (int a = _first_out[u]; a != last_out; ++a) {
1276 int ra = _reverse[a];
1277 if (_res_cap[ra] > 0) {
1278 int v = _source[ra];
1279 int old_rank_v = _rank[v];
1280 if (r < old_rank_v) {
1281 // Compute the new rank of v
1282 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1283 int new_rank_v = old_rank_v;
1284 if (nrc < LargeCost(_max_rank)) {
1285 new_rank_v = r + 1 + static_cast<int>(nrc);
1288 // Change the rank of v
1289 if (new_rank_v < old_rank_v) {
1290 _rank[v] = new_rank_v;
1291 _next_out[v] = _first_out[v];
1293 // Remove v from its old bucket
1294 if (old_rank_v < _max_rank) {
1295 if (_buckets[old_rank_v] == v) {
1296 _buckets[old_rank_v] = _bucket_next[v];
1298 int pv = _bucket_prev[v], nv = _bucket_next[v];
1299 _bucket_next[pv] = nv;
1300 _bucket_prev[nv] = pv;
1304 // Insert v into its new bucket
1305 int nv = _buckets[new_rank_v];
1306 _bucket_next[v] = nv;
1307 _bucket_prev[nv] = v;
1308 _buckets[new_rank_v] = v;
1314 // Finish search if there are no more active nodes
1315 if (_excess[u] > 0) {
1316 total_excess -= _excess[u];
1317 if (total_excess <= 0) break;
1320 if (total_excess <= 0) break;
1324 for (int u = 0; u != _res_node_num; ++u) {
1325 int k = std::min(_rank[u], r);
1327 _pi[u] -= _epsilon * k;
1328 _next_out[u] = _first_out[u];
1333 /// Execute the algorithm performing augment and relabel operations
1334 void startAugment(int max_length) {
1335 // Paramters for heuristics
1336 const int PRICE_REFINEMENT_LIMIT = 2;
1337 const double GLOBAL_UPDATE_FACTOR = 1.0;
1338 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1339 (_res_node_num + _sup_node_num * _sup_node_num));
1340 int next_global_update_limit = global_update_skip;
1342 // Perform cost scaling phases
1344 BoolVector path_arc(_res_arc_num, false);
1345 int relabel_cnt = 0;
1346 int eps_phase_cnt = 0;
1347 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1348 1 : _epsilon / _alpha )
1352 // Price refinement heuristic
1353 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1354 if (priceRefinement()) continue;
1357 // Initialize current phase
1360 // Perform partial augment and relabel operations
1362 // Select an active node (FIFO selection)
1363 while (_active_nodes.size() > 0 &&
1364 _excess[_active_nodes.front()] <= 0) {
1365 _active_nodes.pop_front();
1367 if (_active_nodes.size() == 0) break;
1368 int start = _active_nodes.front();
1370 // Find an augmenting path from the start node
1372 while (int(path.size()) < max_length && _excess[tip] >= 0) {
1374 LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1375 LargeCost pi_tip = _pi[tip];
1376 int last_out = _first_out[tip+1];
1377 for (int a = _next_out[tip]; a != last_out; ++a) {
1378 if (_res_cap[a] > 0) {
1380 rc = _cost[a] + pi_tip - _pi[u];
1385 goto augment; // a cycle is found, stop path search
1391 else if (rc < min_red_cost) {
1399 int ra = _reverse[path.back()];
1401 std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1403 last_out = _next_out[tip];
1404 for (int a = _first_out[tip]; a != last_out; ++a) {
1405 if (_res_cap[a] > 0) {
1406 rc = _cost[a] + pi_tip - _pi[_target[a]];
1407 if (rc < min_red_cost) {
1412 _pi[tip] -= min_red_cost + _epsilon;
1413 _next_out[tip] = _first_out[tip];
1418 int pa = path.back();
1419 path_arc[pa] = false;
1427 // Augment along the found path (as much flow as possible)
1430 int pa, u, v = start;
1431 for (int i = 0; i != int(path.size()); ++i) {
1435 path_arc[pa] = false;
1436 delta = std::min(_res_cap[pa], _excess[u]);
1437 _res_cap[pa] -= delta;
1438 _res_cap[_reverse[pa]] += delta;
1439 _excess[u] -= delta;
1440 _excess[v] += delta;
1441 if (_excess[v] > 0 && _excess[v] <= delta) {
1442 _active_nodes.push_back(v);
1447 // Global update heuristic
1448 if (relabel_cnt >= next_global_update_limit) {
1450 next_global_update_limit += global_update_skip;
1458 /// Execute the algorithm performing push and relabel operations
1460 // Paramters for heuristics
1461 const int PRICE_REFINEMENT_LIMIT = 2;
1462 const double GLOBAL_UPDATE_FACTOR = 2.0;
1464 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1465 (_res_node_num + _sup_node_num * _sup_node_num));
1466 int next_global_update_limit = global_update_skip;
1468 // Perform cost scaling phases
1469 BoolVector hyper(_res_node_num, false);
1470 LargeCostVector hyper_cost(_res_node_num);
1471 int relabel_cnt = 0;
1472 int eps_phase_cnt = 0;
1473 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1474 1 : _epsilon / _alpha )
1478 // Price refinement heuristic
1479 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1480 if (priceRefinement()) continue;
1483 // Initialize current phase
1486 // Perform push and relabel operations
1487 while (_active_nodes.size() > 0) {
1488 LargeCost min_red_cost, rc, pi_n;
1490 int n, t, a, last_out = _res_arc_num;
1493 // Select an active node (FIFO selection)
1494 n = _active_nodes.front();
1495 last_out = _first_out[n+1];
1498 // Perform push operations if there are admissible arcs
1499 if (_excess[n] > 0) {
1500 for (a = _next_out[n]; a != last_out; ++a) {
1501 if (_res_cap[a] > 0 &&
1502 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1503 delta = std::min(_res_cap[a], _excess[n]);
1506 // Push-look-ahead heuristic
1507 Value ahead = -_excess[t];
1508 int last_out_t = _first_out[t+1];
1509 LargeCost pi_t = _pi[t];
1510 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1511 if (_res_cap[ta] > 0 &&
1512 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1513 ahead += _res_cap[ta];
1514 if (ahead >= delta) break;
1516 if (ahead < 0) ahead = 0;
1518 // Push flow along the arc
1519 if (ahead < delta && !hyper[t]) {
1520 _res_cap[a] -= ahead;
1521 _res_cap[_reverse[a]] += ahead;
1522 _excess[n] -= ahead;
1523 _excess[t] += ahead;
1524 _active_nodes.push_front(t);
1526 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1530 _res_cap[a] -= delta;
1531 _res_cap[_reverse[a]] += delta;
1532 _excess[n] -= delta;
1533 _excess[t] += delta;
1534 if (_excess[t] > 0 && _excess[t] <= delta)
1535 _active_nodes.push_back(t);
1538 if (_excess[n] == 0) {
1547 // Relabel the node if it is still active (or hyper)
1548 if (_excess[n] > 0 || hyper[n]) {
1549 min_red_cost = hyper[n] ? -hyper_cost[n] :
1550 std::numeric_limits<LargeCost>::max();
1551 for (int a = _first_out[n]; a != last_out; ++a) {
1552 if (_res_cap[a] > 0) {
1553 rc = _cost[a] + pi_n - _pi[_target[a]];
1554 if (rc < min_red_cost) {
1559 _pi[n] -= min_red_cost + _epsilon;
1560 _next_out[n] = _first_out[n];
1565 // Remove nodes that are not active nor hyper
1567 while ( _active_nodes.size() > 0 &&
1568 _excess[_active_nodes.front()] <= 0 &&
1569 !hyper[_active_nodes.front()] ) {
1570 _active_nodes.pop_front();
1573 // Global update heuristic
1574 if (relabel_cnt >= next_global_update_limit) {
1576 for (int u = 0; u != _res_node_num; ++u)
1578 next_global_update_limit += global_update_skip;
1584 }; //class CostScaling
1590 #endif //LEMON_COST_SCALING_H