COIN-OR::LEMON - Graph Library

source: lemon/lemon/cost_scaling.h @ 1241:879fcb781086

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

Merge #454

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