COIN-OR::LEMON - Graph Library

source: lemon/lemon/cost_scaling.h @ 1254:c5cd8960df74

Last change on this file since 1254:c5cd8960df74 was 1254:c5cd8960df74, checked in by Peter Kovacs <kpeter@…>, 11 years ago

Use m instead of e for denoting the number of arcs/edges (#463)

File size: 51.5 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" \cite amo93networkflows, \cite goldberg90approximation,
95  /// \cite goldberg97efficient, \cite bunnagel98efficient.
96  /// It is a highly efficient primal-dual solution method, which
97  /// can be viewed as the generalization of the \ref Preflow
98  /// "preflow push-relabel" algorithm for the maximum flow problem.
99  /// It is a polynomial algorithm, its running time complexity is
100  /// \f$O(n^2m\log(nK))\f$, where <i>K</i> denotes the maximum arc cost.
101  ///
102  /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
103  /// implementations available in LEMON for solving this problem.
104  /// (For more information, see \ref min_cost_flow_algs "the module page".)
105  ///
106  /// Most of the parameters of the problem (except for the digraph)
107  /// can be given using separate functions, and the algorithm can be
108  /// executed using the \ref run() function. If some parameters are not
109  /// specified, then default values will be used.
110  ///
111  /// \tparam GR The digraph type the algorithm runs on.
112  /// \tparam V The number type used for flow amounts, capacity bounds
113  /// and supply values in the algorithm. By default, it is \c int.
114  /// \tparam C The number type used for costs and potentials in the
115  /// algorithm. By default, it is the same as \c V.
116  /// \tparam TR The traits class that defines various types used by the
117  /// algorithm. By default, it is \ref CostScalingDefaultTraits
118  /// "CostScalingDefaultTraits<GR, V, C>".
119  /// In most cases, this parameter should not be set directly,
120  /// consider to use the named template parameters instead.
121  ///
122  /// \warning Both \c V and \c C must be signed number types.
123  /// \warning All input data (capacities, supply values, and costs) must
124  /// be integer.
125  /// \warning This algorithm does not support negative costs for
126  /// arcs having infinite upper bound.
127  ///
128  /// \note %CostScaling provides three different internal methods,
129  /// from which the most efficient one is used by default.
130  /// For more information, see \ref Method.
131#ifdef DOXYGEN
132  template <typename GR, typename V, typename C, typename TR>
133#else
134  template < typename GR, typename V = int, typename C = V,
135             typename TR = CostScalingDefaultTraits<GR, V, C> >
136#endif
137  class CostScaling
138  {
139  public:
140
141    /// The type of the digraph
142    typedef typename TR::Digraph Digraph;
143    /// The type of the flow amounts, capacity bounds and supply values
144    typedef typename TR::Value Value;
145    /// The type of the arc costs
146    typedef typename TR::Cost Cost;
147
148    /// \brief The large cost type
149    ///
150    /// The large cost type used for internal computations.
151    /// By default, it is \c long \c long if the \c Cost type is integer,
152    /// otherwise it is \c double.
153    typedef typename TR::LargeCost LargeCost;
154
155    /// \brief The \ref lemon::CostScalingDefaultTraits "traits class"
156    /// of the algorithm
157    typedef TR Traits;
158
159  public:
160
161    /// \brief Problem type constants for the \c run() function.
162    ///
163    /// Enum type containing the problem type constants that can be
164    /// returned by the \ref run() function of the algorithm.
165    enum ProblemType {
166      /// The problem has no feasible solution (flow).
167      INFEASIBLE,
168      /// The problem has optimal solution (i.e. it is feasible and
169      /// bounded), and the algorithm has found optimal flow and node
170      /// potentials (primal and dual solutions).
171      OPTIMAL,
172      /// The digraph contains an arc of negative cost and infinite
173      /// upper bound. It means that the objective function is unbounded
174      /// on that arc, however, note that it could actually be bounded
175      /// over the feasible flows, but this algroithm cannot handle
176      /// these cases.
177      UNBOUNDED
178    };
179
180    /// \brief Constants for selecting the internal method.
181    ///
182    /// Enum type containing constants for selecting the internal method
183    /// for the \ref run() function.
184    ///
185    /// \ref CostScaling provides three internal methods that differ mainly
186    /// in their base operations, which are used in conjunction with the
187    /// relabel operation.
188    /// By default, the so called \ref PARTIAL_AUGMENT
189    /// "Partial Augment-Relabel" method is used, which turned out to be
190    /// the most efficient and the most robust on various test inputs.
191    /// However, the other methods can be selected using the \ref run()
192    /// function with the proper parameter.
193    enum Method {
194      /// Local push operations are used, i.e. flow is moved only on one
195      /// admissible arc at once.
196      PUSH,
197      /// Augment operations are used, i.e. flow is moved on admissible
198      /// paths from a node with excess to a node with deficit.
199      AUGMENT,
200      /// Partial augment operations are used, i.e. flow is moved on
201      /// admissible paths started from a node with excess, but the
202      /// lengths of these paths are limited. This method can be viewed
203      /// as a combined version of the previous two operations.
204      PARTIAL_AUGMENT
205    };
206
207  private:
208
209    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
210
211    typedef std::vector<int> IntVector;
212    typedef std::vector<Value> ValueVector;
213    typedef std::vector<Cost> CostVector;
214    typedef std::vector<LargeCost> LargeCostVector;
215    typedef std::vector<char> BoolVector;
216    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
217
218  private:
219
220    template <typename KT, typename VT>
221    class StaticVectorMap {
222    public:
223      typedef KT Key;
224      typedef VT Value;
225
226      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
227
228      const Value& operator[](const Key& key) const {
229        return _v[StaticDigraph::id(key)];
230      }
231
232      Value& operator[](const Key& key) {
233        return _v[StaticDigraph::id(key)];
234      }
235
236      void set(const Key& key, const Value& val) {
237        _v[StaticDigraph::id(key)] = val;
238      }
239
240    private:
241      std::vector<Value>& _v;
242    };
243
244    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
245
246  private:
247
248    // Data related to the underlying digraph
249    const GR &_graph;
250    int _node_num;
251    int _arc_num;
252    int _res_node_num;
253    int _res_arc_num;
254    int _root;
255
256    // Parameters of the problem
257    bool _have_lower;
258    Value _sum_supply;
259    int _sup_node_num;
260
261    // Data structures for storing the digraph
262    IntNodeMap _node_id;
263    IntArcMap _arc_idf;
264    IntArcMap _arc_idb;
265    IntVector _first_out;
266    BoolVector _forward;
267    IntVector _source;
268    IntVector _target;
269    IntVector _reverse;
270
271    // Node and arc data
272    ValueVector _lower;
273    ValueVector _upper;
274    CostVector _scost;
275    ValueVector _supply;
276
277    ValueVector _res_cap;
278    LargeCostVector _cost;
279    LargeCostVector _pi;
280    ValueVector _excess;
281    IntVector _next_out;
282    std::deque<int> _active_nodes;
283
284    // Data for scaling
285    LargeCost _epsilon;
286    int _alpha;
287
288    IntVector _buckets;
289    IntVector _bucket_next;
290    IntVector _bucket_prev;
291    IntVector _rank;
292    int _max_rank;
293
294  public:
295
296    /// \brief Constant for infinite upper bounds (capacities).
297    ///
298    /// Constant for infinite upper bounds (capacities).
299    /// It is \c std::numeric_limits<Value>::infinity() if available,
300    /// \c std::numeric_limits<Value>::max() otherwise.
301    const Value INF;
302
303  public:
304
305    /// \name Named Template Parameters
306    /// @{
307
308    template <typename T>
309    struct SetLargeCostTraits : public Traits {
310      typedef T LargeCost;
311    };
312
313    /// \brief \ref named-templ-param "Named parameter" for setting
314    /// \c LargeCost type.
315    ///
316    /// \ref named-templ-param "Named parameter" for setting \c LargeCost
317    /// type, which is used for internal computations in the algorithm.
318    /// \c Cost must be convertible to \c LargeCost.
319    template <typename T>
320    struct SetLargeCost
321      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
322      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
323    };
324
325    /// @}
326
327  protected:
328
329    CostScaling() {}
330
331  public:
332
333    /// \brief Constructor.
334    ///
335    /// The constructor of the class.
336    ///
337    /// \param graph The digraph the algorithm runs on.
338    CostScaling(const GR& graph) :
339      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
340      INF(std::numeric_limits<Value>::has_infinity ?
341          std::numeric_limits<Value>::infinity() :
342          std::numeric_limits<Value>::max())
343    {
344      // Check the number types
345      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
346        "The flow type of CostScaling must be signed");
347      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
348        "The cost type of CostScaling must be signed");
349
350      // Reset data structures
351      reset();
352    }
353
354    /// \name Parameters
355    /// The parameters of the algorithm can be specified using these
356    /// functions.
357
358    /// @{
359
360    /// \brief Set the lower bounds on the arcs.
361    ///
362    /// This function sets the lower bounds on the arcs.
363    /// If it is not used before calling \ref run(), the lower bounds
364    /// will be set to zero on all arcs.
365    ///
366    /// \param map An arc map storing the lower bounds.
367    /// Its \c Value type must be convertible to the \c Value type
368    /// of the algorithm.
369    ///
370    /// \return <tt>(*this)</tt>
371    template <typename LowerMap>
372    CostScaling& lowerMap(const LowerMap& map) {
373      _have_lower = true;
374      for (ArcIt a(_graph); a != INVALID; ++a) {
375        _lower[_arc_idf[a]] = map[a];
376        _lower[_arc_idb[a]] = map[a];
377      }
378      return *this;
379    }
380
381    /// \brief Set the upper bounds (capacities) on the arcs.
382    ///
383    /// This function sets the upper bounds (capacities) on the arcs.
384    /// If it is not used before calling \ref run(), the upper bounds
385    /// will be set to \ref INF on all arcs (i.e. the flow value will be
386    /// unbounded from above).
387    ///
388    /// \param map An arc map storing the upper bounds.
389    /// Its \c Value type must be convertible to the \c Value type
390    /// of the algorithm.
391    ///
392    /// \return <tt>(*this)</tt>
393    template<typename UpperMap>
394    CostScaling& upperMap(const UpperMap& map) {
395      for (ArcIt a(_graph); a != INVALID; ++a) {
396        _upper[_arc_idf[a]] = map[a];
397      }
398      return *this;
399    }
400
401    /// \brief Set the costs of the arcs.
402    ///
403    /// This function sets the costs of the arcs.
404    /// If it is not used before calling \ref run(), the costs
405    /// will be set to \c 1 on all arcs.
406    ///
407    /// \param map An arc map storing the costs.
408    /// Its \c Value type must be convertible to the \c Cost type
409    /// of the algorithm.
410    ///
411    /// \return <tt>(*this)</tt>
412    template<typename CostMap>
413    CostScaling& costMap(const CostMap& map) {
414      for (ArcIt a(_graph); a != INVALID; ++a) {
415        _scost[_arc_idf[a]] =  map[a];
416        _scost[_arc_idb[a]] = -map[a];
417      }
418      return *this;
419    }
420
421    /// \brief Set the supply values of the nodes.
422    ///
423    /// This function sets the supply values of the nodes.
424    /// If neither this function nor \ref stSupply() is used before
425    /// calling \ref run(), the supply of each node will be set to zero.
426    ///
427    /// \param map A node map storing the supply values.
428    /// Its \c Value type must be convertible to the \c Value type
429    /// of the algorithm.
430    ///
431    /// \return <tt>(*this)</tt>
432    template<typename SupplyMap>
433    CostScaling& supplyMap(const SupplyMap& map) {
434      for (NodeIt n(_graph); n != INVALID; ++n) {
435        _supply[_node_id[n]] = map[n];
436      }
437      return *this;
438    }
439
440    /// \brief Set single source and target nodes and a supply value.
441    ///
442    /// This function sets a single source node and a single target node
443    /// and the required flow value.
444    /// If neither this function nor \ref supplyMap() is used before
445    /// calling \ref run(), the supply of each node will be set to zero.
446    ///
447    /// Using this function has the same effect as using \ref supplyMap()
448    /// with a map in which \c k is assigned to \c s, \c -k is
449    /// assigned to \c t and all other nodes have zero supply value.
450    ///
451    /// \param s The source node.
452    /// \param t The target node.
453    /// \param k The required amount of flow from node \c s to node \c t
454    /// (i.e. the supply of \c s and the demand of \c t).
455    ///
456    /// \return <tt>(*this)</tt>
457    CostScaling& stSupply(const Node& s, const Node& t, Value k) {
458      for (int i = 0; i != _res_node_num; ++i) {
459        _supply[i] = 0;
460      }
461      _supply[_node_id[s]] =  k;
462      _supply[_node_id[t]] = -k;
463      return *this;
464    }
465
466    /// @}
467
468    /// \name Execution control
469    /// The algorithm can be executed using \ref run().
470
471    /// @{
472
473    /// \brief Run the algorithm.
474    ///
475    /// This function runs the algorithm.
476    /// The paramters can be specified using functions \ref lowerMap(),
477    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
478    /// For example,
479    /// \code
480    ///   CostScaling<ListDigraph> cs(graph);
481    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
482    ///     .supplyMap(sup).run();
483    /// \endcode
484    ///
485    /// This function can be called more than once. All the given parameters
486    /// are kept for the next call, unless \ref resetParams() or \ref reset()
487    /// is used, thus only the modified parameters have to be set again.
488    /// If the underlying digraph was also modified after the construction
489    /// of the class (or the last \ref reset() call), then the \ref reset()
490    /// function must be called.
491    ///
492    /// \param method The internal method that will be used in the
493    /// algorithm. For more information, see \ref Method.
494    /// \param factor The cost scaling factor. It must be at least two.
495    ///
496    /// \return \c INFEASIBLE if no feasible flow exists,
497    /// \n \c OPTIMAL if the problem has optimal solution
498    /// (i.e. it is feasible and bounded), and the algorithm has found
499    /// optimal flow and node potentials (primal and dual solutions),
500    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
501    /// and infinite upper bound. It means that the objective function
502    /// is unbounded on that arc, however, note that it could actually be
503    /// bounded over the feasible flows, but this algroithm cannot handle
504    /// these cases.
505    ///
506    /// \see ProblemType, Method
507    /// \see resetParams(), reset()
508    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
509      LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
510      _alpha = factor;
511      ProblemType pt = init();
512      if (pt != OPTIMAL) return pt;
513      start(method);
514      return OPTIMAL;
515    }
516
517    /// \brief Reset all the parameters that have been given before.
518    ///
519    /// This function resets all the paramaters that have been given
520    /// before using functions \ref lowerMap(), \ref upperMap(),
521    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
522    ///
523    /// It is useful for multiple \ref run() calls. Basically, all the given
524    /// parameters are kept for the next \ref run() call, unless
525    /// \ref resetParams() or \ref reset() is used.
526    /// If the underlying digraph was also modified after the construction
527    /// of the class or the last \ref reset() call, then the \ref reset()
528    /// function must be used, otherwise \ref resetParams() is sufficient.
529    ///
530    /// For example,
531    /// \code
532    ///   CostScaling<ListDigraph> cs(graph);
533    ///
534    ///   // First run
535    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
536    ///     .supplyMap(sup).run();
537    ///
538    ///   // Run again with modified cost map (resetParams() is not called,
539    ///   // so only the cost map have to be set again)
540    ///   cost[e] += 100;
541    ///   cs.costMap(cost).run();
542    ///
543    ///   // Run again from scratch using resetParams()
544    ///   // (the lower bounds will be set to zero on all arcs)
545    ///   cs.resetParams();
546    ///   cs.upperMap(capacity).costMap(cost)
547    ///     .supplyMap(sup).run();
548    /// \endcode
549    ///
550    /// \return <tt>(*this)</tt>
551    ///
552    /// \see reset(), run()
553    CostScaling& resetParams() {
554      for (int i = 0; i != _res_node_num; ++i) {
555        _supply[i] = 0;
556      }
557      int limit = _first_out[_root];
558      for (int j = 0; j != limit; ++j) {
559        _lower[j] = 0;
560        _upper[j] = INF;
561        _scost[j] = _forward[j] ? 1 : -1;
562      }
563      for (int j = limit; j != _res_arc_num; ++j) {
564        _lower[j] = 0;
565        _upper[j] = INF;
566        _scost[j] = 0;
567        _scost[_reverse[j]] = 0;
568      }
569      _have_lower = false;
570      return *this;
571    }
572
573    /// \brief Reset the internal data structures and all the parameters
574    /// that have been given before.
575    ///
576    /// This function resets the internal data structures and all the
577    /// paramaters that have been given before using functions \ref lowerMap(),
578    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
579    ///
580    /// It is useful for multiple \ref run() calls. By default, all the given
581    /// parameters are kept for the next \ref run() call, unless
582    /// \ref resetParams() or \ref reset() is used.
583    /// If the underlying digraph was also modified after the construction
584    /// of the class or the last \ref reset() call, then the \ref reset()
585    /// function must be used, otherwise \ref resetParams() is sufficient.
586    ///
587    /// See \ref resetParams() for examples.
588    ///
589    /// \return <tt>(*this)</tt>
590    ///
591    /// \see resetParams(), run()
592    CostScaling& reset() {
593      // Resize vectors
594      _node_num = countNodes(_graph);
595      _arc_num = countArcs(_graph);
596      _res_node_num = _node_num + 1;
597      _res_arc_num = 2 * (_arc_num + _node_num);
598      _root = _node_num;
599
600      _first_out.resize(_res_node_num + 1);
601      _forward.resize(_res_arc_num);
602      _source.resize(_res_arc_num);
603      _target.resize(_res_arc_num);
604      _reverse.resize(_res_arc_num);
605
606      _lower.resize(_res_arc_num);
607      _upper.resize(_res_arc_num);
608      _scost.resize(_res_arc_num);
609      _supply.resize(_res_node_num);
610
611      _res_cap.resize(_res_arc_num);
612      _cost.resize(_res_arc_num);
613      _pi.resize(_res_node_num);
614      _excess.resize(_res_node_num);
615      _next_out.resize(_res_node_num);
616
617      // Copy the graph
618      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
619      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
620        _node_id[n] = i;
621      }
622      i = 0;
623      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
624        _first_out[i] = j;
625        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
626          _arc_idf[a] = j;
627          _forward[j] = true;
628          _source[j] = i;
629          _target[j] = _node_id[_graph.runningNode(a)];
630        }
631        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
632          _arc_idb[a] = j;
633          _forward[j] = false;
634          _source[j] = i;
635          _target[j] = _node_id[_graph.runningNode(a)];
636        }
637        _forward[j] = false;
638        _source[j] = i;
639        _target[j] = _root;
640        _reverse[j] = k;
641        _forward[k] = true;
642        _source[k] = _root;
643        _target[k] = i;
644        _reverse[k] = j;
645        ++j; ++k;
646      }
647      _first_out[i] = j;
648      _first_out[_res_node_num] = k;
649      for (ArcIt a(_graph); a != INVALID; ++a) {
650        int fi = _arc_idf[a];
651        int bi = _arc_idb[a];
652        _reverse[fi] = bi;
653        _reverse[bi] = fi;
654      }
655
656      // Reset parameters
657      resetParams();
658      return *this;
659    }
660
661    /// @}
662
663    /// \name Query Functions
664    /// The results of the algorithm can be obtained using these
665    /// functions.\n
666    /// The \ref run() function must be called before using them.
667
668    /// @{
669
670    /// \brief Return the total cost of the found flow.
671    ///
672    /// This function returns the total cost of the found flow.
673    /// Its complexity is O(m).
674    ///
675    /// \note The return type of the function can be specified as a
676    /// template parameter. For example,
677    /// \code
678    ///   cs.totalCost<double>();
679    /// \endcode
680    /// It is useful if the total cost cannot be stored in the \c Cost
681    /// type of the algorithm, which is the default return type of the
682    /// function.
683    ///
684    /// \pre \ref run() must be called before using this function.
685    template <typename Number>
686    Number totalCost() const {
687      Number c = 0;
688      for (ArcIt a(_graph); a != INVALID; ++a) {
689        int i = _arc_idb[a];
690        c += static_cast<Number>(_res_cap[i]) *
691             (-static_cast<Number>(_scost[i]));
692      }
693      return c;
694    }
695
696#ifndef DOXYGEN
697    Cost totalCost() const {
698      return totalCost<Cost>();
699    }
700#endif
701
702    /// \brief Return the flow on the given arc.
703    ///
704    /// This function returns the flow on the given arc.
705    ///
706    /// \pre \ref run() must be called before using this function.
707    Value flow(const Arc& a) const {
708      return _res_cap[_arc_idb[a]];
709    }
710
711    /// \brief Copy the flow values (the primal solution) into the
712    /// given map.
713    ///
714    /// This function copies the flow value on each arc into the given
715    /// map. The \c Value type of the algorithm must be convertible to
716    /// the \c Value type of the map.
717    ///
718    /// \pre \ref run() must be called before using this function.
719    template <typename FlowMap>
720    void flowMap(FlowMap &map) const {
721      for (ArcIt a(_graph); a != INVALID; ++a) {
722        map.set(a, _res_cap[_arc_idb[a]]);
723      }
724    }
725
726    /// \brief Return the potential (dual value) of the given node.
727    ///
728    /// This function returns the potential (dual value) of the
729    /// given node.
730    ///
731    /// \pre \ref run() must be called before using this function.
732    Cost potential(const Node& n) const {
733      return static_cast<Cost>(_pi[_node_id[n]]);
734    }
735
736    /// \brief Copy the potential values (the dual solution) into the
737    /// given map.
738    ///
739    /// This function copies the potential (dual value) of each node
740    /// into the given map.
741    /// The \c Cost type of the algorithm must be convertible to the
742    /// \c Value type of the map.
743    ///
744    /// \pre \ref run() must be called before using this function.
745    template <typename PotentialMap>
746    void potentialMap(PotentialMap &map) const {
747      for (NodeIt n(_graph); n != INVALID; ++n) {
748        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
749      }
750    }
751
752    /// @}
753
754  private:
755
756    // Initialize the algorithm
757    ProblemType init() {
758      if (_res_node_num <= 1) return INFEASIBLE;
759
760      // Check the sum of supply values
761      _sum_supply = 0;
762      for (int i = 0; i != _root; ++i) {
763        _sum_supply += _supply[i];
764      }
765      if (_sum_supply > 0) return INFEASIBLE;
766
767      // Check lower and upper bounds
768      LEMON_DEBUG(checkBoundMaps(),
769          "Upper bounds must be greater or equal to the lower bounds");
770
771
772      // Initialize vectors
773      for (int i = 0; i != _res_node_num; ++i) {
774        _pi[i] = 0;
775        _excess[i] = _supply[i];
776      }
777
778      // Remove infinite upper bounds and check negative arcs
779      const Value MAX = std::numeric_limits<Value>::max();
780      int last_out;
781      if (_have_lower) {
782        for (int i = 0; i != _root; ++i) {
783          last_out = _first_out[i+1];
784          for (int j = _first_out[i]; j != last_out; ++j) {
785            if (_forward[j]) {
786              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
787              if (c >= MAX) return UNBOUNDED;
788              _excess[i] -= c;
789              _excess[_target[j]] += c;
790            }
791          }
792        }
793      } else {
794        for (int i = 0; i != _root; ++i) {
795          last_out = _first_out[i+1];
796          for (int j = _first_out[i]; j != last_out; ++j) {
797            if (_forward[j] && _scost[j] < 0) {
798              Value c = _upper[j];
799              if (c >= MAX) return UNBOUNDED;
800              _excess[i] -= c;
801              _excess[_target[j]] += c;
802            }
803          }
804        }
805      }
806      Value ex, max_cap = 0;
807      for (int i = 0; i != _res_node_num; ++i) {
808        ex = _excess[i];
809        _excess[i] = 0;
810        if (ex < 0) max_cap -= ex;
811      }
812      for (int j = 0; j != _res_arc_num; ++j) {
813        if (_upper[j] >= MAX) _upper[j] = max_cap;
814      }
815
816      // Initialize the large cost vector and the epsilon parameter
817      _epsilon = 0;
818      LargeCost lc;
819      for (int i = 0; i != _root; ++i) {
820        last_out = _first_out[i+1];
821        for (int j = _first_out[i]; j != last_out; ++j) {
822          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
823          _cost[j] = lc;
824          if (lc > _epsilon) _epsilon = lc;
825        }
826      }
827      _epsilon /= _alpha;
828
829      // Initialize maps for Circulation and remove non-zero lower bounds
830      ConstMap<Arc, Value> low(0);
831      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
832      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
833      ValueArcMap cap(_graph), flow(_graph);
834      ValueNodeMap sup(_graph);
835      for (NodeIt n(_graph); n != INVALID; ++n) {
836        sup[n] = _supply[_node_id[n]];
837      }
838      if (_have_lower) {
839        for (ArcIt a(_graph); a != INVALID; ++a) {
840          int j = _arc_idf[a];
841          Value c = _lower[j];
842          cap[a] = _upper[j] - c;
843          sup[_graph.source(a)] -= c;
844          sup[_graph.target(a)] += c;
845        }
846      } else {
847        for (ArcIt a(_graph); a != INVALID; ++a) {
848          cap[a] = _upper[_arc_idf[a]];
849        }
850      }
851
852      _sup_node_num = 0;
853      for (NodeIt n(_graph); n != INVALID; ++n) {
854        if (sup[n] > 0) ++_sup_node_num;
855      }
856
857      // Find a feasible flow using Circulation
858      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
859        circ(_graph, low, cap, sup);
860      if (!circ.flowMap(flow).run()) return INFEASIBLE;
861
862      // Set residual capacities and handle GEQ supply type
863      if (_sum_supply < 0) {
864        for (ArcIt a(_graph); a != INVALID; ++a) {
865          Value fa = flow[a];
866          _res_cap[_arc_idf[a]] = cap[a] - fa;
867          _res_cap[_arc_idb[a]] = fa;
868          sup[_graph.source(a)] -= fa;
869          sup[_graph.target(a)] += fa;
870        }
871        for (NodeIt n(_graph); n != INVALID; ++n) {
872          _excess[_node_id[n]] = sup[n];
873        }
874        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
875          int u = _target[a];
876          int ra = _reverse[a];
877          _res_cap[a] = -_sum_supply + 1;
878          _res_cap[ra] = -_excess[u];
879          _cost[a] = 0;
880          _cost[ra] = 0;
881          _excess[u] = 0;
882        }
883      } else {
884        for (ArcIt a(_graph); a != INVALID; ++a) {
885          Value fa = flow[a];
886          _res_cap[_arc_idf[a]] = cap[a] - fa;
887          _res_cap[_arc_idb[a]] = fa;
888        }
889        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
890          int ra = _reverse[a];
891          _res_cap[a] = 0;
892          _res_cap[ra] = 0;
893          _cost[a] = 0;
894          _cost[ra] = 0;
895        }
896      }
897
898      // Initialize data structures for buckets
899      _max_rank = _alpha * _res_node_num;
900      _buckets.resize(_max_rank);
901      _bucket_next.resize(_res_node_num + 1);
902      _bucket_prev.resize(_res_node_num + 1);
903      _rank.resize(_res_node_num + 1);
904
905      return OPTIMAL;
906    }
907   
908    // Check if the upper bound is greater or equal to the lower bound
909    // on each arc.
910    bool checkBoundMaps() {
911      for (int j = 0; j != _res_arc_num; ++j) {
912        if (_upper[j] < _lower[j]) return false;
913      }
914      return true;
915    }
916
917    // Execute the algorithm and transform the results
918    void start(Method method) {
919      const int MAX_PARTIAL_PATH_LENGTH = 4;
920
921      switch (method) {
922        case PUSH:
923          startPush();
924          break;
925        case AUGMENT:
926          startAugment(_res_node_num - 1);
927          break;
928        case PARTIAL_AUGMENT:
929          startAugment(MAX_PARTIAL_PATH_LENGTH);
930          break;
931      }
932
933      // Compute node potentials (dual solution)
934      for (int i = 0; i != _res_node_num; ++i) {
935        _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
936      }
937      bool optimal = true;
938      for (int i = 0; optimal && i != _res_node_num; ++i) {
939        LargeCost pi_i = _pi[i];
940        int last_out = _first_out[i+1];
941        for (int j = _first_out[i]; j != last_out; ++j) {
942          if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
943            optimal = false;
944            break;
945          }
946        }
947      }
948
949      if (!optimal) {
950        // Compute node potentials for the original costs with BellmanFord
951        // (if it is necessary)
952        typedef std::pair<int, int> IntPair;
953        StaticDigraph sgr;
954        std::vector<IntPair> arc_vec;
955        std::vector<LargeCost> cost_vec;
956        LargeCostArcMap cost_map(cost_vec);
957
958        arc_vec.clear();
959        cost_vec.clear();
960        for (int j = 0; j != _res_arc_num; ++j) {
961          if (_res_cap[j] > 0) {
962            int u = _source[j], v = _target[j];
963            arc_vec.push_back(IntPair(u, v));
964            cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
965          }
966        }
967        sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
968
969        typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
970          bf(sgr, cost_map);
971        bf.init(0);
972        bf.start();
973
974        for (int i = 0; i != _res_node_num; ++i) {
975          _pi[i] += bf.dist(sgr.node(i));
976        }
977      }
978
979      // Shift potentials to meet the requirements of the GEQ type
980      // optimality conditions
981      LargeCost max_pot = _pi[_root];
982      for (int i = 0; i != _res_node_num; ++i) {
983        if (_pi[i] > max_pot) max_pot = _pi[i];
984      }
985      if (max_pot != 0) {
986        for (int i = 0; i != _res_node_num; ++i) {
987          _pi[i] -= max_pot;
988        }
989      }
990
991      // Handle non-zero lower bounds
992      if (_have_lower) {
993        int limit = _first_out[_root];
994        for (int j = 0; j != limit; ++j) {
995          if (!_forward[j]) _res_cap[j] += _lower[j];
996        }
997      }
998    }
999
1000    // Initialize a cost scaling phase
1001    void initPhase() {
1002      // Saturate arcs not satisfying the optimality condition
1003      for (int u = 0; u != _res_node_num; ++u) {
1004        int last_out = _first_out[u+1];
1005        LargeCost pi_u = _pi[u];
1006        for (int a = _first_out[u]; a != last_out; ++a) {
1007          Value delta = _res_cap[a];
1008          if (delta > 0) {
1009            int v = _target[a];
1010            if (_cost[a] + pi_u - _pi[v] < 0) {
1011              _excess[u] -= delta;
1012              _excess[v] += delta;
1013              _res_cap[a] = 0;
1014              _res_cap[_reverse[a]] += delta;
1015            }
1016          }
1017        }
1018      }
1019
1020      // Find active nodes (i.e. nodes with positive excess)
1021      for (int u = 0; u != _res_node_num; ++u) {
1022        if (_excess[u] > 0) _active_nodes.push_back(u);
1023      }
1024
1025      // Initialize the next arcs
1026      for (int u = 0; u != _res_node_num; ++u) {
1027        _next_out[u] = _first_out[u];
1028      }
1029    }
1030
1031    // Price (potential) refinement heuristic
1032    bool priceRefinement() {
1033
1034      // Stack for stroing the topological order
1035      IntVector stack(_res_node_num);
1036      int stack_top;
1037
1038      // Perform phases
1039      while (topologicalSort(stack, stack_top)) {
1040
1041        // Compute node ranks in the acyclic admissible network and
1042        // store the nodes in buckets
1043        for (int i = 0; i != _res_node_num; ++i) {
1044          _rank[i] = 0;
1045        }
1046        const int bucket_end = _root + 1;
1047        for (int r = 0; r != _max_rank; ++r) {
1048          _buckets[r] = bucket_end;
1049        }
1050        int top_rank = 0;
1051        for ( ; stack_top >= 0; --stack_top) {
1052          int u = stack[stack_top], v;
1053          int rank_u = _rank[u];
1054
1055          LargeCost rc, pi_u = _pi[u];
1056          int last_out = _first_out[u+1];
1057          for (int a = _first_out[u]; a != last_out; ++a) {
1058            if (_res_cap[a] > 0) {
1059              v = _target[a];
1060              rc = _cost[a] + pi_u - _pi[v];
1061              if (rc < 0) {
1062                LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1063                if (nrc < LargeCost(_max_rank)) {
1064                  int new_rank_v = rank_u + static_cast<int>(nrc);
1065                  if (new_rank_v > _rank[v]) {
1066                    _rank[v] = new_rank_v;
1067                  }
1068                }
1069              }
1070            }
1071          }
1072
1073          if (rank_u > 0) {
1074            top_rank = std::max(top_rank, rank_u);
1075            int bfirst = _buckets[rank_u];
1076            _bucket_next[u] = bfirst;
1077            _bucket_prev[bfirst] = u;
1078            _buckets[rank_u] = u;
1079          }
1080        }
1081
1082        // Check if the current flow is epsilon-optimal
1083        if (top_rank == 0) {
1084          return true;
1085        }
1086
1087        // Process buckets in top-down order
1088        for (int rank = top_rank; rank > 0; --rank) {
1089          while (_buckets[rank] != bucket_end) {
1090            // Remove the first node from the current bucket
1091            int u = _buckets[rank];
1092            _buckets[rank] = _bucket_next[u];
1093
1094            // Search the outgoing arcs of u
1095            LargeCost rc, pi_u = _pi[u];
1096            int last_out = _first_out[u+1];
1097            int v, old_rank_v, new_rank_v;
1098            for (int a = _first_out[u]; a != last_out; ++a) {
1099              if (_res_cap[a] > 0) {
1100                v = _target[a];
1101                old_rank_v = _rank[v];
1102
1103                if (old_rank_v < rank) {
1104
1105                  // Compute the new rank of node v
1106                  rc = _cost[a] + pi_u - _pi[v];
1107                  if (rc < 0) {
1108                    new_rank_v = rank;
1109                  } else {
1110                    LargeCost nrc = rc / _epsilon;
1111                    new_rank_v = 0;
1112                    if (nrc < LargeCost(_max_rank)) {
1113                      new_rank_v = rank - 1 - static_cast<int>(nrc);
1114                    }
1115                  }
1116
1117                  // Change the rank of node v
1118                  if (new_rank_v > old_rank_v) {
1119                    _rank[v] = new_rank_v;
1120
1121                    // Remove v from its old bucket
1122                    if (old_rank_v > 0) {
1123                      if (_buckets[old_rank_v] == v) {
1124                        _buckets[old_rank_v] = _bucket_next[v];
1125                      } else {
1126                        int pv = _bucket_prev[v], nv = _bucket_next[v];
1127                        _bucket_next[pv] = nv;
1128                        _bucket_prev[nv] = pv;
1129                      }
1130                    }
1131
1132                    // Insert v into its new bucket
1133                    int nv = _buckets[new_rank_v];
1134                    _bucket_next[v] = nv;
1135                    _bucket_prev[nv] = v;
1136                    _buckets[new_rank_v] = v;
1137                  }
1138                }
1139              }
1140            }
1141
1142            // Refine potential of node u
1143            _pi[u] -= rank * _epsilon;
1144          }
1145        }
1146
1147      }
1148
1149      return false;
1150    }
1151
1152    // Find and cancel cycles in the admissible network and
1153    // determine topological order using DFS
1154    bool topologicalSort(IntVector &stack, int &stack_top) {
1155      const int MAX_CYCLE_CANCEL = 1;
1156
1157      BoolVector reached(_res_node_num, false);
1158      BoolVector processed(_res_node_num, false);
1159      IntVector pred(_res_node_num);
1160      for (int i = 0; i != _res_node_num; ++i) {
1161        _next_out[i] = _first_out[i];
1162      }
1163      stack_top = -1;
1164
1165      int cycle_cnt = 0;
1166      for (int start = 0; start != _res_node_num; ++start) {
1167        if (reached[start]) continue;
1168
1169        // Start DFS search from this start node
1170        pred[start] = -1;
1171        int tip = start, v;
1172        while (true) {
1173          // Check the outgoing arcs of the current tip node
1174          reached[tip] = true;
1175          LargeCost pi_tip = _pi[tip];
1176          int a, last_out = _first_out[tip+1];
1177          for (a = _next_out[tip]; a != last_out; ++a) {
1178            if (_res_cap[a] > 0) {
1179              v = _target[a];
1180              if (_cost[a] + pi_tip - _pi[v] < 0) {
1181                if (!reached[v]) {
1182                  // A new node is reached
1183                  reached[v] = true;
1184                  pred[v] = tip;
1185                  _next_out[tip] = a;
1186                  tip = v;
1187                  a = _next_out[tip];
1188                  last_out = _first_out[tip+1];
1189                  break;
1190                }
1191                else if (!processed[v]) {
1192                  // A cycle is found
1193                  ++cycle_cnt;
1194                  _next_out[tip] = a;
1195
1196                  // Find the minimum residual capacity along the cycle
1197                  Value d, delta = _res_cap[a];
1198                  int u, delta_node = tip;
1199                  for (u = tip; u != v; ) {
1200                    u = pred[u];
1201                    d = _res_cap[_next_out[u]];
1202                    if (d <= delta) {
1203                      delta = d;
1204                      delta_node = u;
1205                    }
1206                  }
1207
1208                  // Augment along the cycle
1209                  _res_cap[a] -= delta;
1210                  _res_cap[_reverse[a]] += delta;
1211                  for (u = tip; u != v; ) {
1212                    u = pred[u];
1213                    int ca = _next_out[u];
1214                    _res_cap[ca] -= delta;
1215                    _res_cap[_reverse[ca]] += delta;
1216                  }
1217
1218                  // Check the maximum number of cycle canceling
1219                  if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1220                    return false;
1221                  }
1222
1223                  // Roll back search to delta_node
1224                  if (delta_node != tip) {
1225                    for (u = tip; u != delta_node; u = pred[u]) {
1226                      reached[u] = false;
1227                    }
1228                    tip = delta_node;
1229                    a = _next_out[tip] + 1;
1230                    last_out = _first_out[tip+1];
1231                    break;
1232                  }
1233                }
1234              }
1235            }
1236          }
1237
1238          // Step back to the previous node
1239          if (a == last_out) {
1240            processed[tip] = true;
1241            stack[++stack_top] = tip;
1242            tip = pred[tip];
1243            if (tip < 0) {
1244              // Finish DFS from the current start node
1245              break;
1246            }
1247            ++_next_out[tip];
1248          }
1249        }
1250
1251      }
1252
1253      return (cycle_cnt == 0);
1254    }
1255
1256    // Global potential update heuristic
1257    void globalUpdate() {
1258      const int bucket_end = _root + 1;
1259
1260      // Initialize buckets
1261      for (int r = 0; r != _max_rank; ++r) {
1262        _buckets[r] = bucket_end;
1263      }
1264      Value total_excess = 0;
1265      int b0 = bucket_end;
1266      for (int i = 0; i != _res_node_num; ++i) {
1267        if (_excess[i] < 0) {
1268          _rank[i] = 0;
1269          _bucket_next[i] = b0;
1270          _bucket_prev[b0] = i;
1271          b0 = i;
1272        } else {
1273          total_excess += _excess[i];
1274          _rank[i] = _max_rank;
1275        }
1276      }
1277      if (total_excess == 0) return;
1278      _buckets[0] = b0;
1279
1280      // Search the buckets
1281      int r = 0;
1282      for ( ; r != _max_rank; ++r) {
1283        while (_buckets[r] != bucket_end) {
1284          // Remove the first node from the current bucket
1285          int u = _buckets[r];
1286          _buckets[r] = _bucket_next[u];
1287
1288          // Search the incoming arcs of u
1289          LargeCost pi_u = _pi[u];
1290          int last_out = _first_out[u+1];
1291          for (int a = _first_out[u]; a != last_out; ++a) {
1292            int ra = _reverse[a];
1293            if (_res_cap[ra] > 0) {
1294              int v = _source[ra];
1295              int old_rank_v = _rank[v];
1296              if (r < old_rank_v) {
1297                // Compute the new rank of v
1298                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1299                int new_rank_v = old_rank_v;
1300                if (nrc < LargeCost(_max_rank)) {
1301                  new_rank_v = r + 1 + static_cast<int>(nrc);
1302                }
1303
1304                // Change the rank of v
1305                if (new_rank_v < old_rank_v) {
1306                  _rank[v] = new_rank_v;
1307                  _next_out[v] = _first_out[v];
1308
1309                  // Remove v from its old bucket
1310                  if (old_rank_v < _max_rank) {
1311                    if (_buckets[old_rank_v] == v) {
1312                      _buckets[old_rank_v] = _bucket_next[v];
1313                    } else {
1314                      int pv = _bucket_prev[v], nv = _bucket_next[v];
1315                      _bucket_next[pv] = nv;
1316                      _bucket_prev[nv] = pv;
1317                    }
1318                  }
1319
1320                  // Insert v into its new bucket
1321                  int nv = _buckets[new_rank_v];
1322                  _bucket_next[v] = nv;
1323                  _bucket_prev[nv] = v;
1324                  _buckets[new_rank_v] = v;
1325                }
1326              }
1327            }
1328          }
1329
1330          // Finish search if there are no more active nodes
1331          if (_excess[u] > 0) {
1332            total_excess -= _excess[u];
1333            if (total_excess <= 0) break;
1334          }
1335        }
1336        if (total_excess <= 0) break;
1337      }
1338
1339      // Relabel nodes
1340      for (int u = 0; u != _res_node_num; ++u) {
1341        int k = std::min(_rank[u], r);
1342        if (k > 0) {
1343          _pi[u] -= _epsilon * k;
1344          _next_out[u] = _first_out[u];
1345        }
1346      }
1347    }
1348
1349    /// Execute the algorithm performing augment and relabel operations
1350    void startAugment(int max_length) {
1351      // Paramters for heuristics
1352      const int PRICE_REFINEMENT_LIMIT = 2;
1353      const double GLOBAL_UPDATE_FACTOR = 1.0;
1354      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1355        (_res_node_num + _sup_node_num * _sup_node_num));
1356      int next_global_update_limit = global_update_skip;
1357
1358      // Perform cost scaling phases
1359      IntVector path;
1360      BoolVector path_arc(_res_arc_num, false);
1361      int relabel_cnt = 0;
1362      int eps_phase_cnt = 0;
1363      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1364                                        1 : _epsilon / _alpha )
1365      {
1366        ++eps_phase_cnt;
1367
1368        // Price refinement heuristic
1369        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1370          if (priceRefinement()) continue;
1371        }
1372
1373        // Initialize current phase
1374        initPhase();
1375
1376        // Perform partial augment and relabel operations
1377        while (true) {
1378          // Select an active node (FIFO selection)
1379          while (_active_nodes.size() > 0 &&
1380                 _excess[_active_nodes.front()] <= 0) {
1381            _active_nodes.pop_front();
1382          }
1383          if (_active_nodes.size() == 0) break;
1384          int start = _active_nodes.front();
1385
1386          // Find an augmenting path from the start node
1387          int tip = start;
1388          while (int(path.size()) < max_length && _excess[tip] >= 0) {
1389            int u;
1390            LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1391            LargeCost pi_tip = _pi[tip];
1392            int last_out = _first_out[tip+1];
1393            for (int a = _next_out[tip]; a != last_out; ++a) {
1394              if (_res_cap[a] > 0) {
1395                u = _target[a];
1396                rc = _cost[a] + pi_tip - _pi[u];
1397                if (rc < 0) {
1398                  path.push_back(a);
1399                  _next_out[tip] = a;
1400                  if (path_arc[a]) {
1401                    goto augment;   // a cycle is found, stop path search
1402                  }
1403                  tip = u;
1404                  path_arc[a] = true;
1405                  goto next_step;
1406                }
1407                else if (rc < min_red_cost) {
1408                  min_red_cost = rc;
1409                }
1410              }
1411            }
1412
1413            // Relabel tip node
1414            if (tip != start) {
1415              int ra = _reverse[path.back()];
1416              min_red_cost =
1417                std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1418            }
1419            last_out = _next_out[tip];
1420            for (int a = _first_out[tip]; a != last_out; ++a) {
1421              if (_res_cap[a] > 0) {
1422                rc = _cost[a] + pi_tip - _pi[_target[a]];
1423                if (rc < min_red_cost) {
1424                  min_red_cost = rc;
1425                }
1426              }
1427            }
1428            _pi[tip] -= min_red_cost + _epsilon;
1429            _next_out[tip] = _first_out[tip];
1430            ++relabel_cnt;
1431
1432            // Step back
1433            if (tip != start) {
1434              int pa = path.back();
1435              path_arc[pa] = false;
1436              tip = _source[pa];
1437              path.pop_back();
1438            }
1439
1440          next_step: ;
1441          }
1442
1443          // Augment along the found path (as much flow as possible)
1444        augment:
1445          Value delta;
1446          int pa, u, v = start;
1447          for (int i = 0; i != int(path.size()); ++i) {
1448            pa = path[i];
1449            u = v;
1450            v = _target[pa];
1451            path_arc[pa] = false;
1452            delta = std::min(_res_cap[pa], _excess[u]);
1453            _res_cap[pa] -= delta;
1454            _res_cap[_reverse[pa]] += delta;
1455            _excess[u] -= delta;
1456            _excess[v] += delta;
1457            if (_excess[v] > 0 && _excess[v] <= delta) {
1458              _active_nodes.push_back(v);
1459            }
1460          }
1461          path.clear();
1462
1463          // Global update heuristic
1464          if (relabel_cnt >= next_global_update_limit) {
1465            globalUpdate();
1466            next_global_update_limit += global_update_skip;
1467          }
1468        }
1469
1470      }
1471
1472    }
1473
1474    /// Execute the algorithm performing push and relabel operations
1475    void startPush() {
1476      // Paramters for heuristics
1477      const int PRICE_REFINEMENT_LIMIT = 2;
1478      const double GLOBAL_UPDATE_FACTOR = 2.0;
1479
1480      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1481        (_res_node_num + _sup_node_num * _sup_node_num));
1482      int next_global_update_limit = global_update_skip;
1483
1484      // Perform cost scaling phases
1485      BoolVector hyper(_res_node_num, false);
1486      LargeCostVector hyper_cost(_res_node_num);
1487      int relabel_cnt = 0;
1488      int eps_phase_cnt = 0;
1489      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1490                                        1 : _epsilon / _alpha )
1491      {
1492        ++eps_phase_cnt;
1493
1494        // Price refinement heuristic
1495        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1496          if (priceRefinement()) continue;
1497        }
1498
1499        // Initialize current phase
1500        initPhase();
1501
1502        // Perform push and relabel operations
1503        while (_active_nodes.size() > 0) {
1504          LargeCost min_red_cost, rc, pi_n;
1505          Value delta;
1506          int n, t, a, last_out = _res_arc_num;
1507
1508        next_node:
1509          // Select an active node (FIFO selection)
1510          n = _active_nodes.front();
1511          last_out = _first_out[n+1];
1512          pi_n = _pi[n];
1513
1514          // Perform push operations if there are admissible arcs
1515          if (_excess[n] > 0) {
1516            for (a = _next_out[n]; a != last_out; ++a) {
1517              if (_res_cap[a] > 0 &&
1518                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
1519                delta = std::min(_res_cap[a], _excess[n]);
1520                t = _target[a];
1521
1522                // Push-look-ahead heuristic
1523                Value ahead = -_excess[t];
1524                int last_out_t = _first_out[t+1];
1525                LargeCost pi_t = _pi[t];
1526                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1527                  if (_res_cap[ta] > 0 &&
1528                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1529                    ahead += _res_cap[ta];
1530                  if (ahead >= delta) break;
1531                }
1532                if (ahead < 0) ahead = 0;
1533
1534                // Push flow along the arc
1535                if (ahead < delta && !hyper[t]) {
1536                  _res_cap[a] -= ahead;
1537                  _res_cap[_reverse[a]] += ahead;
1538                  _excess[n] -= ahead;
1539                  _excess[t] += ahead;
1540                  _active_nodes.push_front(t);
1541                  hyper[t] = true;
1542                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
1543                  _next_out[n] = a;
1544                  goto next_node;
1545                } else {
1546                  _res_cap[a] -= delta;
1547                  _res_cap[_reverse[a]] += delta;
1548                  _excess[n] -= delta;
1549                  _excess[t] += delta;
1550                  if (_excess[t] > 0 && _excess[t] <= delta)
1551                    _active_nodes.push_back(t);
1552                }
1553
1554                if (_excess[n] == 0) {
1555                  _next_out[n] = a;
1556                  goto remove_nodes;
1557                }
1558              }
1559            }
1560            _next_out[n] = a;
1561          }
1562
1563          // Relabel the node if it is still active (or hyper)
1564          if (_excess[n] > 0 || hyper[n]) {
1565             min_red_cost = hyper[n] ? -hyper_cost[n] :
1566               std::numeric_limits<LargeCost>::max();
1567            for (int a = _first_out[n]; a != last_out; ++a) {
1568              if (_res_cap[a] > 0) {
1569                rc = _cost[a] + pi_n - _pi[_target[a]];
1570                if (rc < min_red_cost) {
1571                  min_red_cost = rc;
1572                }
1573              }
1574            }
1575            _pi[n] -= min_red_cost + _epsilon;
1576            _next_out[n] = _first_out[n];
1577            hyper[n] = false;
1578            ++relabel_cnt;
1579          }
1580
1581          // Remove nodes that are not active nor hyper
1582        remove_nodes:
1583          while ( _active_nodes.size() > 0 &&
1584                  _excess[_active_nodes.front()] <= 0 &&
1585                  !hyper[_active_nodes.front()] ) {
1586            _active_nodes.pop_front();
1587          }
1588
1589          // Global update heuristic
1590          if (relabel_cnt >= next_global_update_limit) {
1591            globalUpdate();
1592            for (int u = 0; u != _res_node_num; ++u)
1593              hyper[u] = false;
1594            next_global_update_limit += global_update_skip;
1595          }
1596        }
1597      }
1598    }
1599
1600  }; //class CostScaling
1601
1602  ///@}
1603
1604} //namespace lemon
1605
1606#endif //LEMON_COST_SCALING_H
Note: See TracBrowser for help on using the repository browser.