1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
 
     3  * This file is a part of LEMON, a generic C++ optimization library.
 
     5  * Copyright (C) 2003-2013
 
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
 
     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.
 
    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
 
    19 #ifndef LEMON_CAPACITY_SCALING_H
 
    20 #define LEMON_CAPACITY_SCALING_H
 
    22 /// \ingroup min_cost_flow_algs
 
    25 /// \brief Capacity Scaling algorithm for finding a minimum cost flow.
 
    29 #include <lemon/core.h>
 
    30 #include <lemon/bin_heap.h>
 
    34   /// \brief Default traits class of CapacityScaling algorithm.
 
    36   /// Default traits class of CapacityScaling algorithm.
 
    37   /// \tparam GR Digraph type.
 
    38   /// \tparam V The number type used for flow amounts, capacity bounds
 
    39   /// and supply values. By default it is \c int.
 
    40   /// \tparam C The number type used for costs and potentials.
 
    41   /// By default it is the same as \c V.
 
    42   template <typename GR, typename V = int, typename C = V>
 
    43   struct CapacityScalingDefaultTraits
 
    45     /// The type of the digraph
 
    47     /// The type of the flow amounts, capacity bounds and supply values
 
    49     /// The type of the arc costs
 
    52     /// \brief The type of the heap used for internal Dijkstra computations.
 
    54     /// The type of the heap used for internal Dijkstra computations.
 
    55     /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
 
    56     /// its priority type must be \c Cost and its cross reference type
 
    57     /// must be \ref RangeMap "RangeMap<int>".
 
    58     typedef BinHeap<Cost, RangeMap<int> > Heap;
 
    61   /// \addtogroup min_cost_flow_algs
 
    64   /// \brief Implementation of the Capacity Scaling algorithm for
 
    65   /// finding a \ref min_cost_flow "minimum cost flow".
 
    67   /// \ref CapacityScaling implements the capacity scaling version
 
    68   /// of the successive shortest path algorithm for finding a
 
    69   /// \ref min_cost_flow "minimum cost flow" \cite amo93networkflows,
 
    70   /// \cite edmondskarp72theoretical. It is an efficient dual
 
    71   /// solution method, which runs in polynomial time
 
    72   /// \f$O(m\log U (n+m)\log n)\f$, where <i>U</i> denotes the maximum
 
    73   /// of node supply and arc capacity values.
 
    75   /// This algorithm is typically slower than \ref CostScaling and
 
    76   /// \ref NetworkSimplex, but in special cases, it can be more
 
    77   /// efficient than them.
 
    78   /// (For more information, see \ref min_cost_flow_algs "the module page".)
 
    80   /// Most of the parameters of the problem (except for the digraph)
 
    81   /// can be given using separate functions, and the algorithm can be
 
    82   /// executed using the \ref run() function. If some parameters are not
 
    83   /// specified, then default values will be used.
 
    85   /// \tparam GR The digraph type the algorithm runs on.
 
    86   /// \tparam V The number type used for flow amounts, capacity bounds
 
    87   /// and supply values in the algorithm. By default, it is \c int.
 
    88   /// \tparam C The number type used for costs and potentials in the
 
    89   /// algorithm. By default, it is the same as \c V.
 
    90   /// \tparam TR The traits class that defines various types used by the
 
    91   /// algorithm. By default, it is \ref CapacityScalingDefaultTraits
 
    92   /// "CapacityScalingDefaultTraits<GR, V, C>".
 
    93   /// In most cases, this parameter should not be set directly,
 
    94   /// consider to use the named template parameters instead.
 
    96   /// \warning Both \c V and \c C must be signed number types.
 
    97   /// \warning Capacity bounds and supply values must be integer, but
 
    98   /// arc costs can be arbitrary real numbers.
 
    99   /// \warning This algorithm does not support negative costs for
 
   100   /// arcs having infinite upper bound.
 
   102   template <typename GR, typename V, typename C, typename TR>
 
   104   template < typename GR, typename V = int, typename C = V,
 
   105              typename TR = CapacityScalingDefaultTraits<GR, V, C> >
 
   107   class CapacityScaling
 
   111     /// The type of the digraph
 
   112     typedef typename TR::Digraph Digraph;
 
   113     /// The type of the flow amounts, capacity bounds and supply values
 
   114     typedef typename TR::Value Value;
 
   115     /// The type of the arc costs
 
   116     typedef typename TR::Cost Cost;
 
   118     /// The type of the heap used for internal Dijkstra computations
 
   119     typedef typename TR::Heap Heap;
 
   121     /// \brief The \ref lemon::CapacityScalingDefaultTraits "traits class"
 
   127     /// \brief Problem type constants for the \c run() function.
 
   129     /// Enum type containing the problem type constants that can be
 
   130     /// returned by the \ref run() function of the algorithm.
 
   132       /// The problem has no feasible solution (flow).
 
   134       /// The problem has optimal solution (i.e. it is feasible and
 
   135       /// bounded), and the algorithm has found optimal flow and node
 
   136       /// potentials (primal and dual solutions).
 
   138       /// The digraph contains an arc of negative cost and infinite
 
   139       /// upper bound. It means that the objective function is unbounded
 
   140       /// on that arc, however, note that it could actually be bounded
 
   141       /// over the feasible flows, but this algroithm cannot handle
 
   148     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
 
   150     typedef std::vector<int> IntVector;
 
   151     typedef std::vector<Value> ValueVector;
 
   152     typedef std::vector<Cost> CostVector;
 
   153     typedef std::vector<char> BoolVector;
 
   154     // Note: vector<char> is used instead of vector<bool> for efficiency reasons
 
   158     // Data related to the underlying digraph
 
   165     // Parameters of the problem
 
   169     // Data structures for storing the digraph
 
   173     IntVector _first_out;
 
   185     ValueVector _res_cap;
 
   188     IntVector _excess_nodes;
 
   189     IntVector _deficit_nodes;
 
   197     /// \brief Constant for infinite upper bounds (capacities).
 
   199     /// Constant for infinite upper bounds (capacities).
 
   200     /// It is \c std::numeric_limits<Value>::infinity() if available,
 
   201     /// \c std::numeric_limits<Value>::max() otherwise.
 
   206     // Special implementation of the Dijkstra algorithm for finding
 
   207     // shortest paths in the residual network of the digraph with
 
   208     // respect to the reduced arc costs and modifying the node
 
   209     // potentials according to the found distance labels.
 
   210     class ResidualDijkstra
 
   216       const IntVector &_first_out;
 
   217       const IntVector &_target;
 
   218       const CostVector &_cost;
 
   219       const ValueVector &_res_cap;
 
   220       const ValueVector &_excess;
 
   224       IntVector _proc_nodes;
 
   229       ResidualDijkstra(CapacityScaling& cs) :
 
   230         _node_num(cs._node_num), _geq(cs._sum_supply < 0),
 
   231         _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
 
   232         _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
 
   233         _pred(cs._pred), _dist(cs._node_num)
 
   236       int run(int s, Value delta = 1) {
 
   237         RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
 
   238         Heap heap(heap_cross_ref);
 
   244         while (!heap.empty() && _excess[heap.top()] > -delta) {
 
   245           int u = heap.top(), v;
 
   246           Cost d = heap.prio() + _pi[u], dn;
 
   247           _dist[u] = heap.prio();
 
   248           _proc_nodes.push_back(u);
 
   251           // Traverse outgoing residual arcs
 
   252           int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1;
 
   253           for (int a = _first_out[u]; a != last_out; ++a) {
 
   254             if (_res_cap[a] < delta) continue;
 
   256             switch (heap.state(v)) {
 
   258                 heap.push(v, d + _cost[a] - _pi[v]);
 
   262                 dn = d + _cost[a] - _pi[v];
 
   264                   heap.decrease(v, dn);
 
   268               case Heap::POST_HEAP:
 
   273         if (heap.empty()) return -1;
 
   275         // Update potentials of processed nodes
 
   277         Cost dt = heap.prio();
 
   278         for (int i = 0; i < int(_proc_nodes.size()); ++i) {
 
   279           _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
 
   285     }; //class ResidualDijkstra
 
   289     /// \name Named Template Parameters
 
   292     template <typename T>
 
   293     struct SetHeapTraits : public Traits {
 
   297     /// \brief \ref named-templ-param "Named parameter" for setting
 
   300     /// \ref named-templ-param "Named parameter" for setting \c Heap
 
   301     /// type, which is used for internal Dijkstra computations.
 
   302     /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
 
   303     /// its priority type must be \c Cost and its cross reference type
 
   304     /// must be \ref RangeMap "RangeMap<int>".
 
   305     template <typename T>
 
   307       : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
 
   308       typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
 
   319     /// \brief Constructor.
 
   321     /// The constructor of the class.
 
   323     /// \param graph The digraph the algorithm runs on.
 
   324     CapacityScaling(const GR& graph) :
 
   325       _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
 
   326       INF(std::numeric_limits<Value>::has_infinity ?
 
   327           std::numeric_limits<Value>::infinity() :
 
   328           std::numeric_limits<Value>::max())
 
   330       // Check the number types
 
   331       LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
 
   332         "The flow type of CapacityScaling must be signed");
 
   333       LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
 
   334         "The cost type of CapacityScaling must be signed");
 
   336       // Reset data structures
 
   341     /// The parameters of the algorithm can be specified using these
 
   346     /// \brief Set the lower bounds on the arcs.
 
   348     /// This function sets the lower bounds on the arcs.
 
   349     /// If it is not used before calling \ref run(), the lower bounds
 
   350     /// will be set to zero on all arcs.
 
   352     /// \param map An arc map storing the lower bounds.
 
   353     /// Its \c Value type must be convertible to the \c Value type
 
   354     /// of the algorithm.
 
   356     /// \return <tt>(*this)</tt>
 
   357     template <typename LowerMap>
 
   358     CapacityScaling& lowerMap(const LowerMap& map) {
 
   360       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   361         _lower[_arc_idf[a]] = map[a];
 
   366     /// \brief Set the upper bounds (capacities) on the arcs.
 
   368     /// This function sets the upper bounds (capacities) on the arcs.
 
   369     /// If it is not used before calling \ref run(), the upper bounds
 
   370     /// will be set to \ref INF on all arcs (i.e. the flow value will be
 
   371     /// unbounded from above).
 
   373     /// \param map An arc map storing the upper bounds.
 
   374     /// Its \c Value type must be convertible to the \c Value type
 
   375     /// of the algorithm.
 
   377     /// \return <tt>(*this)</tt>
 
   378     template<typename UpperMap>
 
   379     CapacityScaling& upperMap(const UpperMap& map) {
 
   380       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   381         _upper[_arc_idf[a]] = map[a];
 
   386     /// \brief Set the costs of the arcs.
 
   388     /// This function sets the costs of the arcs.
 
   389     /// If it is not used before calling \ref run(), the costs
 
   390     /// will be set to \c 1 on all arcs.
 
   392     /// \param map An arc map storing the costs.
 
   393     /// Its \c Value type must be convertible to the \c Cost type
 
   394     /// of the algorithm.
 
   396     /// \return <tt>(*this)</tt>
 
   397     template<typename CostMap>
 
   398     CapacityScaling& costMap(const CostMap& map) {
 
   399       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   400         _cost[_arc_idf[a]] =  map[a];
 
   401         _cost[_arc_idb[a]] = -map[a];
 
   406     /// \brief Set the supply values of the nodes.
 
   408     /// This function sets the supply values of the nodes.
 
   409     /// If neither this function nor \ref stSupply() is used before
 
   410     /// calling \ref run(), the supply of each node will be set to zero.
 
   412     /// \param map A node map storing the supply values.
 
   413     /// Its \c Value type must be convertible to the \c Value type
 
   414     /// of the algorithm.
 
   416     /// \return <tt>(*this)</tt>
 
   417     template<typename SupplyMap>
 
   418     CapacityScaling& supplyMap(const SupplyMap& map) {
 
   419       for (NodeIt n(_graph); n != INVALID; ++n) {
 
   420         _supply[_node_id[n]] = map[n];
 
   425     /// \brief Set single source and target nodes and a supply value.
 
   427     /// This function sets a single source node and a single target node
 
   428     /// and the required flow value.
 
   429     /// If neither this function nor \ref supplyMap() is used before
 
   430     /// calling \ref run(), the supply of each node will be set to zero.
 
   432     /// Using this function has the same effect as using \ref supplyMap()
 
   433     /// with a map in which \c k is assigned to \c s, \c -k is
 
   434     /// assigned to \c t and all other nodes have zero supply value.
 
   436     /// \param s The source node.
 
   437     /// \param t The target node.
 
   438     /// \param k The required amount of flow from node \c s to node \c t
 
   439     /// (i.e. the supply of \c s and the demand of \c t).
 
   441     /// \return <tt>(*this)</tt>
 
   442     CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
 
   443       for (int i = 0; i != _node_num; ++i) {
 
   446       _supply[_node_id[s]] =  k;
 
   447       _supply[_node_id[t]] = -k;
 
   453     /// \name Execution control
 
   454     /// The algorithm can be executed using \ref run().
 
   458     /// \brief Run the algorithm.
 
   460     /// This function runs the algorithm.
 
   461     /// The paramters can be specified using functions \ref lowerMap(),
 
   462     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
 
   465     ///   CapacityScaling<ListDigraph> cs(graph);
 
   466     ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
 
   467     ///     .supplyMap(sup).run();
 
   470     /// This function can be called more than once. All the given parameters
 
   471     /// are kept for the next call, unless \ref resetParams() or \ref reset()
 
   472     /// is used, thus only the modified parameters have to be set again.
 
   473     /// If the underlying digraph was also modified after the construction
 
   474     /// of the class (or the last \ref reset() call), then the \ref reset()
 
   475     /// function must be called.
 
   477     /// \param factor The capacity scaling factor. It must be larger than
 
   478     /// one to use scaling. If it is less or equal to one, then scaling
 
   479     /// will be disabled.
 
   481     /// \return \c INFEASIBLE if no feasible flow exists,
 
   482     /// \n \c OPTIMAL if the problem has optimal solution
 
   483     /// (i.e. it is feasible and bounded), and the algorithm has found
 
   484     /// optimal flow and node potentials (primal and dual solutions),
 
   485     /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
 
   486     /// and infinite upper bound. It means that the objective function
 
   487     /// is unbounded on that arc, however, note that it could actually be
 
   488     /// bounded over the feasible flows, but this algroithm cannot handle
 
   492     /// \see resetParams(), reset()
 
   493     ProblemType run(int factor = 4) {
 
   495       ProblemType pt = init();
 
   496       if (pt != OPTIMAL) return pt;
 
   500     /// \brief Reset all the parameters that have been given before.
 
   502     /// This function resets all the paramaters that have been given
 
   503     /// before using functions \ref lowerMap(), \ref upperMap(),
 
   504     /// \ref costMap(), \ref supplyMap(), \ref stSupply().
 
   506     /// It is useful for multiple \ref run() calls. Basically, all the given
 
   507     /// parameters are kept for the next \ref run() call, unless
 
   508     /// \ref resetParams() or \ref reset() is used.
 
   509     /// If the underlying digraph was also modified after the construction
 
   510     /// of the class or the last \ref reset() call, then the \ref reset()
 
   511     /// function must be used, otherwise \ref resetParams() is sufficient.
 
   515     ///   CapacityScaling<ListDigraph> cs(graph);
 
   518     ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
 
   519     ///     .supplyMap(sup).run();
 
   521     ///   // Run again with modified cost map (resetParams() is not called,
 
   522     ///   // so only the cost map have to be set again)
 
   524     ///   cs.costMap(cost).run();
 
   526     ///   // Run again from scratch using resetParams()
 
   527     ///   // (the lower bounds will be set to zero on all arcs)
 
   528     ///   cs.resetParams();
 
   529     ///   cs.upperMap(capacity).costMap(cost)
 
   530     ///     .supplyMap(sup).run();
 
   533     /// \return <tt>(*this)</tt>
 
   535     /// \see reset(), run()
 
   536     CapacityScaling& resetParams() {
 
   537       for (int i = 0; i != _node_num; ++i) {
 
   540       for (int j = 0; j != _res_arc_num; ++j) {
 
   543         _cost[j] = _forward[j] ? 1 : -1;
 
   549     /// \brief Reset the internal data structures and all the parameters
 
   550     /// that have been given before.
 
   552     /// This function resets the internal data structures and all the
 
   553     /// paramaters that have been given before using functions \ref lowerMap(),
 
   554     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
 
   556     /// It is useful for multiple \ref run() calls. Basically, all the given
 
   557     /// parameters are kept for the next \ref run() call, unless
 
   558     /// \ref resetParams() or \ref reset() is used.
 
   559     /// If the underlying digraph was also modified after the construction
 
   560     /// of the class or the last \ref reset() call, then the \ref reset()
 
   561     /// function must be used, otherwise \ref resetParams() is sufficient.
 
   563     /// See \ref resetParams() for examples.
 
   565     /// \return <tt>(*this)</tt>
 
   567     /// \see resetParams(), run()
 
   568     CapacityScaling& reset() {
 
   570       _node_num = countNodes(_graph);
 
   571       _arc_num = countArcs(_graph);
 
   572       _res_arc_num = 2 * (_arc_num + _node_num);
 
   576       _first_out.resize(_node_num + 1);
 
   577       _forward.resize(_res_arc_num);
 
   578       _source.resize(_res_arc_num);
 
   579       _target.resize(_res_arc_num);
 
   580       _reverse.resize(_res_arc_num);
 
   582       _lower.resize(_res_arc_num);
 
   583       _upper.resize(_res_arc_num);
 
   584       _cost.resize(_res_arc_num);
 
   585       _supply.resize(_node_num);
 
   587       _res_cap.resize(_res_arc_num);
 
   588       _pi.resize(_node_num);
 
   589       _excess.resize(_node_num);
 
   590       _pred.resize(_node_num);
 
   593       int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
 
   594       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
 
   598       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
 
   600         for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
 
   604           _target[j] = _node_id[_graph.runningNode(a)];
 
   606         for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
 
   610           _target[j] = _node_id[_graph.runningNode(a)];
 
   623       _first_out[_node_num] = k;
 
   624       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   625         int fi = _arc_idf[a];
 
   626         int bi = _arc_idb[a];
 
   638     /// \name Query Functions
 
   639     /// The results of the algorithm can be obtained using these
 
   641     /// The \ref run() function must be called before using them.
 
   645     /// \brief Return the total cost of the found flow.
 
   647     /// This function returns the total cost of the found flow.
 
   648     /// Its complexity is O(m).
 
   650     /// \note The return type of the function can be specified as a
 
   651     /// template parameter. For example,
 
   653     ///   cs.totalCost<double>();
 
   655     /// It is useful if the total cost cannot be stored in the \c Cost
 
   656     /// type of the algorithm, which is the default return type of the
 
   659     /// \pre \ref run() must be called before using this function.
 
   660     template <typename Number>
 
   661     Number totalCost() const {
 
   663       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   665         c += static_cast<Number>(_res_cap[i]) *
 
   666              (-static_cast<Number>(_cost[i]));
 
   672     Cost totalCost() const {
 
   673       return totalCost<Cost>();
 
   677     /// \brief Return the flow on the given arc.
 
   679     /// This function returns the flow on the given arc.
 
   681     /// \pre \ref run() must be called before using this function.
 
   682     Value flow(const Arc& a) const {
 
   683       return _res_cap[_arc_idb[a]];
 
   686     /// \brief Copy the flow values (the primal solution) into the
 
   689     /// This function copies the flow value on each arc into the given
 
   690     /// map. The \c Value type of the algorithm must be convertible to
 
   691     /// the \c Value type of the map.
 
   693     /// \pre \ref run() must be called before using this function.
 
   694     template <typename FlowMap>
 
   695     void flowMap(FlowMap &map) const {
 
   696       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   697         map.set(a, _res_cap[_arc_idb[a]]);
 
   701     /// \brief Return the potential (dual value) of the given node.
 
   703     /// This function returns the potential (dual value) of the
 
   706     /// \pre \ref run() must be called before using this function.
 
   707     Cost potential(const Node& n) const {
 
   708       return _pi[_node_id[n]];
 
   711     /// \brief Copy the potential values (the dual solution) into the
 
   714     /// This function copies the potential (dual value) of each node
 
   715     /// into the given map.
 
   716     /// The \c Cost type of the algorithm must be convertible to the
 
   717     /// \c Value type of the map.
 
   719     /// \pre \ref run() must be called before using this function.
 
   720     template <typename PotentialMap>
 
   721     void potentialMap(PotentialMap &map) const {
 
   722       for (NodeIt n(_graph); n != INVALID; ++n) {
 
   723         map.set(n, _pi[_node_id[n]]);
 
   731     // Initialize the algorithm
 
   733       if (_node_num <= 1) return INFEASIBLE;
 
   735       // Check the sum of supply values
 
   737       for (int i = 0; i != _root; ++i) {
 
   738         _sum_supply += _supply[i];
 
   740       if (_sum_supply > 0) return INFEASIBLE;
 
   742       // Check lower and upper bounds
 
   743       LEMON_DEBUG(checkBoundMaps(),
 
   744           "Upper bounds must be greater or equal to the lower bounds");
 
   747       // Initialize vectors
 
   748       for (int i = 0; i != _root; ++i) {
 
   750         _excess[i] = _supply[i];
 
   753       // Remove non-zero lower bounds
 
   754       const Value MAX = std::numeric_limits<Value>::max();
 
   757         for (int i = 0; i != _root; ++i) {
 
   758           last_out = _first_out[i+1];
 
   759           for (int j = _first_out[i]; j != last_out; ++j) {
 
   763                 _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
 
   765                 _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
 
   768               _excess[_target[j]] += c;
 
   775         for (int j = 0; j != _res_arc_num; ++j) {
 
   776           _res_cap[j] = _forward[j] ? _upper[j] : 0;
 
   780       // Handle negative costs
 
   781       for (int i = 0; i != _root; ++i) {
 
   782         last_out = _first_out[i+1] - 1;
 
   783         for (int j = _first_out[i]; j != last_out; ++j) {
 
   784           Value rc = _res_cap[j];
 
   785           if (_cost[j] < 0 && rc > 0) {
 
   786             if (rc >= MAX) return UNBOUNDED;
 
   788             _excess[_target[j]] += rc;
 
   790             _res_cap[_reverse[j]] += rc;
 
   795       // Handle GEQ supply type
 
   796       if (_sum_supply < 0) {
 
   798         _excess[_root] = -_sum_supply;
 
   799         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
 
   800           int ra = _reverse[a];
 
   801           _res_cap[a] = -_sum_supply + 1;
 
   809         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
 
   810           int ra = _reverse[a];
 
   818       // Initialize delta value
 
   821         Value max_sup = 0, max_dem = 0, max_cap = 0;
 
   822         for (int i = 0; i != _root; ++i) {
 
   823           Value ex = _excess[i];
 
   824           if ( ex > max_sup) max_sup =  ex;
 
   825           if (-ex > max_dem) max_dem = -ex;
 
   826           int last_out = _first_out[i+1] - 1;
 
   827           for (int j = _first_out[i]; j != last_out; ++j) {
 
   828             if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
 
   831         max_sup = std::min(std::min(max_sup, max_dem), max_cap);
 
   832         for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
 
   841     // Check if the upper bound is greater than or equal to the lower bound
 
   842     // on each forward arc.
 
   843     bool checkBoundMaps() {
 
   844       for (int j = 0; j != _res_arc_num; ++j) {
 
   845         if (_forward[j] && _upper[j] < _lower[j]) return false;
 
   850     ProblemType start() {
 
   851       // Execute the algorithm
 
   854         pt = startWithScaling();
 
   856         pt = startWithoutScaling();
 
   858       // Handle non-zero lower bounds
 
   860         int limit = _first_out[_root];
 
   861         for (int j = 0; j != limit; ++j) {
 
   862           if (_forward[j]) _res_cap[_reverse[j]] += _lower[j];
 
   866       // Shift potentials if necessary
 
   867       Cost pr = _pi[_root];
 
   868       if (_sum_supply < 0 || pr > 0) {
 
   869         for (int i = 0; i != _node_num; ++i) {
 
   877     // Execute the capacity scaling algorithm
 
   878     ProblemType startWithScaling() {
 
   879       // Perform capacity scaling phases
 
   881       ResidualDijkstra _dijkstra(*this);
 
   883         // Saturate all arcs not satisfying the optimality condition
 
   885         for (int u = 0; u != _node_num; ++u) {
 
   886           last_out = _sum_supply < 0 ?
 
   887             _first_out[u+1] : _first_out[u+1] - 1;
 
   888           for (int a = _first_out[u]; a != last_out; ++a) {
 
   890             Cost c = _cost[a] + _pi[u] - _pi[v];
 
   891             Value rc = _res_cap[a];
 
   892             if (c < 0 && rc >= _delta) {
 
   896               _res_cap[_reverse[a]] += rc;
 
   901         // Find excess nodes and deficit nodes
 
   902         _excess_nodes.clear();
 
   903         _deficit_nodes.clear();
 
   904         for (int u = 0; u != _node_num; ++u) {
 
   905           Value ex = _excess[u];
 
   906           if (ex >=  _delta) _excess_nodes.push_back(u);
 
   907           if (ex <= -_delta) _deficit_nodes.push_back(u);
 
   909         int next_node = 0, next_def_node = 0;
 
   911         // Find augmenting shortest paths
 
   912         while (next_node < int(_excess_nodes.size())) {
 
   913           // Check deficit nodes
 
   915             bool delta_deficit = false;
 
   916             for ( ; next_def_node < int(_deficit_nodes.size());
 
   918               if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
 
   919                 delta_deficit = true;
 
   923             if (!delta_deficit) break;
 
   926           // Run Dijkstra in the residual network
 
   927           s = _excess_nodes[next_node];
 
   928           if ((t = _dijkstra.run(s, _delta)) == -1) {
 
   936           // Augment along a shortest path from s to t
 
   937           Value d = std::min(_excess[s], -_excess[t]);
 
   941             while ((a = _pred[u]) != -1) {
 
   942               if (_res_cap[a] < d) d = _res_cap[a];
 
   947           while ((a = _pred[u]) != -1) {
 
   949             _res_cap[_reverse[a]] += d;
 
   955           if (_excess[s] < _delta) ++next_node;
 
   958         if (_delta == 1) break;
 
   959         _delta = _delta <= _factor ? 1 : _delta / _factor;
 
   965     // Execute the successive shortest path algorithm
 
   966     ProblemType startWithoutScaling() {
 
   968       _excess_nodes.clear();
 
   969       for (int i = 0; i != _node_num; ++i) {
 
   970         if (_excess[i] > 0) _excess_nodes.push_back(i);
 
   972       if (_excess_nodes.size() == 0) return OPTIMAL;
 
   975       // Find shortest paths
 
   977       ResidualDijkstra _dijkstra(*this);
 
   978       while ( _excess[_excess_nodes[next_node]] > 0 ||
 
   979               ++next_node < int(_excess_nodes.size()) )
 
   981         // Run Dijkstra in the residual network
 
   982         s = _excess_nodes[next_node];
 
   983         if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
 
   985         // Augment along a shortest path from s to t
 
   986         Value d = std::min(_excess[s], -_excess[t]);
 
   990           while ((a = _pred[u]) != -1) {
 
   991             if (_res_cap[a] < d) d = _res_cap[a];
 
   996         while ((a = _pred[u]) != -1) {
 
   998           _res_cap[_reverse[a]] += d;
 
  1008   }; //class CapacityScaling
 
  1014 #endif //LEMON_CAPACITY_SCALING_H