COIN-OR::LEMON - Graph Library

source: lemon/lemon/cost_scaling.h @ 1240:ee9bac10f58e

Last change on this file since 1240:ee9bac10f58e was 1240:ee9bac10f58e, checked in by Peter Kovacs <kpeter@…>, 12 years ago

Debug checking for capacity bounds in min cost flow algorithms (#454)

File size: 51.3 KB
Line 
1/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library.
4 *
5 * Copyright (C) 2003-2010
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
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.
12 *
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
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_COST_SCALING_H
20#define LEMON_COST_SCALING_H
21
22/// \ingroup min_cost_flow_algs
23/// \file
24/// \brief Cost scaling algorithm for finding a minimum cost flow.
25
26#include <vector>
27#include <deque>
28#include <limits>
29
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>
36
37namespace lemon {
38
39  /// \brief Default traits class of CostScaling algorithm.
40  ///
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.
47#ifdef DOXYGEN
48  template <typename GR, typename V = int, typename C = V>
49#else
50  template < typename GR, typename V = int, typename C = V,
51             bool integer = std::numeric_limits<C>::is_integer >
52#endif
53  struct CostScalingDefaultTraits
54  {
55    /// The type of the digraph
56    typedef GR Digraph;
57    /// The type of the flow amounts, capacity bounds and supply values
58    typedef V Value;
59    /// The type of the arc costs
60    typedef C Cost;
61
62    /// \brief The large cost type used for internal computations
63    ///
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;
69  };
70
71  // Default traits class for integer cost types
72  template <typename GR, typename V, typename C>
73  struct CostScalingDefaultTraits<GR, V, C, true>
74  {
75    typedef GR Digraph;
76    typedef V Value;
77    typedef C Cost;
78#ifdef LEMON_HAVE_LONG_LONG
79    typedef long long LargeCost;
80#else
81    typedef long LargeCost;
82#endif
83  };
84
85
86  /// \addtogroup min_cost_flow_algs
87  /// @{
88
89  /// \brief Implementation of the Cost Scaling algorithm for
90  /// finding a \ref min_cost_flow "minimum cost flow".
91  ///
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.
99  ///
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".)
103  ///
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.
108  ///
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.
119  ///
120  /// \warning Both \c V and \c C must be signed number types.
121  /// \warning All input data (capacities, supply values, and costs) must
122  /// be integer.
123  /// \warning This algorithm does not support negative costs for
124  /// arcs having infinite upper bound.
125  ///
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.
129#ifdef DOXYGEN
130  template <typename GR, typename V, typename C, typename TR>
131#else
132  template < typename GR, typename V = int, typename C = V,
133             typename TR = CostScalingDefaultTraits<GR, V, C> >
134#endif
135  class CostScaling
136  {
137  public:
138
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;
145
146    /// \brief The large cost type
147    ///
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;
152
153    /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
154    typedef TR Traits;
155
156  public:
157
158    /// \brief Problem type constants for the \c run() function.
159    ///
160    /// Enum type containing the problem type constants that can be
161    /// returned by the \ref run() function of the algorithm.
162    enum ProblemType {
163      /// The problem has no feasible solution (flow).
164      INFEASIBLE,
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).
168      OPTIMAL,
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
173      /// these cases.
174      UNBOUNDED
175    };
176
177    /// \brief Constants for selecting the internal method.
178    ///
179    /// Enum type containing constants for selecting the internal method
180    /// for the \ref run() function.
181    ///
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.
190    enum Method {
191      /// Local push operations are used, i.e. flow is moved only on one
192      /// admissible arc at once.
193      PUSH,
194      /// Augment operations are used, i.e. flow is moved on admissible
195      /// paths from a node with excess to a node with deficit.
196      AUGMENT,
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.
201      PARTIAL_AUGMENT
202    };
203
204  private:
205
206    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
207
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
214
215  private:
216
217    template <typename KT, typename VT>
218    class StaticVectorMap {
219    public:
220      typedef KT Key;
221      typedef VT Value;
222
223      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
224
225      const Value& operator[](const Key& key) const {
226        return _v[StaticDigraph::id(key)];
227      }
228
229      Value& operator[](const Key& key) {
230        return _v[StaticDigraph::id(key)];
231      }
232
233      void set(const Key& key, const Value& val) {
234        _v[StaticDigraph::id(key)] = val;
235      }
236
237    private:
238      std::vector<Value>& _v;
239    };
240
241    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
242
243  private:
244
245    // Data related to the underlying digraph
246    const GR &_graph;
247    int _node_num;
248    int _arc_num;
249    int _res_node_num;
250    int _res_arc_num;
251    int _root;
252
253    // Parameters of the problem
254    bool _have_lower;
255    Value _sum_supply;
256    int _sup_node_num;
257
258    // Data structures for storing the digraph
259    IntNodeMap _node_id;
260    IntArcMap _arc_idf;
261    IntArcMap _arc_idb;
262    IntVector _first_out;
263    BoolVector _forward;
264    IntVector _source;
265    IntVector _target;
266    IntVector _reverse;
267
268    // Node and arc data
269    ValueVector _lower;
270    ValueVector _upper;
271    CostVector _scost;
272    ValueVector _supply;
273
274    ValueVector _res_cap;
275    LargeCostVector _cost;
276    LargeCostVector _pi;
277    ValueVector _excess;
278    IntVector _next_out;
279    std::deque<int> _active_nodes;
280
281    // Data for scaling
282    LargeCost _epsilon;
283    int _alpha;
284
285    IntVector _buckets;
286    IntVector _bucket_next;
287    IntVector _bucket_prev;
288    IntVector _rank;
289    int _max_rank;
290
291  public:
292
293    /// \brief Constant for infinite upper bounds (capacities).
294    ///
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.
298    const Value INF;
299
300  public:
301
302    /// \name Named Template Parameters
303    /// @{
304
305    template <typename T>
306    struct SetLargeCostTraits : public Traits {
307      typedef T LargeCost;
308    };
309
310    /// \brief \ref named-templ-param "Named parameter" for setting
311    /// \c LargeCost type.
312    ///
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>
317    struct SetLargeCost
318      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
319      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
320    };
321
322    /// @}
323
324  protected:
325
326    CostScaling() {}
327
328  public:
329
330    /// \brief Constructor.
331    ///
332    /// The constructor of the class.
333    ///
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())
340    {
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");
346
347      // Reset data structures
348      reset();
349    }
350
351    /// \name Parameters
352    /// The parameters of the algorithm can be specified using these
353    /// functions.
354
355    /// @{
356
357    /// \brief Set the lower bounds on the arcs.
358    ///
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.
362    ///
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.
366    ///
367    /// \return <tt>(*this)</tt>
368    template <typename LowerMap>
369    CostScaling& lowerMap(const LowerMap& map) {
370      _have_lower = true;
371      for (ArcIt a(_graph); a != INVALID; ++a) {
372        _lower[_arc_idf[a]] = map[a];
373        _lower[_arc_idb[a]] = map[a];
374      }
375      return *this;
376    }
377
378    /// \brief Set the upper bounds (capacities) on the arcs.
379    ///
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).
384    ///
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.
388    ///
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];
394      }
395      return *this;
396    }
397
398    /// \brief Set the costs of the arcs.
399    ///
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.
403    ///
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.
407    ///
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];
414      }
415      return *this;
416    }
417
418    /// \brief Set the supply values of the nodes.
419    ///
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.
423    ///
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.
427    ///
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];
433      }
434      return *this;
435    }
436
437    /// \brief Set single source and target nodes and a supply value.
438    ///
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.
443    ///
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.
447    ///
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).
452    ///
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) {
456        _supply[i] = 0;
457      }
458      _supply[_node_id[s]] =  k;
459      _supply[_node_id[t]] = -k;
460      return *this;
461    }
462
463    /// @}
464
465    /// \name Execution control
466    /// The algorithm can be executed using \ref run().
467
468    /// @{
469
470    /// \brief Run the algorithm.
471    ///
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().
475    /// For example,
476    /// \code
477    ///   CostScaling<ListDigraph> cs(graph);
478    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
479    ///     .supplyMap(sup).run();
480    /// \endcode
481    ///
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.
488    ///
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.
492    ///
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
501    /// these cases.
502    ///
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");
507      _alpha = factor;
508      ProblemType pt = init();
509      if (pt != OPTIMAL) return pt;
510      start(method);
511      return OPTIMAL;
512    }
513
514    /// \brief Reset all the parameters that have been given before.
515    ///
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().
519    ///
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.
526    ///
527    /// For example,
528    /// \code
529    ///   CostScaling<ListDigraph> cs(graph);
530    ///
531    ///   // First run
532    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
533    ///     .supplyMap(sup).run();
534    ///
535    ///   // Run again with modified cost map (resetParams() is not called,
536    ///   // so only the cost map have to be set again)
537    ///   cost[e] += 100;
538    ///   cs.costMap(cost).run();
539    ///
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();
545    /// \endcode
546    ///
547    /// \return <tt>(*this)</tt>
548    ///
549    /// \see reset(), run()
550    CostScaling& resetParams() {
551      for (int i = 0; i != _res_node_num; ++i) {
552        _supply[i] = 0;
553      }
554      int limit = _first_out[_root];
555      for (int j = 0; j != limit; ++j) {
556        _lower[j] = 0;
557        _upper[j] = INF;
558        _scost[j] = _forward[j] ? 1 : -1;
559      }
560      for (int j = limit; j != _res_arc_num; ++j) {
561        _lower[j] = 0;
562        _upper[j] = INF;
563        _scost[j] = 0;
564        _scost[_reverse[j]] = 0;
565      }
566      _have_lower = false;
567      return *this;
568    }
569
570    /// \brief Reset the internal data structures and all the parameters
571    /// that have been given before.
572    ///
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().
576    ///
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.
583    ///
584    /// See \ref resetParams() for examples.
585    ///
586    /// \return <tt>(*this)</tt>
587    ///
588    /// \see resetParams(), run()
589    CostScaling& reset() {
590      // Resize vectors
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);
595      _root = _node_num;
596
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);
602
603      _lower.resize(_res_arc_num);
604      _upper.resize(_res_arc_num);
605      _scost.resize(_res_arc_num);
606      _supply.resize(_res_node_num);
607
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);
613
614      // Copy the graph
615      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
616      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
617        _node_id[n] = i;
618      }
619      i = 0;
620      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
621        _first_out[i] = j;
622        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
623          _arc_idf[a] = j;
624          _forward[j] = true;
625          _source[j] = i;
626          _target[j] = _node_id[_graph.runningNode(a)];
627        }
628        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
629          _arc_idb[a] = j;
630          _forward[j] = false;
631          _source[j] = i;
632          _target[j] = _node_id[_graph.runningNode(a)];
633        }
634        _forward[j] = false;
635        _source[j] = i;
636        _target[j] = _root;
637        _reverse[j] = k;
638        _forward[k] = true;
639        _source[k] = _root;
640        _target[k] = i;
641        _reverse[k] = j;
642        ++j; ++k;
643      }
644      _first_out[i] = j;
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];
649        _reverse[fi] = bi;
650        _reverse[bi] = fi;
651      }
652
653      // Reset parameters
654      resetParams();
655      return *this;
656    }
657
658    /// @}
659
660    /// \name Query Functions
661    /// The results of the algorithm can be obtained using these
662    /// functions.\n
663    /// The \ref run() function must be called before using them.
664
665    /// @{
666
667    /// \brief Return the total cost of the found flow.
668    ///
669    /// This function returns the total cost of the found flow.
670    /// Its complexity is O(e).
671    ///
672    /// \note The return type of the function can be specified as a
673    /// template parameter. For example,
674    /// \code
675    ///   cs.totalCost<double>();
676    /// \endcode
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
679    /// function.
680    ///
681    /// \pre \ref run() must be called before using this function.
682    template <typename Number>
683    Number totalCost() const {
684      Number c = 0;
685      for (ArcIt a(_graph); a != INVALID; ++a) {
686        int i = _arc_idb[a];
687        c += static_cast<Number>(_res_cap[i]) *
688             (-static_cast<Number>(_scost[i]));
689      }
690      return c;
691    }
692
693#ifndef DOXYGEN
694    Cost totalCost() const {
695      return totalCost<Cost>();
696    }
697#endif
698
699    /// \brief Return the flow on the given arc.
700    ///
701    /// This function returns the flow on the given arc.
702    ///
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]];
706    }
707
708    /// \brief Copy the flow values (the primal solution) into the
709    /// given map.
710    ///
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.
714    ///
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]]);
720      }
721    }
722
723    /// \brief Return the potential (dual value) of the given node.
724    ///
725    /// This function returns the potential (dual value) of the
726    /// given node.
727    ///
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]]);
731    }
732
733    /// \brief Copy the potential values (the dual solution) into the
734    /// given map.
735    ///
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.
740    ///
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]]));
746      }
747    }
748
749    /// @}
750
751  private:
752
753    // Initialize the algorithm
754    ProblemType init() {
755      if (_res_node_num <= 1) return INFEASIBLE;
756
757      // Check the sum of supply values
758      _sum_supply = 0;
759      for (int i = 0; i != _root; ++i) {
760        _sum_supply += _supply[i];
761      }
762      if (_sum_supply > 0) return INFEASIBLE;
763
764      // Check lower and upper bounds
765      LEMON_DEBUG(checkBoundMaps(),
766          "Upper bounds must be greater or equal to the lower bounds");
767
768
769      // Initialize vectors
770      for (int i = 0; i != _res_node_num; ++i) {
771        _pi[i] = 0;
772        _excess[i] = _supply[i];
773      }
774
775      // Remove infinite upper bounds and check negative arcs
776      const Value MAX = std::numeric_limits<Value>::max();
777      int last_out;
778      if (_have_lower) {
779        for (int i = 0; i != _root; ++i) {
780          last_out = _first_out[i+1];
781          for (int j = _first_out[i]; j != last_out; ++j) {
782            if (_forward[j]) {
783              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
784              if (c >= MAX) return UNBOUNDED;
785              _excess[i] -= c;
786              _excess[_target[j]] += c;
787            }
788          }
789        }
790      } else {
791        for (int i = 0; i != _root; ++i) {
792          last_out = _first_out[i+1];
793          for (int j = _first_out[i]; j != last_out; ++j) {
794            if (_forward[j] && _scost[j] < 0) {
795              Value c = _upper[j];
796              if (c >= MAX) return UNBOUNDED;
797              _excess[i] -= c;
798              _excess[_target[j]] += c;
799            }
800          }
801        }
802      }
803      Value ex, max_cap = 0;
804      for (int i = 0; i != _res_node_num; ++i) {
805        ex = _excess[i];
806        _excess[i] = 0;
807        if (ex < 0) max_cap -= ex;
808      }
809      for (int j = 0; j != _res_arc_num; ++j) {
810        if (_upper[j] >= MAX) _upper[j] = max_cap;
811      }
812
813      // Initialize the large cost vector and the epsilon parameter
814      _epsilon = 0;
815      LargeCost lc;
816      for (int i = 0; i != _root; ++i) {
817        last_out = _first_out[i+1];
818        for (int j = _first_out[i]; j != last_out; ++j) {
819          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
820          _cost[j] = lc;
821          if (lc > _epsilon) _epsilon = lc;
822        }
823      }
824      _epsilon /= _alpha;
825
826      // Initialize maps for Circulation and remove non-zero lower bounds
827      ConstMap<Arc, Value> low(0);
828      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
829      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
830      ValueArcMap cap(_graph), flow(_graph);
831      ValueNodeMap sup(_graph);
832      for (NodeIt n(_graph); n != INVALID; ++n) {
833        sup[n] = _supply[_node_id[n]];
834      }
835      if (_have_lower) {
836        for (ArcIt a(_graph); a != INVALID; ++a) {
837          int j = _arc_idf[a];
838          Value c = _lower[j];
839          cap[a] = _upper[j] - c;
840          sup[_graph.source(a)] -= c;
841          sup[_graph.target(a)] += c;
842        }
843      } else {
844        for (ArcIt a(_graph); a != INVALID; ++a) {
845          cap[a] = _upper[_arc_idf[a]];
846        }
847      }
848
849      _sup_node_num = 0;
850      for (NodeIt n(_graph); n != INVALID; ++n) {
851        if (sup[n] > 0) ++_sup_node_num;
852      }
853
854      // Find a feasible flow using Circulation
855      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
856        circ(_graph, low, cap, sup);
857      if (!circ.flowMap(flow).run()) return INFEASIBLE;
858
859      // Set residual capacities and handle GEQ supply type
860      if (_sum_supply < 0) {
861        for (ArcIt a(_graph); a != INVALID; ++a) {
862          Value fa = flow[a];
863          _res_cap[_arc_idf[a]] = cap[a] - fa;
864          _res_cap[_arc_idb[a]] = fa;
865          sup[_graph.source(a)] -= fa;
866          sup[_graph.target(a)] += fa;
867        }
868        for (NodeIt n(_graph); n != INVALID; ++n) {
869          _excess[_node_id[n]] = sup[n];
870        }
871        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
872          int u = _target[a];
873          int ra = _reverse[a];
874          _res_cap[a] = -_sum_supply + 1;
875          _res_cap[ra] = -_excess[u];
876          _cost[a] = 0;
877          _cost[ra] = 0;
878          _excess[u] = 0;
879        }
880      } else {
881        for (ArcIt a(_graph); a != INVALID; ++a) {
882          Value fa = flow[a];
883          _res_cap[_arc_idf[a]] = cap[a] - fa;
884          _res_cap[_arc_idb[a]] = fa;
885        }
886        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
887          int ra = _reverse[a];
888          _res_cap[a] = 0;
889          _res_cap[ra] = 0;
890          _cost[a] = 0;
891          _cost[ra] = 0;
892        }
893      }
894
895      // Initialize data structures for buckets
896      _max_rank = _alpha * _res_node_num;
897      _buckets.resize(_max_rank);
898      _bucket_next.resize(_res_node_num + 1);
899      _bucket_prev.resize(_res_node_num + 1);
900      _rank.resize(_res_node_num + 1);
901
902      return OPTIMAL;
903    }
904   
905    // Check if the upper bound is greater or equal to the lower bound
906    // on each arc.
907    bool checkBoundMaps() {
908      for (int j = 0; j != _res_arc_num; ++j) {
909        if (_upper[j] < _lower[j]) return false;
910      }
911      return true;
912    }
913
914    // Execute the algorithm and transform the results
915    void start(Method method) {
916      const int MAX_PARTIAL_PATH_LENGTH = 4;
917
918      switch (method) {
919        case PUSH:
920          startPush();
921          break;
922        case AUGMENT:
923          startAugment(_res_node_num - 1);
924          break;
925        case PARTIAL_AUGMENT:
926          startAugment(MAX_PARTIAL_PATH_LENGTH);
927          break;
928      }
929
930      // Compute node potentials (dual solution)
931      for (int i = 0; i != _res_node_num; ++i) {
932        _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
933      }
934      bool optimal = true;
935      for (int i = 0; optimal && i != _res_node_num; ++i) {
936        LargeCost pi_i = _pi[i];
937        int last_out = _first_out[i+1];
938        for (int j = _first_out[i]; j != last_out; ++j) {
939          if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
940            optimal = false;
941            break;
942          }
943        }
944      }
945
946      if (!optimal) {
947        // Compute node potentials for the original costs with BellmanFord
948        // (if it is necessary)
949        typedef std::pair<int, int> IntPair;
950        StaticDigraph sgr;
951        std::vector<IntPair> arc_vec;
952        std::vector<LargeCost> cost_vec;
953        LargeCostArcMap cost_map(cost_vec);
954
955        arc_vec.clear();
956        cost_vec.clear();
957        for (int j = 0; j != _res_arc_num; ++j) {
958          if (_res_cap[j] > 0) {
959            int u = _source[j], v = _target[j];
960            arc_vec.push_back(IntPair(u, v));
961            cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
962          }
963        }
964        sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
965
966        typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
967          bf(sgr, cost_map);
968        bf.init(0);
969        bf.start();
970
971        for (int i = 0; i != _res_node_num; ++i) {
972          _pi[i] += bf.dist(sgr.node(i));
973        }
974      }
975
976      // Shift potentials to meet the requirements of the GEQ type
977      // optimality conditions
978      LargeCost max_pot = _pi[_root];
979      for (int i = 0; i != _res_node_num; ++i) {
980        if (_pi[i] > max_pot) max_pot = _pi[i];
981      }
982      if (max_pot != 0) {
983        for (int i = 0; i != _res_node_num; ++i) {
984          _pi[i] -= max_pot;
985        }
986      }
987
988      // Handle non-zero lower bounds
989      if (_have_lower) {
990        int limit = _first_out[_root];
991        for (int j = 0; j != limit; ++j) {
992          if (!_forward[j]) _res_cap[j] += _lower[j];
993        }
994      }
995    }
996
997    // Initialize a cost scaling phase
998    void initPhase() {
999      // Saturate arcs not satisfying the optimality condition
1000      for (int u = 0; u != _res_node_num; ++u) {
1001        int last_out = _first_out[u+1];
1002        LargeCost pi_u = _pi[u];
1003        for (int a = _first_out[u]; a != last_out; ++a) {
1004          Value delta = _res_cap[a];
1005          if (delta > 0) {
1006            int v = _target[a];
1007            if (_cost[a] + pi_u - _pi[v] < 0) {
1008              _excess[u] -= delta;
1009              _excess[v] += delta;
1010              _res_cap[a] = 0;
1011              _res_cap[_reverse[a]] += delta;
1012            }
1013          }
1014        }
1015      }
1016
1017      // Find active nodes (i.e. nodes with positive excess)
1018      for (int u = 0; u != _res_node_num; ++u) {
1019        if (_excess[u] > 0) _active_nodes.push_back(u);
1020      }
1021
1022      // Initialize the next arcs
1023      for (int u = 0; u != _res_node_num; ++u) {
1024        _next_out[u] = _first_out[u];
1025      }
1026    }
1027
1028    // Price (potential) refinement heuristic
1029    bool priceRefinement() {
1030
1031      // Stack for stroing the topological order
1032      IntVector stack(_res_node_num);
1033      int stack_top;
1034
1035      // Perform phases
1036      while (topologicalSort(stack, stack_top)) {
1037
1038        // Compute node ranks in the acyclic admissible network and
1039        // store the nodes in buckets
1040        for (int i = 0; i != _res_node_num; ++i) {
1041          _rank[i] = 0;
1042        }
1043        const int bucket_end = _root + 1;
1044        for (int r = 0; r != _max_rank; ++r) {
1045          _buckets[r] = bucket_end;
1046        }
1047        int top_rank = 0;
1048        for ( ; stack_top >= 0; --stack_top) {
1049          int u = stack[stack_top], v;
1050          int rank_u = _rank[u];
1051
1052          LargeCost rc, pi_u = _pi[u];
1053          int last_out = _first_out[u+1];
1054          for (int a = _first_out[u]; a != last_out; ++a) {
1055            if (_res_cap[a] > 0) {
1056              v = _target[a];
1057              rc = _cost[a] + pi_u - _pi[v];
1058              if (rc < 0) {
1059                LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1060                if (nrc < LargeCost(_max_rank)) {
1061                  int new_rank_v = rank_u + static_cast<int>(nrc);
1062                  if (new_rank_v > _rank[v]) {
1063                    _rank[v] = new_rank_v;
1064                  }
1065                }
1066              }
1067            }
1068          }
1069
1070          if (rank_u > 0) {
1071            top_rank = std::max(top_rank, rank_u);
1072            int bfirst = _buckets[rank_u];
1073            _bucket_next[u] = bfirst;
1074            _bucket_prev[bfirst] = u;
1075            _buckets[rank_u] = u;
1076          }
1077        }
1078
1079        // Check if the current flow is epsilon-optimal
1080        if (top_rank == 0) {
1081          return true;
1082        }
1083
1084        // Process buckets in top-down order
1085        for (int rank = top_rank; rank > 0; --rank) {
1086          while (_buckets[rank] != bucket_end) {
1087            // Remove the first node from the current bucket
1088            int u = _buckets[rank];
1089            _buckets[rank] = _bucket_next[u];
1090
1091            // Search the outgoing arcs of u
1092            LargeCost rc, pi_u = _pi[u];
1093            int last_out = _first_out[u+1];
1094            int v, old_rank_v, new_rank_v;
1095            for (int a = _first_out[u]; a != last_out; ++a) {
1096              if (_res_cap[a] > 0) {
1097                v = _target[a];
1098                old_rank_v = _rank[v];
1099
1100                if (old_rank_v < rank) {
1101
1102                  // Compute the new rank of node v
1103                  rc = _cost[a] + pi_u - _pi[v];
1104                  if (rc < 0) {
1105                    new_rank_v = rank;
1106                  } else {
1107                    LargeCost nrc = rc / _epsilon;
1108                    new_rank_v = 0;
1109                    if (nrc < LargeCost(_max_rank)) {
1110                      new_rank_v = rank - 1 - static_cast<int>(nrc);
1111                    }
1112                  }
1113
1114                  // Change the rank of node v
1115                  if (new_rank_v > old_rank_v) {
1116                    _rank[v] = new_rank_v;
1117
1118                    // Remove v from its old bucket
1119                    if (old_rank_v > 0) {
1120                      if (_buckets[old_rank_v] == v) {
1121                        _buckets[old_rank_v] = _bucket_next[v];
1122                      } else {
1123                        int pv = _bucket_prev[v], nv = _bucket_next[v];
1124                        _bucket_next[pv] = nv;
1125                        _bucket_prev[nv] = pv;
1126                      }
1127                    }
1128
1129                    // Insert v into its new bucket
1130                    int nv = _buckets[new_rank_v];
1131                    _bucket_next[v] = nv;
1132                    _bucket_prev[nv] = v;
1133                    _buckets[new_rank_v] = v;
1134                  }
1135                }
1136              }
1137            }
1138
1139            // Refine potential of node u
1140            _pi[u] -= rank * _epsilon;
1141          }
1142        }
1143
1144      }
1145
1146      return false;
1147    }
1148
1149    // Find and cancel cycles in the admissible network and
1150    // determine topological order using DFS
1151    bool topologicalSort(IntVector &stack, int &stack_top) {
1152      const int MAX_CYCLE_CANCEL = 1;
1153
1154      BoolVector reached(_res_node_num, false);
1155      BoolVector processed(_res_node_num, false);
1156      IntVector pred(_res_node_num);
1157      for (int i = 0; i != _res_node_num; ++i) {
1158        _next_out[i] = _first_out[i];
1159      }
1160      stack_top = -1;
1161
1162      int cycle_cnt = 0;
1163      for (int start = 0; start != _res_node_num; ++start) {
1164        if (reached[start]) continue;
1165
1166        // Start DFS search from this start node
1167        pred[start] = -1;
1168        int tip = start, v;
1169        while (true) {
1170          // Check the outgoing arcs of the current tip node
1171          reached[tip] = true;
1172          LargeCost pi_tip = _pi[tip];
1173          int a, last_out = _first_out[tip+1];
1174          for (a = _next_out[tip]; a != last_out; ++a) {
1175            if (_res_cap[a] > 0) {
1176              v = _target[a];
1177              if (_cost[a] + pi_tip - _pi[v] < 0) {
1178                if (!reached[v]) {
1179                  // A new node is reached
1180                  reached[v] = true;
1181                  pred[v] = tip;
1182                  _next_out[tip] = a;
1183                  tip = v;
1184                  a = _next_out[tip];
1185                  last_out = _first_out[tip+1];
1186                  break;
1187                }
1188                else if (!processed[v]) {
1189                  // A cycle is found
1190                  ++cycle_cnt;
1191                  _next_out[tip] = a;
1192
1193                  // Find the minimum residual capacity along the cycle
1194                  Value d, delta = _res_cap[a];
1195                  int u, delta_node = tip;
1196                  for (u = tip; u != v; ) {
1197                    u = pred[u];
1198                    d = _res_cap[_next_out[u]];
1199                    if (d <= delta) {
1200                      delta = d;
1201                      delta_node = u;
1202                    }
1203                  }
1204
1205                  // Augment along the cycle
1206                  _res_cap[a] -= delta;
1207                  _res_cap[_reverse[a]] += delta;
1208                  for (u = tip; u != v; ) {
1209                    u = pred[u];
1210                    int ca = _next_out[u];
1211                    _res_cap[ca] -= delta;
1212                    _res_cap[_reverse[ca]] += delta;
1213                  }
1214
1215                  // Check the maximum number of cycle canceling
1216                  if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1217                    return false;
1218                  }
1219
1220                  // Roll back search to delta_node
1221                  if (delta_node != tip) {
1222                    for (u = tip; u != delta_node; u = pred[u]) {
1223                      reached[u] = false;
1224                    }
1225                    tip = delta_node;
1226                    a = _next_out[tip] + 1;
1227                    last_out = _first_out[tip+1];
1228                    break;
1229                  }
1230                }
1231              }
1232            }
1233          }
1234
1235          // Step back to the previous node
1236          if (a == last_out) {
1237            processed[tip] = true;
1238            stack[++stack_top] = tip;
1239            tip = pred[tip];
1240            if (tip < 0) {
1241              // Finish DFS from the current start node
1242              break;
1243            }
1244            ++_next_out[tip];
1245          }
1246        }
1247
1248      }
1249
1250      return (cycle_cnt == 0);
1251    }
1252
1253    // Global potential update heuristic
1254    void globalUpdate() {
1255      const int bucket_end = _root + 1;
1256
1257      // Initialize buckets
1258      for (int r = 0; r != _max_rank; ++r) {
1259        _buckets[r] = bucket_end;
1260      }
1261      Value total_excess = 0;
1262      int b0 = bucket_end;
1263      for (int i = 0; i != _res_node_num; ++i) {
1264        if (_excess[i] < 0) {
1265          _rank[i] = 0;
1266          _bucket_next[i] = b0;
1267          _bucket_prev[b0] = i;
1268          b0 = i;
1269        } else {
1270          total_excess += _excess[i];
1271          _rank[i] = _max_rank;
1272        }
1273      }
1274      if (total_excess == 0) return;
1275      _buckets[0] = b0;
1276
1277      // Search the buckets
1278      int r = 0;
1279      for ( ; r != _max_rank; ++r) {
1280        while (_buckets[r] != bucket_end) {
1281          // Remove the first node from the current bucket
1282          int u = _buckets[r];
1283          _buckets[r] = _bucket_next[u];
1284
1285          // Search the incomming arcs of u
1286          LargeCost pi_u = _pi[u];
1287          int last_out = _first_out[u+1];
1288          for (int a = _first_out[u]; a != last_out; ++a) {
1289            int ra = _reverse[a];
1290            if (_res_cap[ra] > 0) {
1291              int v = _source[ra];
1292              int old_rank_v = _rank[v];
1293              if (r < old_rank_v) {
1294                // Compute the new rank of v
1295                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1296                int new_rank_v = old_rank_v;
1297                if (nrc < LargeCost(_max_rank)) {
1298                  new_rank_v = r + 1 + static_cast<int>(nrc);
1299                }
1300
1301                // Change the rank of v
1302                if (new_rank_v < old_rank_v) {
1303                  _rank[v] = new_rank_v;
1304                  _next_out[v] = _first_out[v];
1305
1306                  // Remove v from its old bucket
1307                  if (old_rank_v < _max_rank) {
1308                    if (_buckets[old_rank_v] == v) {
1309                      _buckets[old_rank_v] = _bucket_next[v];
1310                    } else {
1311                      int pv = _bucket_prev[v], nv = _bucket_next[v];
1312                      _bucket_next[pv] = nv;
1313                      _bucket_prev[nv] = pv;
1314                    }
1315                  }
1316
1317                  // Insert v into its new bucket
1318                  int nv = _buckets[new_rank_v];
1319                  _bucket_next[v] = nv;
1320                  _bucket_prev[nv] = v;
1321                  _buckets[new_rank_v] = v;
1322                }
1323              }
1324            }
1325          }
1326
1327          // Finish search if there are no more active nodes
1328          if (_excess[u] > 0) {
1329            total_excess -= _excess[u];
1330            if (total_excess <= 0) break;
1331          }
1332        }
1333        if (total_excess <= 0) break;
1334      }
1335
1336      // Relabel nodes
1337      for (int u = 0; u != _res_node_num; ++u) {
1338        int k = std::min(_rank[u], r);
1339        if (k > 0) {
1340          _pi[u] -= _epsilon * k;
1341          _next_out[u] = _first_out[u];
1342        }
1343      }
1344    }
1345
1346    /// Execute the algorithm performing augment and relabel operations
1347    void startAugment(int max_length) {
1348      // Paramters for heuristics
1349      const int PRICE_REFINEMENT_LIMIT = 2;
1350      const double GLOBAL_UPDATE_FACTOR = 1.0;
1351      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1352        (_res_node_num + _sup_node_num * _sup_node_num));
1353      int next_global_update_limit = global_update_skip;
1354
1355      // Perform cost scaling phases
1356      IntVector path;
1357      BoolVector path_arc(_res_arc_num, false);
1358      int relabel_cnt = 0;
1359      int eps_phase_cnt = 0;
1360      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1361                                        1 : _epsilon / _alpha )
1362      {
1363        ++eps_phase_cnt;
1364
1365        // Price refinement heuristic
1366        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1367          if (priceRefinement()) continue;
1368        }
1369
1370        // Initialize current phase
1371        initPhase();
1372
1373        // Perform partial augment and relabel operations
1374        while (true) {
1375          // Select an active node (FIFO selection)
1376          while (_active_nodes.size() > 0 &&
1377                 _excess[_active_nodes.front()] <= 0) {
1378            _active_nodes.pop_front();
1379          }
1380          if (_active_nodes.size() == 0) break;
1381          int start = _active_nodes.front();
1382
1383          // Find an augmenting path from the start node
1384          int tip = start;
1385          while (int(path.size()) < max_length && _excess[tip] >= 0) {
1386            int u;
1387            LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1388            LargeCost pi_tip = _pi[tip];
1389            int last_out = _first_out[tip+1];
1390            for (int a = _next_out[tip]; a != last_out; ++a) {
1391              if (_res_cap[a] > 0) {
1392                u = _target[a];
1393                rc = _cost[a] + pi_tip - _pi[u];
1394                if (rc < 0) {
1395                  path.push_back(a);
1396                  _next_out[tip] = a;
1397                  if (path_arc[a]) {
1398                    goto augment;   // a cycle is found, stop path search
1399                  }
1400                  tip = u;
1401                  path_arc[a] = true;
1402                  goto next_step;
1403                }
1404                else if (rc < min_red_cost) {
1405                  min_red_cost = rc;
1406                }
1407              }
1408            }
1409
1410            // Relabel tip node
1411            if (tip != start) {
1412              int ra = _reverse[path.back()];
1413              min_red_cost =
1414                std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1415            }
1416            last_out = _next_out[tip];
1417            for (int a = _first_out[tip]; a != last_out; ++a) {
1418              if (_res_cap[a] > 0) {
1419                rc = _cost[a] + pi_tip - _pi[_target[a]];
1420                if (rc < min_red_cost) {
1421                  min_red_cost = rc;
1422                }
1423              }
1424            }
1425            _pi[tip] -= min_red_cost + _epsilon;
1426            _next_out[tip] = _first_out[tip];
1427            ++relabel_cnt;
1428
1429            // Step back
1430            if (tip != start) {
1431              int pa = path.back();
1432              path_arc[pa] = false;
1433              tip = _source[pa];
1434              path.pop_back();
1435            }
1436
1437          next_step: ;
1438          }
1439
1440          // Augment along the found path (as much flow as possible)
1441        augment:
1442          Value delta;
1443          int pa, u, v = start;
1444          for (int i = 0; i != int(path.size()); ++i) {
1445            pa = path[i];
1446            u = v;
1447            v = _target[pa];
1448            path_arc[pa] = false;
1449            delta = std::min(_res_cap[pa], _excess[u]);
1450            _res_cap[pa] -= delta;
1451            _res_cap[_reverse[pa]] += delta;
1452            _excess[u] -= delta;
1453            _excess[v] += delta;
1454            if (_excess[v] > 0 && _excess[v] <= delta) {
1455              _active_nodes.push_back(v);
1456            }
1457          }
1458          path.clear();
1459
1460          // Global update heuristic
1461          if (relabel_cnt >= next_global_update_limit) {
1462            globalUpdate();
1463            next_global_update_limit += global_update_skip;
1464          }
1465        }
1466
1467      }
1468
1469    }
1470
1471    /// Execute the algorithm performing push and relabel operations
1472    void startPush() {
1473      // Paramters for heuristics
1474      const int PRICE_REFINEMENT_LIMIT = 2;
1475      const double GLOBAL_UPDATE_FACTOR = 2.0;
1476
1477      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1478        (_res_node_num + _sup_node_num * _sup_node_num));
1479      int next_global_update_limit = global_update_skip;
1480
1481      // Perform cost scaling phases
1482      BoolVector hyper(_res_node_num, false);
1483      LargeCostVector hyper_cost(_res_node_num);
1484      int relabel_cnt = 0;
1485      int eps_phase_cnt = 0;
1486      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1487                                        1 : _epsilon / _alpha )
1488      {
1489        ++eps_phase_cnt;
1490
1491        // Price refinement heuristic
1492        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1493          if (priceRefinement()) continue;
1494        }
1495
1496        // Initialize current phase
1497        initPhase();
1498
1499        // Perform push and relabel operations
1500        while (_active_nodes.size() > 0) {
1501          LargeCost min_red_cost, rc, pi_n;
1502          Value delta;
1503          int n, t, a, last_out = _res_arc_num;
1504
1505        next_node:
1506          // Select an active node (FIFO selection)
1507          n = _active_nodes.front();
1508          last_out = _first_out[n+1];
1509          pi_n = _pi[n];
1510
1511          // Perform push operations if there are admissible arcs
1512          if (_excess[n] > 0) {
1513            for (a = _next_out[n]; a != last_out; ++a) {
1514              if (_res_cap[a] > 0 &&
1515                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
1516                delta = std::min(_res_cap[a], _excess[n]);
1517                t = _target[a];
1518
1519                // Push-look-ahead heuristic
1520                Value ahead = -_excess[t];
1521                int last_out_t = _first_out[t+1];
1522                LargeCost pi_t = _pi[t];
1523                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1524                  if (_res_cap[ta] > 0 &&
1525                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1526                    ahead += _res_cap[ta];
1527                  if (ahead >= delta) break;
1528                }
1529                if (ahead < 0) ahead = 0;
1530
1531                // Push flow along the arc
1532                if (ahead < delta && !hyper[t]) {
1533                  _res_cap[a] -= ahead;
1534                  _res_cap[_reverse[a]] += ahead;
1535                  _excess[n] -= ahead;
1536                  _excess[t] += ahead;
1537                  _active_nodes.push_front(t);
1538                  hyper[t] = true;
1539                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
1540                  _next_out[n] = a;
1541                  goto next_node;
1542                } else {
1543                  _res_cap[a] -= delta;
1544                  _res_cap[_reverse[a]] += delta;
1545                  _excess[n] -= delta;
1546                  _excess[t] += delta;
1547                  if (_excess[t] > 0 && _excess[t] <= delta)
1548                    _active_nodes.push_back(t);
1549                }
1550
1551                if (_excess[n] == 0) {
1552                  _next_out[n] = a;
1553                  goto remove_nodes;
1554                }
1555              }
1556            }
1557            _next_out[n] = a;
1558          }
1559
1560          // Relabel the node if it is still active (or hyper)
1561          if (_excess[n] > 0 || hyper[n]) {
1562             min_red_cost = hyper[n] ? -hyper_cost[n] :
1563               std::numeric_limits<LargeCost>::max();
1564            for (int a = _first_out[n]; a != last_out; ++a) {
1565              if (_res_cap[a] > 0) {
1566                rc = _cost[a] + pi_n - _pi[_target[a]];
1567                if (rc < min_red_cost) {
1568                  min_red_cost = rc;
1569                }
1570              }
1571            }
1572            _pi[n] -= min_red_cost + _epsilon;
1573            _next_out[n] = _first_out[n];
1574            hyper[n] = false;
1575            ++relabel_cnt;
1576          }
1577
1578          // Remove nodes that are not active nor hyper
1579        remove_nodes:
1580          while ( _active_nodes.size() > 0 &&
1581                  _excess[_active_nodes.front()] <= 0 &&
1582                  !hyper[_active_nodes.front()] ) {
1583            _active_nodes.pop_front();
1584          }
1585
1586          // Global update heuristic
1587          if (relabel_cnt >= next_global_update_limit) {
1588            globalUpdate();
1589            for (int u = 0; u != _res_node_num; ++u)
1590              hyper[u] = false;
1591            next_global_update_limit += global_update_skip;
1592          }
1593        }
1594      }
1595    }
1596
1597  }; //class CostScaling
1598
1599  ///@}
1600
1601} //namespace lemon
1602
1603#endif //LEMON_COST_SCALING_H
Note: See TracBrowser for help on using the repository browser.