COIN-OR::LEMON - Graph Library

source: lemon/lemon/cost_scaling.h @ 1271:fb1c7da561ce

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

Remove long lines (from all but one file)

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