COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/cost_scaling.h @ 1103:c0c2f5c87aa6

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

Rename field in min cost flow codes (#478)

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