COIN-OR::LEMON - Graph Library

source: lemon/lemon/cost_scaling.h @ 1192:b84e68af8248

Last change on this file since 1192:b84e68af8248 was 1165:16f55008c863, checked in by Peter Kovacs <kpeter@…>, 8 years ago

Doc improvements for min cost flow algorithms (#437)

File size: 50.9 KB
RevLine 
[956]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
[874]2 *
[956]3 * This file is a part of LEMON, a generic C++ optimization library.
[874]4 *
[956]5 * Copyright (C) 2003-2010
[874]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>
[875]33#include <lemon/static_graph.h>
[874]34#include <lemon/circulation.h>
35#include <lemon/bellman_ford.h>
36
37namespace lemon {
38
[875]39  /// \brief Default traits class of CostScaling algorithm.
40  ///
41  /// Default traits class of CostScaling algorithm.
42  /// \tparam GR Digraph type.
[878]43  /// \tparam V The number type used for flow amounts, capacity bounds
[875]44  /// and supply values. By default it is \c int.
[878]45  /// \tparam C The number type used for costs and potentials.
[875]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
[874]86  /// \addtogroup min_cost_flow_algs
87  /// @{
88
[875]89  /// \brief Implementation of the Cost Scaling algorithm for
90  /// finding a \ref min_cost_flow "minimum cost flow".
[874]91  ///
[875]92  /// \ref CostScaling implements a cost scaling algorithm that performs
[879]93  /// push/augment and relabel operations for finding a \ref min_cost_flow
94  /// "minimum cost flow" \ref amo93networkflows, \ref goldberg90approximation,
[956]95  /// \ref goldberg97efficient, \ref bunnagel98efficient.
[879]96  /// It is a highly efficient primal-dual solution method, which
[875]97  /// can be viewed as the generalization of the \ref Preflow
98  /// "preflow push-relabel" algorithm for the maximum flow problem.
[874]99  ///
[1023]100  /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
[1165]101  /// implementations available in LEMON for solving this problem.
102  /// (For more information, see \ref min_cost_flow_algs "the module page".)
[1023]103  ///
[875]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.
[874]108  ///
[875]109  /// \tparam GR The digraph type the algorithm runs on.
[878]110  /// \tparam V The number type used for flow amounts, capacity bounds
[891]111  /// and supply values in the algorithm. By default, it is \c int.
[878]112  /// \tparam C The number type used for costs and potentials in the
[891]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.
[874]119  ///
[1025]120  /// \warning Both \c V and \c C must be signed number types.
121  /// \warning All input data (capacities, supply values, and costs) must
[875]122  /// be integer.
[1023]123  /// \warning This algorithm does not support negative costs for
124  /// arcs having infinite upper bound.
[876]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.
[875]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
[874]135  class CostScaling
136  {
[875]137  public:
[874]138
[875]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;
[874]145
[875]146    /// \brief The large cost type
147    ///
148    /// The large cost type used for internal computations.
[891]149    /// By default, it is \c long \c long if the \c Cost type is integer,
[875]150    /// otherwise it is \c double.
151    typedef typename TR::LargeCost LargeCost;
[874]152
[875]153    /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
154    typedef TR Traits;
[874]155
156  public:
157
[875]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
[878]171      /// on that arc, however, note that it could actually be bounded
[875]172      /// over the feasible flows, but this algroithm cannot handle
173      /// these cases.
174      UNBOUNDED
175    };
[874]176
[876]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
[1023]186    /// "Partial Augment-Relabel" method is used, which turned out to be
[876]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,
[956]197      /// Partial augment operations are used, i.e. flow is moved on
[876]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
[874]204  private:
205
[875]206    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
[874]207
[875]208    typedef std::vector<int> IntVector;
209    typedef std::vector<Value> ValueVector;
210    typedef std::vector<Cost> CostVector;
211    typedef std::vector<LargeCost> LargeCostVector;
[910]212    typedef std::vector<char> BoolVector;
213    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
[874]214
[875]215  private:
[956]216
[875]217    template <typename KT, typename VT>
[886]218    class StaticVectorMap {
[874]219    public:
[875]220      typedef KT Key;
221      typedef VT Value;
[956]222
[886]223      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
[956]224
[875]225      const Value& operator[](const Key& key) const {
226        return _v[StaticDigraph::id(key)];
[874]227      }
228
[875]229      Value& operator[](const Key& key) {
230        return _v[StaticDigraph::id(key)];
231      }
[956]232
[875]233      void set(const Key& key, const Value& val) {
234        _v[StaticDigraph::id(key)] = val;
[874]235      }
236
[875]237    private:
238      std::vector<Value>& _v;
239    };
240
[886]241    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
[874]242
243  private:
244
[875]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;
[874]252
[875]253    // Parameters of the problem
254    bool _have_lower;
255    Value _sum_supply;
[910]256    int _sup_node_num;
[874]257
[875]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;
[874]283    int _alpha;
284
[910]285    IntVector _buckets;
286    IntVector _bucket_next;
287    IntVector _bucket_prev;
288    IntVector _rank;
289    int _max_rank;
[956]290
[875]291  public:
[956]292
[875]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
[874]300  public:
301
[875]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.
[874]312    ///
[875]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
[941]324  protected:
325
326    CostScaling() {}
327
[875]328  public:
329
330    /// \brief Constructor.
[874]331    ///
[875]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())
[874]340    {
[878]341      // Check the number types
[875]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");
[956]346
[898]347      // Reset data structures
[875]348      reset();
[874]349    }
350
[875]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.
[874]358    ///
[875]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.
[874]362    ///
[875]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];
[874]374      }
375      return *this;
376    }
377
[875]378    /// \brief Set the upper bounds (capacities) on the arcs.
[874]379    ///
[875]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
[878]383    /// unbounded from above).
[874]384    ///
[875]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];
[874]394      }
395      return *this;
396    }
397
[875]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()
[1023]445    /// with a map in which \c k is assigned to \c s, \c -k is
[875]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    }
[956]462
[875]463    /// @}
464
[874]465    /// \name Execution control
[875]466    /// The algorithm can be executed using \ref run().
[874]467
468    /// @{
469
470    /// \brief Run the algorithm.
471    ///
[875]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    ///
[898]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.
[874]488    ///
[876]489    /// \param method The internal method that will be used in the
490    /// algorithm. For more information, see \ref Method.
[1049]491    /// \param factor The cost scaling factor. It must be at least two.
[874]492    ///
[875]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
[878]499    /// is unbounded on that arc, however, note that it could actually be
[875]500    /// bounded over the feasible flows, but this algroithm cannot handle
501    /// these cases.
502    ///
[876]503    /// \see ProblemType, Method
[898]504    /// \see resetParams(), reset()
[1049]505    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
506      LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
[876]507      _alpha = factor;
[875]508      ProblemType pt = init();
509      if (pt != OPTIMAL) return pt;
[876]510      start(method);
[875]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    ///
[898]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.
[875]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    ///
[898]535    ///   // Run again with modified cost map (resetParams() is not called,
[875]536    ///   // so only the cost map have to be set again)
537    ///   cost[e] += 100;
538    ///   cs.costMap(cost).run();
539    ///
[898]540    ///   // Run again from scratch using resetParams()
[875]541    ///   // (the lower bounds will be set to zero on all arcs)
[898]542    ///   cs.resetParams();
[875]543    ///   cs.upperMap(capacity).costMap(cost)
544    ///     .supplyMap(sup).run();
545    /// \endcode
546    ///
547    /// \return <tt>(*this)</tt>
[898]548    ///
549    /// \see reset(), run()
550    CostScaling& resetParams() {
[875]551      for (int i = 0; i != _res_node_num; ++i) {
552        _supply[i] = 0;
[874]553      }
[875]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;
[956]565      }
[875]566      _have_lower = false;
567      return *this;
[874]568    }
569
[1045]570    /// \brief Reset the internal data structures and all the parameters
571    /// that have been given before.
[898]572    ///
[1045]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().
[898]576    ///
[1045]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    ///
[898]586    /// \return <tt>(*this)</tt>
[1045]587    ///
588    /// \see resetParams(), run()
[898]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);
[956]607
[898]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      }
[956]652
[898]653      // Reset parameters
654      resetParams();
655      return *this;
656    }
657
[874]658    /// @}
659
660    /// \name Query Functions
[875]661    /// The results of the algorithm can be obtained using these
[874]662    /// functions.\n
[875]663    /// The \ref run() function must be called before using them.
[874]664
665    /// @{
666
[875]667    /// \brief Return the total cost of the found flow.
[874]668    ///
[875]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.
[874]680    ///
681    /// \pre \ref run() must be called before using this function.
[875]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;
[874]691    }
692
[875]693#ifndef DOXYGEN
694    Cost totalCost() const {
695      return totalCost<Cost>();
[874]696    }
[875]697#endif
[874]698
699    /// \brief Return the flow on the given arc.
700    ///
[875]701    /// This function returns the flow on the given arc.
[874]702    ///
703    /// \pre \ref run() must be called before using this function.
[875]704    Value flow(const Arc& a) const {
705      return _res_cap[_arc_idb[a]];
[874]706    }
707
[1165]708    /// \brief Copy the flow values (the primal solution) into the
709    /// given map.
[874]710    ///
[875]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.
[874]714    ///
715    /// \pre \ref run() must be called before using this function.
[875]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      }
[874]721    }
722
[875]723    /// \brief Return the potential (dual value) of the given node.
[874]724    ///
[875]725    /// This function returns the potential (dual value) of the
726    /// given node.
[874]727    ///
728    /// \pre \ref run() must be called before using this function.
[875]729    Cost potential(const Node& n) const {
730      return static_cast<Cost>(_pi[_node_id[n]]);
731    }
732
[1165]733    /// \brief Copy the potential values (the dual solution) into the
734    /// given map.
[875]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      }
[874]747    }
748
749    /// @}
750
751  private:
752
[875]753    // Initialize the algorithm
754    ProblemType init() {
[887]755      if (_res_node_num <= 1) return INFEASIBLE;
[875]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];
[874]761      }
[875]762      if (_sum_supply > 0) return INFEASIBLE;
[956]763
[875]764
765      // Initialize vectors
766      for (int i = 0; i != _res_node_num; ++i) {
767        _pi[i] = 0;
768        _excess[i] = _supply[i];
769      }
[956]770
[875]771      // Remove infinite upper bounds and check negative arcs
772      const Value MAX = std::numeric_limits<Value>::max();
773      int last_out;
774      if (_have_lower) {
775        for (int i = 0; i != _root; ++i) {
776          last_out = _first_out[i+1];
777          for (int j = _first_out[i]; j != last_out; ++j) {
778            if (_forward[j]) {
779              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
780              if (c >= MAX) return UNBOUNDED;
781              _excess[i] -= c;
782              _excess[_target[j]] += c;
783            }
784          }
785        }
786      } else {
787        for (int i = 0; i != _root; ++i) {
788          last_out = _first_out[i+1];
789          for (int j = _first_out[i]; j != last_out; ++j) {
790            if (_forward[j] && _scost[j] < 0) {
791              Value c = _upper[j];
792              if (c >= MAX) return UNBOUNDED;
793              _excess[i] -= c;
794              _excess[_target[j]] += c;
795            }
796          }
797        }
798      }
799      Value ex, max_cap = 0;
800      for (int i = 0; i != _res_node_num; ++i) {
801        ex = _excess[i];
802        _excess[i] = 0;
803        if (ex < 0) max_cap -= ex;
804      }
805      for (int j = 0; j != _res_arc_num; ++j) {
806        if (_upper[j] >= MAX) _upper[j] = max_cap;
[874]807      }
808
[875]809      // Initialize the large cost vector and the epsilon parameter
810      _epsilon = 0;
811      LargeCost lc;
812      for (int i = 0; i != _root; ++i) {
813        last_out = _first_out[i+1];
814        for (int j = _first_out[i]; j != last_out; ++j) {
815          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
816          _cost[j] = lc;
817          if (lc > _epsilon) _epsilon = lc;
818        }
819      }
820      _epsilon /= _alpha;
[874]821
[875]822      // Initialize maps for Circulation and remove non-zero lower bounds
823      ConstMap<Arc, Value> low(0);
824      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
825      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
826      ValueArcMap cap(_graph), flow(_graph);
827      ValueNodeMap sup(_graph);
828      for (NodeIt n(_graph); n != INVALID; ++n) {
829        sup[n] = _supply[_node_id[n]];
[874]830      }
[875]831      if (_have_lower) {
832        for (ArcIt a(_graph); a != INVALID; ++a) {
833          int j = _arc_idf[a];
834          Value c = _lower[j];
835          cap[a] = _upper[j] - c;
836          sup[_graph.source(a)] -= c;
837          sup[_graph.target(a)] += c;
838        }
839      } else {
840        for (ArcIt a(_graph); a != INVALID; ++a) {
841          cap[a] = _upper[_arc_idf[a]];
842        }
843      }
[874]844
[910]845      _sup_node_num = 0;
846      for (NodeIt n(_graph); n != INVALID; ++n) {
847        if (sup[n] > 0) ++_sup_node_num;
848      }
849
[874]850      // Find a feasible flow using Circulation
[875]851      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
852        circ(_graph, low, cap, sup);
853      if (!circ.flowMap(flow).run()) return INFEASIBLE;
854
855      // Set residual capacities and handle GEQ supply type
856      if (_sum_supply < 0) {
857        for (ArcIt a(_graph); a != INVALID; ++a) {
858          Value fa = flow[a];
859          _res_cap[_arc_idf[a]] = cap[a] - fa;
860          _res_cap[_arc_idb[a]] = fa;
861          sup[_graph.source(a)] -= fa;
862          sup[_graph.target(a)] += fa;
863        }
864        for (NodeIt n(_graph); n != INVALID; ++n) {
865          _excess[_node_id[n]] = sup[n];
866        }
867        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
868          int u = _target[a];
869          int ra = _reverse[a];
870          _res_cap[a] = -_sum_supply + 1;
871          _res_cap[ra] = -_excess[u];
872          _cost[a] = 0;
873          _cost[ra] = 0;
874          _excess[u] = 0;
875        }
876      } else {
877        for (ArcIt a(_graph); a != INVALID; ++a) {
878          Value fa = flow[a];
879          _res_cap[_arc_idf[a]] = cap[a] - fa;
880          _res_cap[_arc_idb[a]] = fa;
881        }
882        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
883          int ra = _reverse[a];
[910]884          _res_cap[a] = 0;
[875]885          _res_cap[ra] = 0;
886          _cost[a] = 0;
887          _cost[ra] = 0;
888        }
889      }
[956]890
891      // Initialize data structures for buckets
[910]892      _max_rank = _alpha * _res_node_num;
893      _buckets.resize(_max_rank);
894      _bucket_next.resize(_res_node_num + 1);
895      _bucket_prev.resize(_res_node_num + 1);
896      _rank.resize(_res_node_num + 1);
[956]897
[1045]898      return OPTIMAL;
899    }
900
901    // Execute the algorithm and transform the results
902    void start(Method method) {
903      const int MAX_PARTIAL_PATH_LENGTH = 4;
904
[876]905      switch (method) {
906        case PUSH:
907          startPush();
908          break;
909        case AUGMENT:
[1041]910          startAugment(_res_node_num - 1);
[876]911          break;
912        case PARTIAL_AUGMENT:
[1045]913          startAugment(MAX_PARTIAL_PATH_LENGTH);
[876]914          break;
[875]915      }
916
[1048]917      // Compute node potentials (dual solution)
918      for (int i = 0; i != _res_node_num; ++i) {
919        _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
920      }
921      bool optimal = true;
922      for (int i = 0; optimal && i != _res_node_num; ++i) {
923        LargeCost pi_i = _pi[i];
924        int last_out = _first_out[i+1];
925        for (int j = _first_out[i]; j != last_out; ++j) {
926          if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
927            optimal = false;
928            break;
929          }
[875]930        }
931      }
932
[1048]933      if (!optimal) {
934        // Compute node potentials for the original costs with BellmanFord
935        // (if it is necessary)
936        typedef std::pair<int, int> IntPair;
937        StaticDigraph sgr;
938        std::vector<IntPair> arc_vec;
939        std::vector<LargeCost> cost_vec;
940        LargeCostArcMap cost_map(cost_vec);
941
942        arc_vec.clear();
943        cost_vec.clear();
944        for (int j = 0; j != _res_arc_num; ++j) {
945          if (_res_cap[j] > 0) {
946            int u = _source[j], v = _target[j];
947            arc_vec.push_back(IntPair(u, v));
948            cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
949          }
950        }
951        sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
952
953        typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
954          bf(sgr, cost_map);
955        bf.init(0);
956        bf.start();
957
958        for (int i = 0; i != _res_node_num; ++i) {
959          _pi[i] += bf.dist(sgr.node(i));
960        }
961      }
962
963      // Shift potentials to meet the requirements of the GEQ type
964      // optimality conditions
965      LargeCost max_pot = _pi[_root];
966      for (int i = 0; i != _res_node_num; ++i) {
967        if (_pi[i] > max_pot) max_pot = _pi[i];
968      }
969      if (max_pot != 0) {
970        for (int i = 0; i != _res_node_num; ++i) {
971          _pi[i] -= max_pot;
972        }
973      }
[875]974
975      // Handle non-zero lower bounds
976      if (_have_lower) {
977        int limit = _first_out[_root];
978        for (int j = 0; j != limit; ++j) {
979          if (!_forward[j]) _res_cap[j] += _lower[j];
980        }
981      }
[874]982    }
[956]983
[910]984    // Initialize a cost scaling phase
985    void initPhase() {
986      // Saturate arcs not satisfying the optimality condition
987      for (int u = 0; u != _res_node_num; ++u) {
988        int last_out = _first_out[u+1];
989        LargeCost pi_u = _pi[u];
990        for (int a = _first_out[u]; a != last_out; ++a) {
[1045]991          Value delta = _res_cap[a];
992          if (delta > 0) {
993            int v = _target[a];
994            if (_cost[a] + pi_u - _pi[v] < 0) {
995              _excess[u] -= delta;
996              _excess[v] += delta;
997              _res_cap[a] = 0;
998              _res_cap[_reverse[a]] += delta;
999            }
[910]1000          }
1001        }
1002      }
[956]1003
[910]1004      // Find active nodes (i.e. nodes with positive excess)
1005      for (int u = 0; u != _res_node_num; ++u) {
1006        if (_excess[u] > 0) _active_nodes.push_back(u);
1007      }
1008
1009      // Initialize the next arcs
1010      for (int u = 0; u != _res_node_num; ++u) {
1011        _next_out[u] = _first_out[u];
1012      }
1013    }
[956]1014
[1047]1015    // Price (potential) refinement heuristic
1016    bool priceRefinement() {
[910]1017
[1047]1018      // Stack for stroing the topological order
1019      IntVector stack(_res_node_num);
1020      int stack_top;
1021
1022      // Perform phases
1023      while (topologicalSort(stack, stack_top)) {
1024
1025        // Compute node ranks in the acyclic admissible network and
1026        // store the nodes in buckets
1027        for (int i = 0; i != _res_node_num; ++i) {
1028          _rank[i] = 0;
[910]1029        }
[1047]1030        const int bucket_end = _root + 1;
1031        for (int r = 0; r != _max_rank; ++r) {
1032          _buckets[r] = bucket_end;
1033        }
1034        int top_rank = 0;
1035        for ( ; stack_top >= 0; --stack_top) {
1036          int u = stack[stack_top], v;
1037          int rank_u = _rank[u];
1038
1039          LargeCost rc, pi_u = _pi[u];
1040          int last_out = _first_out[u+1];
1041          for (int a = _first_out[u]; a != last_out; ++a) {
1042            if (_res_cap[a] > 0) {
1043              v = _target[a];
1044              rc = _cost[a] + pi_u - _pi[v];
1045              if (rc < 0) {
1046                LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1047                if (nrc < LargeCost(_max_rank)) {
1048                  int new_rank_v = rank_u + static_cast<int>(nrc);
1049                  if (new_rank_v > _rank[v]) {
1050                    _rank[v] = new_rank_v;
1051                  }
1052                }
1053              }
1054            }
1055          }
1056
1057          if (rank_u > 0) {
1058            top_rank = std::max(top_rank, rank_u);
1059            int bfirst = _buckets[rank_u];
1060            _bucket_next[u] = bfirst;
1061            _bucket_prev[bfirst] = u;
1062            _buckets[rank_u] = u;
1063          }
1064        }
1065
1066        // Check if the current flow is epsilon-optimal
1067        if (top_rank == 0) {
1068          return true;
1069        }
1070
1071        // Process buckets in top-down order
1072        for (int rank = top_rank; rank > 0; --rank) {
1073          while (_buckets[rank] != bucket_end) {
1074            // Remove the first node from the current bucket
1075            int u = _buckets[rank];
1076            _buckets[rank] = _bucket_next[u];
1077
1078            // Search the outgoing arcs of u
1079            LargeCost rc, pi_u = _pi[u];
1080            int last_out = _first_out[u+1];
1081            int v, old_rank_v, new_rank_v;
1082            for (int a = _first_out[u]; a != last_out; ++a) {
1083              if (_res_cap[a] > 0) {
1084                v = _target[a];
1085                old_rank_v = _rank[v];
1086
1087                if (old_rank_v < rank) {
1088
1089                  // Compute the new rank of node v
1090                  rc = _cost[a] + pi_u - _pi[v];
1091                  if (rc < 0) {
1092                    new_rank_v = rank;
1093                  } else {
1094                    LargeCost nrc = rc / _epsilon;
1095                    new_rank_v = 0;
1096                    if (nrc < LargeCost(_max_rank)) {
1097                      new_rank_v = rank - 1 - static_cast<int>(nrc);
1098                    }
1099                  }
1100
1101                  // Change the rank of node v
1102                  if (new_rank_v > old_rank_v) {
1103                    _rank[v] = new_rank_v;
1104
1105                    // Remove v from its old bucket
1106                    if (old_rank_v > 0) {
1107                      if (_buckets[old_rank_v] == v) {
1108                        _buckets[old_rank_v] = _bucket_next[v];
1109                      } else {
1110                        int pv = _bucket_prev[v], nv = _bucket_next[v];
1111                        _bucket_next[pv] = nv;
1112                        _bucket_prev[nv] = pv;
1113                      }
1114                    }
1115
1116                    // Insert v into its new bucket
1117                    int nv = _buckets[new_rank_v];
1118                    _bucket_next[v] = nv;
1119                    _bucket_prev[nv] = v;
1120                    _buckets[new_rank_v] = v;
1121                  }
1122                }
1123              }
1124            }
1125
1126            // Refine potential of node u
1127            _pi[u] -= rank * _epsilon;
1128          }
1129        }
1130
[910]1131      }
1132
[1047]1133      return false;
1134    }
1135
1136    // Find and cancel cycles in the admissible network and
1137    // determine topological order using DFS
1138    bool topologicalSort(IntVector &stack, int &stack_top) {
1139      const int MAX_CYCLE_CANCEL = 1;
1140
1141      BoolVector reached(_res_node_num, false);
1142      BoolVector processed(_res_node_num, false);
1143      IntVector pred(_res_node_num);
1144      for (int i = 0; i != _res_node_num; ++i) {
1145        _next_out[i] = _first_out[i];
[910]1146      }
[1047]1147      stack_top = -1;
1148
1149      int cycle_cnt = 0;
1150      for (int start = 0; start != _res_node_num; ++start) {
1151        if (reached[start]) continue;
1152
1153        // Start DFS search from this start node
1154        pred[start] = -1;
1155        int tip = start, v;
1156        while (true) {
1157          // Check the outgoing arcs of the current tip node
1158          reached[tip] = true;
1159          LargeCost pi_tip = _pi[tip];
1160          int a, last_out = _first_out[tip+1];
1161          for (a = _next_out[tip]; a != last_out; ++a) {
1162            if (_res_cap[a] > 0) {
1163              v = _target[a];
1164              if (_cost[a] + pi_tip - _pi[v] < 0) {
1165                if (!reached[v]) {
1166                  // A new node is reached
1167                  reached[v] = true;
1168                  pred[v] = tip;
1169                  _next_out[tip] = a;
1170                  tip = v;
1171                  a = _next_out[tip];
1172                  last_out = _first_out[tip+1];
1173                  break;
1174                }
1175                else if (!processed[v]) {
1176                  // A cycle is found
1177                  ++cycle_cnt;
1178                  _next_out[tip] = a;
1179
1180                  // Find the minimum residual capacity along the cycle
1181                  Value d, delta = _res_cap[a];
1182                  int u, delta_node = tip;
1183                  for (u = tip; u != v; ) {
1184                    u = pred[u];
1185                    d = _res_cap[_next_out[u]];
1186                    if (d <= delta) {
1187                      delta = d;
1188                      delta_node = u;
1189                    }
1190                  }
1191
1192                  // Augment along the cycle
1193                  _res_cap[a] -= delta;
1194                  _res_cap[_reverse[a]] += delta;
1195                  for (u = tip; u != v; ) {
1196                    u = pred[u];
1197                    int ca = _next_out[u];
1198                    _res_cap[ca] -= delta;
1199                    _res_cap[_reverse[ca]] += delta;
1200                  }
1201
1202                  // Check the maximum number of cycle canceling
1203                  if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1204                    return false;
1205                  }
1206
1207                  // Roll back search to delta_node
1208                  if (delta_node != tip) {
1209                    for (u = tip; u != delta_node; u = pred[u]) {
1210                      reached[u] = false;
1211                    }
1212                    tip = delta_node;
1213                    a = _next_out[tip] + 1;
1214                    last_out = _first_out[tip+1];
1215                    break;
1216                  }
1217                }
1218              }
1219            }
1220          }
1221
1222          // Step back to the previous node
1223          if (a == last_out) {
1224            processed[tip] = true;
1225            stack[++stack_top] = tip;
1226            tip = pred[tip];
1227            if (tip < 0) {
1228              // Finish DFS from the current start node
1229              break;
1230            }
1231            ++_next_out[tip];
1232          }
1233        }
1234
1235      }
1236
1237      return (cycle_cnt == 0);
[910]1238    }
1239
1240    // Global potential update heuristic
1241    void globalUpdate() {
[1045]1242      const int bucket_end = _root + 1;
[956]1243
[910]1244      // Initialize buckets
1245      for (int r = 0; r != _max_rank; ++r) {
1246        _buckets[r] = bucket_end;
1247      }
1248      Value total_excess = 0;
[1045]1249      int b0 = bucket_end;
[910]1250      for (int i = 0; i != _res_node_num; ++i) {
1251        if (_excess[i] < 0) {
1252          _rank[i] = 0;
[1045]1253          _bucket_next[i] = b0;
1254          _bucket_prev[b0] = i;
1255          b0 = i;
[910]1256        } else {
1257          total_excess += _excess[i];
1258          _rank[i] = _max_rank;
1259        }
1260      }
1261      if (total_excess == 0) return;
[1045]1262      _buckets[0] = b0;
[910]1263
1264      // Search the buckets
1265      int r = 0;
1266      for ( ; r != _max_rank; ++r) {
1267        while (_buckets[r] != bucket_end) {
1268          // Remove the first node from the current bucket
1269          int u = _buckets[r];
1270          _buckets[r] = _bucket_next[u];
[956]1271
[910]1272          // Search the incomming arcs of u
1273          LargeCost pi_u = _pi[u];
1274          int last_out = _first_out[u+1];
1275          for (int a = _first_out[u]; a != last_out; ++a) {
1276            int ra = _reverse[a];
1277            if (_res_cap[ra] > 0) {
1278              int v = _source[ra];
1279              int old_rank_v = _rank[v];
1280              if (r < old_rank_v) {
1281                // Compute the new rank of v
1282                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1283                int new_rank_v = old_rank_v;
[1045]1284                if (nrc < LargeCost(_max_rank)) {
1285                  new_rank_v = r + 1 + static_cast<int>(nrc);
1286                }
[956]1287
[910]1288                // Change the rank of v
1289                if (new_rank_v < old_rank_v) {
1290                  _rank[v] = new_rank_v;
1291                  _next_out[v] = _first_out[v];
[956]1292
[910]1293                  // Remove v from its old bucket
1294                  if (old_rank_v < _max_rank) {
1295                    if (_buckets[old_rank_v] == v) {
1296                      _buckets[old_rank_v] = _bucket_next[v];
1297                    } else {
[1045]1298                      int pv = _bucket_prev[v], nv = _bucket_next[v];
1299                      _bucket_next[pv] = nv;
1300                      _bucket_prev[nv] = pv;
[910]1301                    }
1302                  }
[956]1303
[1045]1304                  // Insert v into its new bucket
1305                  int nv = _buckets[new_rank_v];
1306                  _bucket_next[v] = nv;
1307                  _bucket_prev[nv] = v;
[910]1308                  _buckets[new_rank_v] = v;
1309                }
1310              }
1311            }
1312          }
1313
1314          // Finish search if there are no more active nodes
1315          if (_excess[u] > 0) {
1316            total_excess -= _excess[u];
1317            if (total_excess <= 0) break;
1318          }
1319        }
1320        if (total_excess <= 0) break;
1321      }
[956]1322
[910]1323      // Relabel nodes
1324      for (int u = 0; u != _res_node_num; ++u) {
1325        int k = std::min(_rank[u], r);
1326        if (k > 0) {
1327          _pi[u] -= _epsilon * k;
1328          _next_out[u] = _first_out[u];
1329        }
1330      }
1331    }
[874]1332
[876]1333    /// Execute the algorithm performing augment and relabel operations
[1041]1334    void startAugment(int max_length) {
[874]1335      // Paramters for heuristics
[1047]1336      const int PRICE_REFINEMENT_LIMIT = 2;
[1046]1337      const double GLOBAL_UPDATE_FACTOR = 1.0;
1338      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
[910]1339        (_res_node_num + _sup_node_num * _sup_node_num));
[1046]1340      int next_global_update_limit = global_update_skip;
[956]1341
[875]1342      // Perform cost scaling phases
[1046]1343      IntVector path;
1344      BoolVector path_arc(_res_arc_num, false);
1345      int relabel_cnt = 0;
[1047]1346      int eps_phase_cnt = 0;
[874]1347      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1348                                        1 : _epsilon / _alpha )
1349      {
[1047]1350        ++eps_phase_cnt;
1351
1352        // Price refinement heuristic
1353        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1354          if (priceRefinement()) continue;
[874]1355        }
[956]1356
[910]1357        // Initialize current phase
1358        initPhase();
[956]1359
[874]1360        // Perform partial augment and relabel operations
[875]1361        while (true) {
[874]1362          // Select an active node (FIFO selection)
[875]1363          while (_active_nodes.size() > 0 &&
1364                 _excess[_active_nodes.front()] <= 0) {
1365            _active_nodes.pop_front();
[874]1366          }
[875]1367          if (_active_nodes.size() == 0) break;
1368          int start = _active_nodes.front();
[874]1369
1370          // Find an augmenting path from the start node
[875]1371          int tip = start;
[1046]1372          while (int(path.size()) < max_length && _excess[tip] >= 0) {
[875]1373            int u;
[1046]1374            LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1375            LargeCost pi_tip = _pi[tip];
[910]1376            int last_out = _first_out[tip+1];
[875]1377            for (int a = _next_out[tip]; a != last_out; ++a) {
[1046]1378              if (_res_cap[a] > 0) {
1379                u = _target[a];
1380                rc = _cost[a] + pi_tip - _pi[u];
1381                if (rc < 0) {
1382                  path.push_back(a);
1383                  _next_out[tip] = a;
1384                  if (path_arc[a]) {
1385                    goto augment;   // a cycle is found, stop path search
1386                  }
1387                  tip = u;
1388                  path_arc[a] = true;
1389                  goto next_step;
1390                }
1391                else if (rc < min_red_cost) {
1392                  min_red_cost = rc;
1393                }
[874]1394              }
1395            }
1396
1397            // Relabel tip node
[910]1398            if (tip != start) {
1399              int ra = _reverse[path.back()];
[1046]1400              min_red_cost =
1401                std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
[910]1402            }
[1046]1403            last_out = _next_out[tip];
[875]1404            for (int a = _first_out[tip]; a != last_out; ++a) {
[1046]1405              if (_res_cap[a] > 0) {
1406                rc = _cost[a] + pi_tip - _pi[_target[a]];
1407                if (rc < min_red_cost) {
1408                  min_red_cost = rc;
1409                }
[875]1410              }
[874]1411            }
[875]1412            _pi[tip] -= min_red_cost + _epsilon;
1413            _next_out[tip] = _first_out[tip];
[910]1414            ++relabel_cnt;
[874]1415
1416            // Step back
1417            if (tip != start) {
[1046]1418              int pa = path.back();
1419              path_arc[pa] = false;
1420              tip = _source[pa];
[910]1421              path.pop_back();
[874]1422            }
1423
[875]1424          next_step: ;
[874]1425          }
1426
1427          // Augment along the found path (as much flow as possible)
[1046]1428        augment:
[875]1429          Value delta;
[910]1430          int pa, u, v = start;
1431          for (int i = 0; i != int(path.size()); ++i) {
1432            pa = path[i];
[875]1433            u = v;
[910]1434            v = _target[pa];
[1046]1435            path_arc[pa] = false;
[875]1436            delta = std::min(_res_cap[pa], _excess[u]);
1437            _res_cap[pa] -= delta;
1438            _res_cap[_reverse[pa]] += delta;
1439            _excess[u] -= delta;
1440            _excess[v] += delta;
[1046]1441            if (_excess[v] > 0 && _excess[v] <= delta) {
[875]1442              _active_nodes.push_back(v);
[1046]1443            }
[874]1444          }
[1046]1445          path.clear();
[910]1446
1447          // Global update heuristic
[1046]1448          if (relabel_cnt >= next_global_update_limit) {
[910]1449            globalUpdate();
[1046]1450            next_global_update_limit += global_update_skip;
[910]1451          }
[874]1452        }
[1046]1453
[874]1454      }
[1046]1455
[874]1456    }
1457
[875]1458    /// Execute the algorithm performing push and relabel operations
[876]1459    void startPush() {
[874]1460      // Paramters for heuristics
[1047]1461      const int PRICE_REFINEMENT_LIMIT = 2;
[910]1462      const double GLOBAL_UPDATE_FACTOR = 2.0;
[874]1463
[1046]1464      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
[910]1465        (_res_node_num + _sup_node_num * _sup_node_num));
[1046]1466      int next_global_update_limit = global_update_skip;
[956]1467
[875]1468      // Perform cost scaling phases
1469      BoolVector hyper(_res_node_num, false);
[910]1470      LargeCostVector hyper_cost(_res_node_num);
[1046]1471      int relabel_cnt = 0;
[1047]1472      int eps_phase_cnt = 0;
[874]1473      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1474                                        1 : _epsilon / _alpha )
1475      {
[1047]1476        ++eps_phase_cnt;
1477
1478        // Price refinement heuristic
1479        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1480          if (priceRefinement()) continue;
[874]1481        }
[956]1482
[910]1483        // Initialize current phase
1484        initPhase();
[874]1485
1486        // Perform push and relabel operations
[875]1487        while (_active_nodes.size() > 0) {
[910]1488          LargeCost min_red_cost, rc, pi_n;
[875]1489          Value delta;
1490          int n, t, a, last_out = _res_arc_num;
1491
[910]1492        next_node:
[874]1493          // Select an active node (FIFO selection)
[875]1494          n = _active_nodes.front();
[910]1495          last_out = _first_out[n+1];
1496          pi_n = _pi[n];
[956]1497
[874]1498          // Perform push operations if there are admissible arcs
[875]1499          if (_excess[n] > 0) {
1500            for (a = _next_out[n]; a != last_out; ++a) {
1501              if (_res_cap[a] > 0 &&
[910]1502                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
[875]1503                delta = std::min(_res_cap[a], _excess[n]);
1504                t = _target[a];
[874]1505
1506                // Push-look-ahead heuristic
[875]1507                Value ahead = -_excess[t];
[910]1508                int last_out_t = _first_out[t+1];
1509                LargeCost pi_t = _pi[t];
[875]1510                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
[956]1511                  if (_res_cap[ta] > 0 &&
[910]1512                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
[875]1513                    ahead += _res_cap[ta];
1514                  if (ahead >= delta) break;
[874]1515                }
1516                if (ahead < 0) ahead = 0;
1517
1518                // Push flow along the arc
[910]1519                if (ahead < delta && !hyper[t]) {
[875]1520                  _res_cap[a] -= ahead;
1521                  _res_cap[_reverse[a]] += ahead;
[874]1522                  _excess[n] -= ahead;
1523                  _excess[t] += ahead;
[875]1524                  _active_nodes.push_front(t);
[874]1525                  hyper[t] = true;
[910]1526                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
[875]1527                  _next_out[n] = a;
1528                  goto next_node;
[874]1529                } else {
[875]1530                  _res_cap[a] -= delta;
1531                  _res_cap[_reverse[a]] += delta;
[874]1532                  _excess[n] -= delta;
1533                  _excess[t] += delta;
1534                  if (_excess[t] > 0 && _excess[t] <= delta)
[875]1535                    _active_nodes.push_back(t);
[874]1536                }
1537
[875]1538                if (_excess[n] == 0) {
1539                  _next_out[n] = a;
1540                  goto remove_nodes;
1541                }
[874]1542              }
1543            }
[875]1544            _next_out[n] = a;
[874]1545          }
1546
1547          // Relabel the node if it is still active (or hyper)
[875]1548          if (_excess[n] > 0 || hyper[n]) {
[910]1549             min_red_cost = hyper[n] ? -hyper_cost[n] :
1550               std::numeric_limits<LargeCost>::max();
[875]1551            for (int a = _first_out[n]; a != last_out; ++a) {
[1046]1552              if (_res_cap[a] > 0) {
1553                rc = _cost[a] + pi_n - _pi[_target[a]];
1554                if (rc < min_red_cost) {
1555                  min_red_cost = rc;
1556                }
[875]1557              }
[874]1558            }
[875]1559            _pi[n] -= min_red_cost + _epsilon;
[910]1560            _next_out[n] = _first_out[n];
[874]1561            hyper[n] = false;
[910]1562            ++relabel_cnt;
[874]1563          }
[956]1564
[874]1565          // Remove nodes that are not active nor hyper
[875]1566        remove_nodes:
1567          while ( _active_nodes.size() > 0 &&
1568                  _excess[_active_nodes.front()] <= 0 &&
1569                  !hyper[_active_nodes.front()] ) {
1570            _active_nodes.pop_front();
[874]1571          }
[956]1572
[910]1573          // Global update heuristic
[1046]1574          if (relabel_cnt >= next_global_update_limit) {
[910]1575            globalUpdate();
1576            for (int u = 0; u != _res_node_num; ++u)
1577              hyper[u] = false;
[1046]1578            next_global_update_limit += global_update_skip;
[910]1579          }
[874]1580        }
1581      }
1582    }
1583
1584  }; //class CostScaling
1585
1586  ///@}
1587
1588} //namespace lemon
1589
1590#endif //LEMON_COST_SCALING_H
Note: See TracBrowser for help on using the repository browser.