COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/cost_scaling.h @ 1069:d1a48668ddb4

Last change on this file since 1069:d1a48668ddb4 was 1053:1c978b5bcc65, checked in by Alpar Juttner <alpar@…>, 11 years ago

Use doxygen's own bibtex support (#456)

File size: 51.1 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
767      // Initialize vectors
768      for (int i = 0; i != _res_node_num; ++i) {
769        _pi[i] = 0;
770        _excess[i] = _supply[i];
771      }
772
773      // Remove infinite upper bounds and check negative arcs
774      const Value MAX = std::numeric_limits<Value>::max();
775      int last_out;
776      if (_have_lower) {
777        for (int i = 0; i != _root; ++i) {
778          last_out = _first_out[i+1];
779          for (int j = _first_out[i]; j != last_out; ++j) {
780            if (_forward[j]) {
781              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
782              if (c >= MAX) return UNBOUNDED;
783              _excess[i] -= c;
784              _excess[_target[j]] += c;
785            }
786          }
787        }
788      } else {
789        for (int i = 0; i != _root; ++i) {
790          last_out = _first_out[i+1];
791          for (int j = _first_out[i]; j != last_out; ++j) {
792            if (_forward[j] && _scost[j] < 0) {
793              Value c = _upper[j];
794              if (c >= MAX) return UNBOUNDED;
795              _excess[i] -= c;
796              _excess[_target[j]] += c;
797            }
798          }
799        }
800      }
801      Value ex, max_cap = 0;
802      for (int i = 0; i != _res_node_num; ++i) {
803        ex = _excess[i];
804        _excess[i] = 0;
805        if (ex < 0) max_cap -= ex;
806      }
807      for (int j = 0; j != _res_arc_num; ++j) {
808        if (_upper[j] >= MAX) _upper[j] = max_cap;
809      }
810
811      // Initialize the large cost vector and the epsilon parameter
812      _epsilon = 0;
813      LargeCost lc;
814      for (int i = 0; i != _root; ++i) {
815        last_out = _first_out[i+1];
816        for (int j = _first_out[i]; j != last_out; ++j) {
817          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
818          _cost[j] = lc;
819          if (lc > _epsilon) _epsilon = lc;
820        }
821      }
822      _epsilon /= _alpha;
823
824      // Initialize maps for Circulation and remove non-zero lower bounds
825      ConstMap<Arc, Value> low(0);
826      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
827      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
828      ValueArcMap cap(_graph), flow(_graph);
829      ValueNodeMap sup(_graph);
830      for (NodeIt n(_graph); n != INVALID; ++n) {
831        sup[n] = _supply[_node_id[n]];
832      }
833      if (_have_lower) {
834        for (ArcIt a(_graph); a != INVALID; ++a) {
835          int j = _arc_idf[a];
836          Value c = _lower[j];
837          cap[a] = _upper[j] - c;
838          sup[_graph.source(a)] -= c;
839          sup[_graph.target(a)] += c;
840        }
841      } else {
842        for (ArcIt a(_graph); a != INVALID; ++a) {
843          cap[a] = _upper[_arc_idf[a]];
844        }
845      }
846
847      _sup_node_num = 0;
848      for (NodeIt n(_graph); n != INVALID; ++n) {
849        if (sup[n] > 0) ++_sup_node_num;
850      }
851
852      // Find a feasible flow using Circulation
853      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
854        circ(_graph, low, cap, sup);
855      if (!circ.flowMap(flow).run()) return INFEASIBLE;
856
857      // Set residual capacities and handle GEQ supply type
858      if (_sum_supply < 0) {
859        for (ArcIt a(_graph); a != INVALID; ++a) {
860          Value fa = flow[a];
861          _res_cap[_arc_idf[a]] = cap[a] - fa;
862          _res_cap[_arc_idb[a]] = fa;
863          sup[_graph.source(a)] -= fa;
864          sup[_graph.target(a)] += fa;
865        }
866        for (NodeIt n(_graph); n != INVALID; ++n) {
867          _excess[_node_id[n]] = sup[n];
868        }
869        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
870          int u = _target[a];
871          int ra = _reverse[a];
872          _res_cap[a] = -_sum_supply + 1;
873          _res_cap[ra] = -_excess[u];
874          _cost[a] = 0;
875          _cost[ra] = 0;
876          _excess[u] = 0;
877        }
878      } else {
879        for (ArcIt a(_graph); a != INVALID; ++a) {
880          Value fa = flow[a];
881          _res_cap[_arc_idf[a]] = cap[a] - fa;
882          _res_cap[_arc_idb[a]] = fa;
883        }
884        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
885          int ra = _reverse[a];
886          _res_cap[a] = 0;
887          _res_cap[ra] = 0;
888          _cost[a] = 0;
889          _cost[ra] = 0;
890        }
891      }
892
893      // Initialize data structures for buckets
894      _max_rank = _alpha * _res_node_num;
895      _buckets.resize(_max_rank);
896      _bucket_next.resize(_res_node_num + 1);
897      _bucket_prev.resize(_res_node_num + 1);
898      _rank.resize(_res_node_num + 1);
899
900      return OPTIMAL;
901    }
902
903    // Execute the algorithm and transform the results
904    void start(Method method) {
905      const int MAX_PARTIAL_PATH_LENGTH = 4;
906
907      switch (method) {
908        case PUSH:
909          startPush();
910          break;
911        case AUGMENT:
912          startAugment(_res_node_num - 1);
913          break;
914        case PARTIAL_AUGMENT:
915          startAugment(MAX_PARTIAL_PATH_LENGTH);
916          break;
917      }
918
919      // Compute node potentials (dual solution)
920      for (int i = 0; i != _res_node_num; ++i) {
921        _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
922      }
923      bool optimal = true;
924      for (int i = 0; optimal && i != _res_node_num; ++i) {
925        LargeCost pi_i = _pi[i];
926        int last_out = _first_out[i+1];
927        for (int j = _first_out[i]; j != last_out; ++j) {
928          if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
929            optimal = false;
930            break;
931          }
932        }
933      }
934
935      if (!optimal) {
936        // Compute node potentials for the original costs with BellmanFord
937        // (if it is necessary)
938        typedef std::pair<int, int> IntPair;
939        StaticDigraph sgr;
940        std::vector<IntPair> arc_vec;
941        std::vector<LargeCost> cost_vec;
942        LargeCostArcMap cost_map(cost_vec);
943
944        arc_vec.clear();
945        cost_vec.clear();
946        for (int j = 0; j != _res_arc_num; ++j) {
947          if (_res_cap[j] > 0) {
948            int u = _source[j], v = _target[j];
949            arc_vec.push_back(IntPair(u, v));
950            cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
951          }
952        }
953        sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
954
955        typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
956          bf(sgr, cost_map);
957        bf.init(0);
958        bf.start();
959
960        for (int i = 0; i != _res_node_num; ++i) {
961          _pi[i] += bf.dist(sgr.node(i));
962        }
963      }
964
965      // Shift potentials to meet the requirements of the GEQ type
966      // optimality conditions
967      LargeCost max_pot = _pi[_root];
968      for (int i = 0; i != _res_node_num; ++i) {
969        if (_pi[i] > max_pot) max_pot = _pi[i];
970      }
971      if (max_pot != 0) {
972        for (int i = 0; i != _res_node_num; ++i) {
973          _pi[i] -= max_pot;
974        }
975      }
976
977      // Handle non-zero lower bounds
978      if (_have_lower) {
979        int limit = _first_out[_root];
980        for (int j = 0; j != limit; ++j) {
981          if (!_forward[j]) _res_cap[j] += _lower[j];
982        }
983      }
984    }
985
986    // Initialize a cost scaling phase
987    void initPhase() {
988      // Saturate arcs not satisfying the optimality condition
989      for (int u = 0; u != _res_node_num; ++u) {
990        int last_out = _first_out[u+1];
991        LargeCost pi_u = _pi[u];
992        for (int a = _first_out[u]; a != last_out; ++a) {
993          Value delta = _res_cap[a];
994          if (delta > 0) {
995            int v = _target[a];
996            if (_cost[a] + pi_u - _pi[v] < 0) {
997              _excess[u] -= delta;
998              _excess[v] += delta;
999              _res_cap[a] = 0;
1000              _res_cap[_reverse[a]] += delta;
1001            }
1002          }
1003        }
1004      }
1005
1006      // Find active nodes (i.e. nodes with positive excess)
1007      for (int u = 0; u != _res_node_num; ++u) {
1008        if (_excess[u] > 0) _active_nodes.push_back(u);
1009      }
1010
1011      // Initialize the next arcs
1012      for (int u = 0; u != _res_node_num; ++u) {
1013        _next_out[u] = _first_out[u];
1014      }
1015    }
1016
1017    // Price (potential) refinement heuristic
1018    bool priceRefinement() {
1019
1020      // Stack for stroing the topological order
1021      IntVector stack(_res_node_num);
1022      int stack_top;
1023
1024      // Perform phases
1025      while (topologicalSort(stack, stack_top)) {
1026
1027        // Compute node ranks in the acyclic admissible network and
1028        // store the nodes in buckets
1029        for (int i = 0; i != _res_node_num; ++i) {
1030          _rank[i] = 0;
1031        }
1032        const int bucket_end = _root + 1;
1033        for (int r = 0; r != _max_rank; ++r) {
1034          _buckets[r] = bucket_end;
1035        }
1036        int top_rank = 0;
1037        for ( ; stack_top >= 0; --stack_top) {
1038          int u = stack[stack_top], v;
1039          int rank_u = _rank[u];
1040
1041          LargeCost rc, pi_u = _pi[u];
1042          int last_out = _first_out[u+1];
1043          for (int a = _first_out[u]; a != last_out; ++a) {
1044            if (_res_cap[a] > 0) {
1045              v = _target[a];
1046              rc = _cost[a] + pi_u - _pi[v];
1047              if (rc < 0) {
1048                LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
1049                if (nrc < LargeCost(_max_rank)) {
1050                  int new_rank_v = rank_u + static_cast<int>(nrc);
1051                  if (new_rank_v > _rank[v]) {
1052                    _rank[v] = new_rank_v;
1053                  }
1054                }
1055              }
1056            }
1057          }
1058
1059          if (rank_u > 0) {
1060            top_rank = std::max(top_rank, rank_u);
1061            int bfirst = _buckets[rank_u];
1062            _bucket_next[u] = bfirst;
1063            _bucket_prev[bfirst] = u;
1064            _buckets[rank_u] = u;
1065          }
1066        }
1067
1068        // Check if the current flow is epsilon-optimal
1069        if (top_rank == 0) {
1070          return true;
1071        }
1072
1073        // Process buckets in top-down order
1074        for (int rank = top_rank; rank > 0; --rank) {
1075          while (_buckets[rank] != bucket_end) {
1076            // Remove the first node from the current bucket
1077            int u = _buckets[rank];
1078            _buckets[rank] = _bucket_next[u];
1079
1080            // Search the outgoing arcs of u
1081            LargeCost rc, pi_u = _pi[u];
1082            int last_out = _first_out[u+1];
1083            int v, old_rank_v, new_rank_v;
1084            for (int a = _first_out[u]; a != last_out; ++a) {
1085              if (_res_cap[a] > 0) {
1086                v = _target[a];
1087                old_rank_v = _rank[v];
1088
1089                if (old_rank_v < rank) {
1090
1091                  // Compute the new rank of node v
1092                  rc = _cost[a] + pi_u - _pi[v];
1093                  if (rc < 0) {
1094                    new_rank_v = rank;
1095                  } else {
1096                    LargeCost nrc = rc / _epsilon;
1097                    new_rank_v = 0;
1098                    if (nrc < LargeCost(_max_rank)) {
1099                      new_rank_v = rank - 1 - static_cast<int>(nrc);
1100                    }
1101                  }
1102
1103                  // Change the rank of node v
1104                  if (new_rank_v > old_rank_v) {
1105                    _rank[v] = new_rank_v;
1106
1107                    // Remove v from its old bucket
1108                    if (old_rank_v > 0) {
1109                      if (_buckets[old_rank_v] == v) {
1110                        _buckets[old_rank_v] = _bucket_next[v];
1111                      } else {
1112                        int pv = _bucket_prev[v], nv = _bucket_next[v];
1113                        _bucket_next[pv] = nv;
1114                        _bucket_prev[nv] = pv;
1115                      }
1116                    }
1117
1118                    // Insert v into its new bucket
1119                    int nv = _buckets[new_rank_v];
1120                    _bucket_next[v] = nv;
1121                    _bucket_prev[nv] = v;
1122                    _buckets[new_rank_v] = v;
1123                  }
1124                }
1125              }
1126            }
1127
1128            // Refine potential of node u
1129            _pi[u] -= rank * _epsilon;
1130          }
1131        }
1132
1133      }
1134
1135      return false;
1136    }
1137
1138    // Find and cancel cycles in the admissible network and
1139    // determine topological order using DFS
1140    bool topologicalSort(IntVector &stack, int &stack_top) {
1141      const int MAX_CYCLE_CANCEL = 1;
1142
1143      BoolVector reached(_res_node_num, false);
1144      BoolVector processed(_res_node_num, false);
1145      IntVector pred(_res_node_num);
1146      for (int i = 0; i != _res_node_num; ++i) {
1147        _next_out[i] = _first_out[i];
1148      }
1149      stack_top = -1;
1150
1151      int cycle_cnt = 0;
1152      for (int start = 0; start != _res_node_num; ++start) {
1153        if (reached[start]) continue;
1154
1155        // Start DFS search from this start node
1156        pred[start] = -1;
1157        int tip = start, v;
1158        while (true) {
1159          // Check the outgoing arcs of the current tip node
1160          reached[tip] = true;
1161          LargeCost pi_tip = _pi[tip];
1162          int a, last_out = _first_out[tip+1];
1163          for (a = _next_out[tip]; a != last_out; ++a) {
1164            if (_res_cap[a] > 0) {
1165              v = _target[a];
1166              if (_cost[a] + pi_tip - _pi[v] < 0) {
1167                if (!reached[v]) {
1168                  // A new node is reached
1169                  reached[v] = true;
1170                  pred[v] = tip;
1171                  _next_out[tip] = a;
1172                  tip = v;
1173                  a = _next_out[tip];
1174                  last_out = _first_out[tip+1];
1175                  break;
1176                }
1177                else if (!processed[v]) {
1178                  // A cycle is found
1179                  ++cycle_cnt;
1180                  _next_out[tip] = a;
1181
1182                  // Find the minimum residual capacity along the cycle
1183                  Value d, delta = _res_cap[a];
1184                  int u, delta_node = tip;
1185                  for (u = tip; u != v; ) {
1186                    u = pred[u];
1187                    d = _res_cap[_next_out[u]];
1188                    if (d <= delta) {
1189                      delta = d;
1190                      delta_node = u;
1191                    }
1192                  }
1193
1194                  // Augment along the cycle
1195                  _res_cap[a] -= delta;
1196                  _res_cap[_reverse[a]] += delta;
1197                  for (u = tip; u != v; ) {
1198                    u = pred[u];
1199                    int ca = _next_out[u];
1200                    _res_cap[ca] -= delta;
1201                    _res_cap[_reverse[ca]] += delta;
1202                  }
1203
1204                  // Check the maximum number of cycle canceling
1205                  if (cycle_cnt >= MAX_CYCLE_CANCEL) {
1206                    return false;
1207                  }
1208
1209                  // Roll back search to delta_node
1210                  if (delta_node != tip) {
1211                    for (u = tip; u != delta_node; u = pred[u]) {
1212                      reached[u] = false;
1213                    }
1214                    tip = delta_node;
1215                    a = _next_out[tip] + 1;
1216                    last_out = _first_out[tip+1];
1217                    break;
1218                  }
1219                }
1220              }
1221            }
1222          }
1223
1224          // Step back to the previous node
1225          if (a == last_out) {
1226            processed[tip] = true;
1227            stack[++stack_top] = tip;
1228            tip = pred[tip];
1229            if (tip < 0) {
1230              // Finish DFS from the current start node
1231              break;
1232            }
1233            ++_next_out[tip];
1234          }
1235        }
1236
1237      }
1238
1239      return (cycle_cnt == 0);
1240    }
1241
1242    // Global potential update heuristic
1243    void globalUpdate() {
1244      const int bucket_end = _root + 1;
1245
1246      // Initialize buckets
1247      for (int r = 0; r != _max_rank; ++r) {
1248        _buckets[r] = bucket_end;
1249      }
1250      Value total_excess = 0;
1251      int b0 = bucket_end;
1252      for (int i = 0; i != _res_node_num; ++i) {
1253        if (_excess[i] < 0) {
1254          _rank[i] = 0;
1255          _bucket_next[i] = b0;
1256          _bucket_prev[b0] = i;
1257          b0 = i;
1258        } else {
1259          total_excess += _excess[i];
1260          _rank[i] = _max_rank;
1261        }
1262      }
1263      if (total_excess == 0) return;
1264      _buckets[0] = b0;
1265
1266      // Search the buckets
1267      int r = 0;
1268      for ( ; r != _max_rank; ++r) {
1269        while (_buckets[r] != bucket_end) {
1270          // Remove the first node from the current bucket
1271          int u = _buckets[r];
1272          _buckets[r] = _bucket_next[u];
1273
1274          // Search the incoming arcs of u
1275          LargeCost pi_u = _pi[u];
1276          int last_out = _first_out[u+1];
1277          for (int a = _first_out[u]; a != last_out; ++a) {
1278            int ra = _reverse[a];
1279            if (_res_cap[ra] > 0) {
1280              int v = _source[ra];
1281              int old_rank_v = _rank[v];
1282              if (r < old_rank_v) {
1283                // Compute the new rank of v
1284                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1285                int new_rank_v = old_rank_v;
1286                if (nrc < LargeCost(_max_rank)) {
1287                  new_rank_v = r + 1 + static_cast<int>(nrc);
1288                }
1289
1290                // Change the rank of v
1291                if (new_rank_v < old_rank_v) {
1292                  _rank[v] = new_rank_v;
1293                  _next_out[v] = _first_out[v];
1294
1295                  // Remove v from its old bucket
1296                  if (old_rank_v < _max_rank) {
1297                    if (_buckets[old_rank_v] == v) {
1298                      _buckets[old_rank_v] = _bucket_next[v];
1299                    } else {
1300                      int pv = _bucket_prev[v], nv = _bucket_next[v];
1301                      _bucket_next[pv] = nv;
1302                      _bucket_prev[nv] = pv;
1303                    }
1304                  }
1305
1306                  // Insert v into its new bucket
1307                  int nv = _buckets[new_rank_v];
1308                  _bucket_next[v] = nv;
1309                  _bucket_prev[nv] = v;
1310                  _buckets[new_rank_v] = v;
1311                }
1312              }
1313            }
1314          }
1315
1316          // Finish search if there are no more active nodes
1317          if (_excess[u] > 0) {
1318            total_excess -= _excess[u];
1319            if (total_excess <= 0) break;
1320          }
1321        }
1322        if (total_excess <= 0) break;
1323      }
1324
1325      // Relabel nodes
1326      for (int u = 0; u != _res_node_num; ++u) {
1327        int k = std::min(_rank[u], r);
1328        if (k > 0) {
1329          _pi[u] -= _epsilon * k;
1330          _next_out[u] = _first_out[u];
1331        }
1332      }
1333    }
1334
1335    /// Execute the algorithm performing augment and relabel operations
1336    void startAugment(int max_length) {
1337      // Paramters for heuristics
1338      const int PRICE_REFINEMENT_LIMIT = 2;
1339      const double GLOBAL_UPDATE_FACTOR = 1.0;
1340      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1341        (_res_node_num + _sup_node_num * _sup_node_num));
1342      int next_global_update_limit = global_update_skip;
1343
1344      // Perform cost scaling phases
1345      IntVector path;
1346      BoolVector path_arc(_res_arc_num, false);
1347      int relabel_cnt = 0;
1348      int eps_phase_cnt = 0;
1349      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1350                                        1 : _epsilon / _alpha )
1351      {
1352        ++eps_phase_cnt;
1353
1354        // Price refinement heuristic
1355        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1356          if (priceRefinement()) continue;
1357        }
1358
1359        // Initialize current phase
1360        initPhase();
1361
1362        // Perform partial augment and relabel operations
1363        while (true) {
1364          // Select an active node (FIFO selection)
1365          while (_active_nodes.size() > 0 &&
1366                 _excess[_active_nodes.front()] <= 0) {
1367            _active_nodes.pop_front();
1368          }
1369          if (_active_nodes.size() == 0) break;
1370          int start = _active_nodes.front();
1371
1372          // Find an augmenting path from the start node
1373          int tip = start;
1374          while (int(path.size()) < max_length && _excess[tip] >= 0) {
1375            int u;
1376            LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
1377            LargeCost pi_tip = _pi[tip];
1378            int last_out = _first_out[tip+1];
1379            for (int a = _next_out[tip]; a != last_out; ++a) {
1380              if (_res_cap[a] > 0) {
1381                u = _target[a];
1382                rc = _cost[a] + pi_tip - _pi[u];
1383                if (rc < 0) {
1384                  path.push_back(a);
1385                  _next_out[tip] = a;
1386                  if (path_arc[a]) {
1387                    goto augment;   // a cycle is found, stop path search
1388                  }
1389                  tip = u;
1390                  path_arc[a] = true;
1391                  goto next_step;
1392                }
1393                else if (rc < min_red_cost) {
1394                  min_red_cost = rc;
1395                }
1396              }
1397            }
1398
1399            // Relabel tip node
1400            if (tip != start) {
1401              int ra = _reverse[path.back()];
1402              min_red_cost =
1403                std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
1404            }
1405            last_out = _next_out[tip];
1406            for (int a = _first_out[tip]; a != last_out; ++a) {
1407              if (_res_cap[a] > 0) {
1408                rc = _cost[a] + pi_tip - _pi[_target[a]];
1409                if (rc < min_red_cost) {
1410                  min_red_cost = rc;
1411                }
1412              }
1413            }
1414            _pi[tip] -= min_red_cost + _epsilon;
1415            _next_out[tip] = _first_out[tip];
1416            ++relabel_cnt;
1417
1418            // Step back
1419            if (tip != start) {
1420              int pa = path.back();
1421              path_arc[pa] = false;
1422              tip = _source[pa];
1423              path.pop_back();
1424            }
1425
1426          next_step: ;
1427          }
1428
1429          // Augment along the found path (as much flow as possible)
1430        augment:
1431          Value delta;
1432          int pa, u, v = start;
1433          for (int i = 0; i != int(path.size()); ++i) {
1434            pa = path[i];
1435            u = v;
1436            v = _target[pa];
1437            path_arc[pa] = false;
1438            delta = std::min(_res_cap[pa], _excess[u]);
1439            _res_cap[pa] -= delta;
1440            _res_cap[_reverse[pa]] += delta;
1441            _excess[u] -= delta;
1442            _excess[v] += delta;
1443            if (_excess[v] > 0 && _excess[v] <= delta) {
1444              _active_nodes.push_back(v);
1445            }
1446          }
1447          path.clear();
1448
1449          // Global update heuristic
1450          if (relabel_cnt >= next_global_update_limit) {
1451            globalUpdate();
1452            next_global_update_limit += global_update_skip;
1453          }
1454        }
1455
1456      }
1457
1458    }
1459
1460    /// Execute the algorithm performing push and relabel operations
1461    void startPush() {
1462      // Paramters for heuristics
1463      const int PRICE_REFINEMENT_LIMIT = 2;
1464      const double GLOBAL_UPDATE_FACTOR = 2.0;
1465
1466      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
1467        (_res_node_num + _sup_node_num * _sup_node_num));
1468      int next_global_update_limit = global_update_skip;
1469
1470      // Perform cost scaling phases
1471      BoolVector hyper(_res_node_num, false);
1472      LargeCostVector hyper_cost(_res_node_num);
1473      int relabel_cnt = 0;
1474      int eps_phase_cnt = 0;
1475      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1476                                        1 : _epsilon / _alpha )
1477      {
1478        ++eps_phase_cnt;
1479
1480        // Price refinement heuristic
1481        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
1482          if (priceRefinement()) continue;
1483        }
1484
1485        // Initialize current phase
1486        initPhase();
1487
1488        // Perform push and relabel operations
1489        while (_active_nodes.size() > 0) {
1490          LargeCost min_red_cost, rc, pi_n;
1491          Value delta;
1492          int n, t, a, last_out = _res_arc_num;
1493
1494        next_node:
1495          // Select an active node (FIFO selection)
1496          n = _active_nodes.front();
1497          last_out = _first_out[n+1];
1498          pi_n = _pi[n];
1499
1500          // Perform push operations if there are admissible arcs
1501          if (_excess[n] > 0) {
1502            for (a = _next_out[n]; a != last_out; ++a) {
1503              if (_res_cap[a] > 0 &&
1504                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
1505                delta = std::min(_res_cap[a], _excess[n]);
1506                t = _target[a];
1507
1508                // Push-look-ahead heuristic
1509                Value ahead = -_excess[t];
1510                int last_out_t = _first_out[t+1];
1511                LargeCost pi_t = _pi[t];
1512                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1513                  if (_res_cap[ta] > 0 &&
1514                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1515                    ahead += _res_cap[ta];
1516                  if (ahead >= delta) break;
1517                }
1518                if (ahead < 0) ahead = 0;
1519
1520                // Push flow along the arc
1521                if (ahead < delta && !hyper[t]) {
1522                  _res_cap[a] -= ahead;
1523                  _res_cap[_reverse[a]] += ahead;
1524                  _excess[n] -= ahead;
1525                  _excess[t] += ahead;
1526                  _active_nodes.push_front(t);
1527                  hyper[t] = true;
1528                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
1529                  _next_out[n] = a;
1530                  goto next_node;
1531                } else {
1532                  _res_cap[a] -= delta;
1533                  _res_cap[_reverse[a]] += delta;
1534                  _excess[n] -= delta;
1535                  _excess[t] += delta;
1536                  if (_excess[t] > 0 && _excess[t] <= delta)
1537                    _active_nodes.push_back(t);
1538                }
1539
1540                if (_excess[n] == 0) {
1541                  _next_out[n] = a;
1542                  goto remove_nodes;
1543                }
1544              }
1545            }
1546            _next_out[n] = a;
1547          }
1548
1549          // Relabel the node if it is still active (or hyper)
1550          if (_excess[n] > 0 || hyper[n]) {
1551             min_red_cost = hyper[n] ? -hyper_cost[n] :
1552               std::numeric_limits<LargeCost>::max();
1553            for (int a = _first_out[n]; a != last_out; ++a) {
1554              if (_res_cap[a] > 0) {
1555                rc = _cost[a] + pi_n - _pi[_target[a]];
1556                if (rc < min_red_cost) {
1557                  min_red_cost = rc;
1558                }
1559              }
1560            }
1561            _pi[n] -= min_red_cost + _epsilon;
1562            _next_out[n] = _first_out[n];
1563            hyper[n] = false;
1564            ++relabel_cnt;
1565          }
1566
1567          // Remove nodes that are not active nor hyper
1568        remove_nodes:
1569          while ( _active_nodes.size() > 0 &&
1570                  _excess[_active_nodes.front()] <= 0 &&
1571                  !hyper[_active_nodes.front()] ) {
1572            _active_nodes.pop_front();
1573          }
1574
1575          // Global update heuristic
1576          if (relabel_cnt >= next_global_update_limit) {
1577            globalUpdate();
1578            for (int u = 0; u != _res_node_num; ++u)
1579              hyper[u] = false;
1580            next_global_update_limit += global_update_skip;
1581          }
1582        }
1583      }
1584    }
1585
1586  }; //class CostScaling
1587
1588  ///@}
1589
1590} //namespace lemon
1591
1592#endif //LEMON_COST_SCALING_H
Note: See TracBrowser for help on using the repository browser.