COIN-OR::LEMON - Graph Library

source: lemon/lemon/cost_scaling.h @ 1298:a78e5b779b69

Last change on this file since 1298:a78e5b779b69 was 1298:a78e5b779b69, checked in by Alpar Juttner <alpar@…>, 11 years ago

Merge bugfix #478

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