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;
767 // Initialize vectors
768 for (int i = 0; i != _res_node_num; ++i) {
770 _excess[i] = _supply[i];
773 // Remove infinite upper bounds and check negative arcs
774 const Value MAX = std::numeric_limits<Value>::max();
777 for (int i = 0; i != _root; ++i) {
778 last_out = _first_out[i+1];
779 for (int j = _first_out[i]; j != last_out; ++j) {
781 Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
782 if (c >= MAX) return UNBOUNDED;
784 _excess[_target[j]] += c;
789 for (int i = 0; i != _root; ++i) {
790 last_out = _first_out[i+1];
791 for (int j = _first_out[i]; j != last_out; ++j) {
792 if (_forward[j] && _scost[j] < 0) {
794 if (c >= MAX) return UNBOUNDED;
796 _excess[_target[j]] += c;
801 Value ex, max_cap = 0;
802 for (int i = 0; i != _res_node_num; ++i) {
805 if (ex < 0) max_cap -= ex;
807 for (int j = 0; j != _res_arc_num; ++j) {
808 if (_upper[j] >= MAX) _upper[j] = max_cap;
811 // Initialize the large cost vector and the epsilon parameter
814 for (int i = 0; i != _root; ++i) {
815 last_out = _first_out[i+1];
816 for (int j = _first_out[i]; j != last_out; ++j) {
817 lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
819 if (lc > _epsilon) _epsilon = lc;
824 // Initialize maps for Circulation and remove non-zero lower bounds
825 ConstMap<Arc, Value> low(0);
826 typedef typename Digraph::template ArcMap<Value> ValueArcMap;
827 typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
828 ValueArcMap cap(_graph), flow(_graph);
829 ValueNodeMap sup(_graph);
830 for (NodeIt n(_graph); n != INVALID; ++n) {
831 sup[n] = _supply[_node_id[n]];
834 for (ArcIt a(_graph); a != INVALID; ++a) {
837 cap[a] = _upper[j] - c;
838 sup[_graph.source(a)] -= c;
839 sup[_graph.target(a)] += c;
842 for (ArcIt a(_graph); a != INVALID; ++a) {
843 cap[a] = _upper[_arc_idf[a]];
848 for (NodeIt n(_graph); n != INVALID; ++n) {
849 if (sup[n] > 0) ++_sup_node_num;
852 // Find a feasible flow using Circulation
853 Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
854 circ(_graph, low, cap, sup);
855 if (!circ.flowMap(flow).run()) return INFEASIBLE;
857 // Set residual capacities and handle GEQ supply type
858 if (_sum_supply < 0) {
859 for (ArcIt a(_graph); a != INVALID; ++a) {
861 _res_cap[_arc_idf[a]] = cap[a] - fa;
862 _res_cap[_arc_idb[a]] = fa;
863 sup[_graph.source(a)] -= fa;
864 sup[_graph.target(a)] += fa;
866 for (NodeIt n(_graph); n != INVALID; ++n) {
867 _excess[_node_id[n]] = sup[n];
869 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
871 int ra = _reverse[a];
872 _res_cap[a] = -_sum_supply + 1;
873 _res_cap[ra] = -_excess[u];
879 for (ArcIt a(_graph); a != INVALID; ++a) {
881 _res_cap[_arc_idf[a]] = cap[a] - fa;
882 _res_cap[_arc_idb[a]] = fa;
884 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
885 int ra = _reverse[a];
893 // Initialize data structures for buckets
894 _max_rank = _alpha * _res_node_num;
895 _buckets.resize(_max_rank);
896 _bucket_next.resize(_res_node_num + 1);
897 _bucket_prev.resize(_res_node_num + 1);
898 _rank.resize(_res_node_num + 1);
903 // Execute the algorithm and transform the results
904 void start(Method method) {
905 const int MAX_PARTIAL_PATH_LENGTH = 4;
912 startAugment(_res_node_num - 1);
914 case PARTIAL_AUGMENT:
915 startAugment(MAX_PARTIAL_PATH_LENGTH);
919 // Compute node potentials (dual solution)
920 for (int i = 0; i != _res_node_num; ++i) {
921 _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
924 for (int i = 0; optimal && i != _res_node_num; ++i) {
925 LargeCost pi_i = _pi[i];
926 int last_out = _first_out[i+1];
927 for (int j = _first_out[i]; j != last_out; ++j) {
928 if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
936 // Compute node potentials for the original costs with BellmanFord
937 // (if it is necessary)
938 typedef std::pair<int, int> IntPair;
940 std::vector<IntPair> arc_vec;
941 std::vector<LargeCost> cost_vec;
942 LargeCostArcMap cost_map(cost_vec);
946 for (int j = 0; j != _res_arc_num; ++j) {
947 if (_res_cap[j] > 0) {
948 int u = _source[j], v = _target[j];
949 arc_vec.push_back(IntPair(u, v));
950 cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
953 sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
955 typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
960 for (int i = 0; i != _res_node_num; ++i) {
961 _pi[i] += bf.dist(sgr.node(i));
965 // Shift potentials to meet the requirements of the GEQ type
966 // optimality conditions
967 LargeCost max_pot = _pi[_root];
968 for (int i = 0; i != _res_node_num; ++i) {
969 if (_pi[i] > max_pot) max_pot = _pi[i];
972 for (int i = 0; i != _res_node_num; ++i) {
977 // Handle non-zero lower bounds
979 int limit = _first_out[_root];
980 for (int j = 0; j != limit; ++j) {
981 if (!_forward[j]) _res_cap[j] += _lower[j];
986 // Initialize a cost scaling phase
988 // Saturate arcs not satisfying the optimality condition
989 for (int u = 0; u != _res_node_num; ++u) {
990 int last_out = _first_out[u+1];
991 LargeCost pi_u = _pi[u];
992 for (int a = _first_out[u]; a != last_out; ++a) {
993 Value delta = _res_cap[a];
996 if (_cost[a] + pi_u - _pi[v] < 0) {
1000 _res_cap[_reverse[a]] += delta;
1006 // Find active nodes (i.e. nodes with positive excess)
1007 for (int u = 0; u != _res_node_num; ++u) {
1008 if (_excess[u] > 0) _active_nodes.push_back(u);
1011 // Initialize the next arcs
1012 for (int u = 0; u != _res_node_num; ++u) {
1013 _next_out[u] = _first_out[u];
1017 // Price (potential) refinement heuristic
1018 bool priceRefinement() {
1020 // Stack for stroing the topological order
1021 IntVector stack(_res_node_num);
1025 while (topologicalSort(stack, stack_top)) {
1027 // Compute node ranks in the acyclic admissible network and
1028 // store the nodes in buckets
1029 for (int i = 0; i != _res_node_num; ++i) {
1032 const int bucket_end = _root + 1;
1033 for (int r = 0; r != _max_rank; ++r) {
1034 _buckets[r] = bucket_end;
1037 for ( ; stack_top >= 0; --stack_top) {
1038 int u = stack[stack_top], v;
1039 int rank_u = _rank[u];
1041 LargeCost rc, pi_u = _pi[u];
1042 int last_out = _first_out[u+1];
1043 for (int a = _first_out[u]; a != last_out; ++a) {
1044 if (_res_cap[a] > 0) {
1046 rc = _cost[a] + pi_u - _pi[v];
1048 LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1049 if (nrc < LargeCost(_max_rank)) {
1050 int new_rank_v = rank_u + static_cast<int>(nrc);
1051 if (new_rank_v > _rank[v]) {
1052 _rank[v] = new_rank_v;
1060 top_rank = std::max(top_rank, rank_u);
1061 int bfirst = _buckets[rank_u];
1062 _bucket_next[u] = bfirst;
1063 _bucket_prev[bfirst] = u;
1064 _buckets[rank_u] = u;
1068 // Check if the current flow is epsilon-optimal
1069 if (top_rank == 0) {
1073 // Process buckets in top-down order
1074 for (int rank = top_rank; rank > 0; --rank) {
1075 while (_buckets[rank] != bucket_end) {
1076 // Remove the first node from the current bucket
1077 int u = _buckets[rank];
1078 _buckets[rank] = _bucket_next[u];
1080 // Search the outgoing arcs of u
1081 LargeCost rc, pi_u = _pi[u];
1082 int last_out = _first_out[u+1];
1083 int v, old_rank_v, new_rank_v;
1084 for (int a = _first_out[u]; a != last_out; ++a) {
1085 if (_res_cap[a] > 0) {
1087 old_rank_v = _rank[v];
1089 if (old_rank_v < rank) {
1091 // Compute the new rank of node v
1092 rc = _cost[a] + pi_u - _pi[v];
1096 LargeCost nrc = rc / _epsilon;
1098 if (nrc < LargeCost(_max_rank)) {
1099 new_rank_v = rank - 1 - static_cast<int>(nrc);
1103 // Change the rank of node v
1104 if (new_rank_v > old_rank_v) {
1105 _rank[v] = new_rank_v;
1107 // Remove v from its old bucket
1108 if (old_rank_v > 0) {
1109 if (_buckets[old_rank_v] == v) {
1110 _buckets[old_rank_v] = _bucket_next[v];
1112 int pv = _bucket_prev[v], nv = _bucket_next[v];
1113 _bucket_next[pv] = nv;
1114 _bucket_prev[nv] = pv;
1118 // Insert v into its new bucket
1119 int nv = _buckets[new_rank_v];
1120 _bucket_next[v] = nv;
1121 _bucket_prev[nv] = v;
1122 _buckets[new_rank_v] = v;
1128 // Refine potential of node u
1129 _pi[u] -= rank * _epsilon;
1138 // Find and cancel cycles in the admissible network and
1139 // determine topological order using DFS
1140 bool topologicalSort(IntVector &stack, int &stack_top) {
1141 const int MAX_CYCLE_CANCEL = 1;
1143 BoolVector reached(_res_node_num, false);
1144 BoolVector processed(_res_node_num, false);
1145 IntVector pred(_res_node_num);
1146 for (int i = 0; i != _res_node_num; ++i) {
1147 _next_out[i] = _first_out[i];
1152 for (int start = 0; start != _res_node_num; ++start) {
1153 if (reached[start]) continue;
1155 // Start DFS search from this start node
1159 // Check the outgoing arcs of the current tip node
1160 reached[tip] = true;
1161 LargeCost pi_tip = _pi[tip];
1162 int a, last_out = _first_out[tip+1];
1163 for (a = _next_out[tip]; a != last_out; ++a) {
1164 if (_res_cap[a] > 0) {
1166 if (_cost[a] + pi_tip - _pi[v] < 0) {
1168 // A new node is reached
1174 last_out = _first_out[tip+1];
1177 else if (!processed[v]) {
1182 // Find the minimum residual capacity along the cycle
1183 Value d, delta = _res_cap[a];
1184 int u, delta_node = tip;
1185 for (u = tip; u != v; ) {
1187 d = _res_cap[_next_out[u]];
1194 // Augment along the cycle
1195 _res_cap[a] -= delta;
1196 _res_cap[_reverse[a]] += delta;
1197 for (u = tip; u != v; ) {
1199 int ca = _next_out[u];
1200 _res_cap[ca] -= delta;
1201 _res_cap[_reverse[ca]] += delta;
1204 // Check the maximum number of cycle canceling
1205 if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1209 // Roll back search to delta_node
1210 if (delta_node != tip) {
1211 for (u = tip; u != delta_node; u = pred[u]) {
1215 a = _next_out[tip] + 1;
1216 last_out = _first_out[tip+1];
1224 // Step back to the previous node
1225 if (a == last_out) {
1226 processed[tip] = true;
1227 stack[++stack_top] = tip;
1230 // Finish DFS from the current start node
1239 return (cycle_cnt == 0);
1242 // Global potential update heuristic
1243 void globalUpdate() {
1244 const int bucket_end = _root + 1;
1246 // Initialize buckets
1247 for (int r = 0; r != _max_rank; ++r) {
1248 _buckets[r] = bucket_end;
1250 Value total_excess = 0;
1251 int b0 = bucket_end;
1252 for (int i = 0; i != _res_node_num; ++i) {
1253 if (_excess[i] < 0) {
1255 _bucket_next[i] = b0;
1256 _bucket_prev[b0] = i;
1259 total_excess += _excess[i];
1260 _rank[i] = _max_rank;
1263 if (total_excess == 0) return;
1266 // Search the buckets
1268 for ( ; r != _max_rank; ++r) {
1269 while (_buckets[r] != bucket_end) {
1270 // Remove the first node from the current bucket
1271 int u = _buckets[r];
1272 _buckets[r] = _bucket_next[u];
1274 // Search the incoming arcs of u
1275 LargeCost pi_u = _pi[u];
1276 int last_out = _first_out[u+1];
1277 for (int a = _first_out[u]; a != last_out; ++a) {
1278 int ra = _reverse[a];
1279 if (_res_cap[ra] > 0) {
1280 int v = _source[ra];
1281 int old_rank_v = _rank[v];
1282 if (r < old_rank_v) {
1283 // Compute the new rank of v
1284 LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1285 int new_rank_v = old_rank_v;
1286 if (nrc < LargeCost(_max_rank)) {
1287 new_rank_v = r + 1 + static_cast<int>(nrc);
1290 // Change the rank of v
1291 if (new_rank_v < old_rank_v) {
1292 _rank[v] = new_rank_v;
1293 _next_out[v] = _first_out[v];
1295 // Remove v from its old bucket
1296 if (old_rank_v < _max_rank) {
1297 if (_buckets[old_rank_v] == v) {
1298 _buckets[old_rank_v] = _bucket_next[v];
1300 int pv = _bucket_prev[v], nv = _bucket_next[v];
1301 _bucket_next[pv] = nv;
1302 _bucket_prev[nv] = pv;
1306 // Insert v into its new bucket
1307 int nv = _buckets[new_rank_v];
1308 _bucket_next[v] = nv;
1309 _bucket_prev[nv] = v;
1310 _buckets[new_rank_v] = v;
1316 // Finish search if there are no more active nodes
1317 if (_excess[u] > 0) {
1318 total_excess -= _excess[u];
1319 if (total_excess <= 0) break;
1322 if (total_excess <= 0) break;
1326 for (int u = 0; u != _res_node_num; ++u) {
1327 int k = std::min(_rank[u], r);
1329 _pi[u] -= _epsilon * k;
1330 _next_out[u] = _first_out[u];
1335 /// Execute the algorithm performing augment and relabel operations
1336 void startAugment(int max_length) {
1337 // Paramters for heuristics
1338 const int PRICE_REFINEMENT_LIMIT = 2;
1339 const double GLOBAL_UPDATE_FACTOR = 1.0;
1340 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1341 (_res_node_num + _sup_node_num * _sup_node_num));
1342 int next_global_update_limit = global_update_skip;
1344 // Perform cost scaling phases
1346 BoolVector path_arc(_res_arc_num, false);
1347 int relabel_cnt = 0;
1348 int eps_phase_cnt = 0;
1349 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1350 1 : _epsilon / _alpha )
1354 // Price refinement heuristic
1355 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1356 if (priceRefinement()) continue;
1359 // Initialize current phase
1362 // Perform partial augment and relabel operations
1364 // Select an active node (FIFO selection)
1365 while (_active_nodes.size() > 0 &&
1366 _excess[_active_nodes.front()] <= 0) {
1367 _active_nodes.pop_front();
1369 if (_active_nodes.size() == 0) break;
1370 int start = _active_nodes.front();
1372 // Find an augmenting path from the start node
1374 while (int(path.size()) < max_length && _excess[tip] >= 0) {
1376 LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1377 LargeCost pi_tip = _pi[tip];
1378 int last_out = _first_out[tip+1];
1379 for (int a = _next_out[tip]; a != last_out; ++a) {
1380 if (_res_cap[a] > 0) {
1382 rc = _cost[a] + pi_tip - _pi[u];
1387 goto augment; // a cycle is found, stop path search
1393 else if (rc < min_red_cost) {
1401 int ra = _reverse[path.back()];
1403 std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1405 last_out = _next_out[tip];
1406 for (int a = _first_out[tip]; a != last_out; ++a) {
1407 if (_res_cap[a] > 0) {
1408 rc = _cost[a] + pi_tip - _pi[_target[a]];
1409 if (rc < min_red_cost) {
1414 _pi[tip] -= min_red_cost + _epsilon;
1415 _next_out[tip] = _first_out[tip];
1420 int pa = path.back();
1421 path_arc[pa] = false;
1429 // Augment along the found path (as much flow as possible)
1432 int pa, u, v = start;
1433 for (int i = 0; i != int(path.size()); ++i) {
1437 path_arc[pa] = false;
1438 delta = std::min(_res_cap[pa], _excess[u]);
1439 _res_cap[pa] -= delta;
1440 _res_cap[_reverse[pa]] += delta;
1441 _excess[u] -= delta;
1442 _excess[v] += delta;
1443 if (_excess[v] > 0 && _excess[v] <= delta) {
1444 _active_nodes.push_back(v);
1449 // Global update heuristic
1450 if (relabel_cnt >= next_global_update_limit) {
1452 next_global_update_limit += global_update_skip;
1460 /// Execute the algorithm performing push and relabel operations
1462 // Paramters for heuristics
1463 const int PRICE_REFINEMENT_LIMIT = 2;
1464 const double GLOBAL_UPDATE_FACTOR = 2.0;
1466 const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1467 (_res_node_num + _sup_node_num * _sup_node_num));
1468 int next_global_update_limit = global_update_skip;
1470 // Perform cost scaling phases
1471 BoolVector hyper(_res_node_num, false);
1472 LargeCostVector hyper_cost(_res_node_num);
1473 int relabel_cnt = 0;
1474 int eps_phase_cnt = 0;
1475 for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1476 1 : _epsilon / _alpha )
1480 // Price refinement heuristic
1481 if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1482 if (priceRefinement()) continue;
1485 // Initialize current phase
1488 // Perform push and relabel operations
1489 while (_active_nodes.size() > 0) {
1490 LargeCost min_red_cost, rc, pi_n;
1492 int n, t, a, last_out = _res_arc_num;
1495 // Select an active node (FIFO selection)
1496 n = _active_nodes.front();
1497 last_out = _first_out[n+1];
1500 // Perform push operations if there are admissible arcs
1501 if (_excess[n] > 0) {
1502 for (a = _next_out[n]; a != last_out; ++a) {
1503 if (_res_cap[a] > 0 &&
1504 _cost[a] + pi_n - _pi[_target[a]] < 0) {
1505 delta = std::min(_res_cap[a], _excess[n]);
1508 // Push-look-ahead heuristic
1509 Value ahead = -_excess[t];
1510 int last_out_t = _first_out[t+1];
1511 LargeCost pi_t = _pi[t];
1512 for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1513 if (_res_cap[ta] > 0 &&
1514 _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1515 ahead += _res_cap[ta];
1516 if (ahead >= delta) break;
1518 if (ahead < 0) ahead = 0;
1520 // Push flow along the arc
1521 if (ahead < delta && !hyper[t]) {
1522 _res_cap[a] -= ahead;
1523 _res_cap[_reverse[a]] += ahead;
1524 _excess[n] -= ahead;
1525 _excess[t] += ahead;
1526 _active_nodes.push_front(t);
1528 hyper_cost[t] = _cost[a] + pi_n - pi_t;
1532 _res_cap[a] -= delta;
1533 _res_cap[_reverse[a]] += delta;
1534 _excess[n] -= delta;
1535 _excess[t] += delta;
1536 if (_excess[t] > 0 && _excess[t] <= delta)
1537 _active_nodes.push_back(t);
1540 if (_excess[n] == 0) {
1549 // Relabel the node if it is still active (or hyper)
1550 if (_excess[n] > 0 || hyper[n]) {
1551 min_red_cost = hyper[n] ? -hyper_cost[n] :
1552 std::numeric_limits<LargeCost>::max();
1553 for (int a = _first_out[n]; a != last_out; ++a) {
1554 if (_res_cap[a] > 0) {
1555 rc = _cost[a] + pi_n - _pi[_target[a]];
1556 if (rc < min_red_cost) {
1561 _pi[n] -= min_red_cost + _epsilon;
1562 _next_out[n] = _first_out[n];
1567 // Remove nodes that are not active nor hyper
1569 while ( _active_nodes.size() > 0 &&
1570 _excess[_active_nodes.front()] <= 0 &&
1571 !hyper[_active_nodes.front()] ) {
1572 _active_nodes.pop_front();
1575 // Global update heuristic
1576 if (relabel_cnt >= next_global_update_limit) {
1578 for (int u = 0; u != _res_node_num; ++u)
1580 next_global_update_limit += global_update_skip;
1586 }; //class CostScaling
1592 #endif //LEMON_COST_SCALING_H