COIN-OR::LEMON - Graph Library

source: lemon/lemon/capacity_scaling.h @ 910:f3bc4e9b5f3a

Last change on this file since 910:f3bc4e9b5f3a was 910:f3bc4e9b5f3a, checked in by Peter Kovacs <kpeter@…>, 15 years ago

New heuristics for MCF algorithms (#340)
and some implementation improvements.

  • A useful heuristic is added to NetworkSimplex? to make the initial pivots faster.
  • A powerful global update heuristic is added to CostScaling? and the implementation is reworked with various improvements.
  • Better relabeling in CostScaling? to improve numerical stability and make the code faster.
  • A small improvement is made in CapacityScaling? for better delta computation.
  • Add notes to the classes about the usage of vector<char> instead of vector<bool> for efficiency reasons.
File size: 29.3 KB
Line 
1/* -*- C++ -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library
4 *
5 * Copyright (C) 2003-2008
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_CAPACITY_SCALING_H
20#define LEMON_CAPACITY_SCALING_H
21
22/// \ingroup min_cost_flow_algs
23///
24/// \file
25/// \brief Capacity Scaling algorithm for finding a minimum cost flow.
26
27#include <vector>
28#include <limits>
29#include <lemon/core.h>
30#include <lemon/bin_heap.h>
31
32namespace lemon {
33
34  /// \brief Default traits class of CapacityScaling algorithm.
35  ///
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
44  {
45    /// The type of the digraph
46    typedef GR Digraph;
47    /// The type of the flow amounts, capacity bounds and supply values
48    typedef V Value;
49    /// The type of the arc costs
50    typedef C Cost;
51
52    /// \brief The type of the heap used for internal Dijkstra computations.
53    ///
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;
59  };
60
61  /// \addtogroup min_cost_flow_algs
62  /// @{
63
64  /// \brief Implementation of the Capacity Scaling algorithm for
65  /// finding a \ref min_cost_flow "minimum cost flow".
66  ///
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" \ref amo93networkflows,
70  /// \ref edmondskarp72theoretical. It is an efficient dual
71  /// solution method.
72  ///
73  /// Most of the parameters of the problem (except for the digraph)
74  /// can be given using separate functions, and the algorithm can be
75  /// executed using the \ref run() function. If some parameters are not
76  /// specified, then default values will be used.
77  ///
78  /// \tparam GR The digraph type the algorithm runs on.
79  /// \tparam V The number type used for flow amounts, capacity bounds
80  /// and supply values in the algorithm. By default it is \c int.
81  /// \tparam C The number type used for costs and potentials in the
82  /// algorithm. By default it is the same as \c V.
83  ///
84  /// \warning Both number types must be signed and all input data must
85  /// be integer.
86  /// \warning This algorithm does not support negative costs for such
87  /// arcs that have infinite upper bound.
88#ifdef DOXYGEN
89  template <typename GR, typename V, typename C, typename TR>
90#else
91  template < typename GR, typename V = int, typename C = V,
92             typename TR = CapacityScalingDefaultTraits<GR, V, C> >
93#endif
94  class CapacityScaling
95  {
96  public:
97
98    /// The type of the digraph
99    typedef typename TR::Digraph Digraph;
100    /// The type of the flow amounts, capacity bounds and supply values
101    typedef typename TR::Value Value;
102    /// The type of the arc costs
103    typedef typename TR::Cost Cost;
104
105    /// The type of the heap used for internal Dijkstra computations
106    typedef typename TR::Heap Heap;
107
108    /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
109    typedef TR Traits;
110
111  public:
112
113    /// \brief Problem type constants for the \c run() function.
114    ///
115    /// Enum type containing the problem type constants that can be
116    /// returned by the \ref run() function of the algorithm.
117    enum ProblemType {
118      /// The problem has no feasible solution (flow).
119      INFEASIBLE,
120      /// The problem has optimal solution (i.e. it is feasible and
121      /// bounded), and the algorithm has found optimal flow and node
122      /// potentials (primal and dual solutions).
123      OPTIMAL,
124      /// The digraph contains an arc of negative cost and infinite
125      /// upper bound. It means that the objective function is unbounded
126      /// on that arc, however, note that it could actually be bounded
127      /// over the feasible flows, but this algroithm cannot handle
128      /// these cases.
129      UNBOUNDED
130    };
131 
132  private:
133
134    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
135
136    typedef std::vector<int> IntVector;
137    typedef std::vector<Value> ValueVector;
138    typedef std::vector<Cost> CostVector;
139    typedef std::vector<char> BoolVector;
140    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
141
142  private:
143
144    // Data related to the underlying digraph
145    const GR &_graph;
146    int _node_num;
147    int _arc_num;
148    int _res_arc_num;
149    int _root;
150
151    // Parameters of the problem
152    bool _have_lower;
153    Value _sum_supply;
154
155    // Data structures for storing the digraph
156    IntNodeMap _node_id;
157    IntArcMap _arc_idf;
158    IntArcMap _arc_idb;
159    IntVector _first_out;
160    BoolVector _forward;
161    IntVector _source;
162    IntVector _target;
163    IntVector _reverse;
164
165    // Node and arc data
166    ValueVector _lower;
167    ValueVector _upper;
168    CostVector _cost;
169    ValueVector _supply;
170
171    ValueVector _res_cap;
172    CostVector _pi;
173    ValueVector _excess;
174    IntVector _excess_nodes;
175    IntVector _deficit_nodes;
176
177    Value _delta;
178    int _factor;
179    IntVector _pred;
180
181  public:
182 
183    /// \brief Constant for infinite upper bounds (capacities).
184    ///
185    /// Constant for infinite upper bounds (capacities).
186    /// It is \c std::numeric_limits<Value>::infinity() if available,
187    /// \c std::numeric_limits<Value>::max() otherwise.
188    const Value INF;
189
190  private:
191
192    // Special implementation of the Dijkstra algorithm for finding
193    // shortest paths in the residual network of the digraph with
194    // respect to the reduced arc costs and modifying the node
195    // potentials according to the found distance labels.
196    class ResidualDijkstra
197    {
198    private:
199
200      int _node_num;
201      bool _geq;
202      const IntVector &_first_out;
203      const IntVector &_target;
204      const CostVector &_cost;
205      const ValueVector &_res_cap;
206      const ValueVector &_excess;
207      CostVector &_pi;
208      IntVector &_pred;
209     
210      IntVector _proc_nodes;
211      CostVector _dist;
212     
213    public:
214
215      ResidualDijkstra(CapacityScaling& cs) :
216        _node_num(cs._node_num), _geq(cs._sum_supply < 0),
217        _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
218        _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
219        _pred(cs._pred), _dist(cs._node_num)
220      {}
221
222      int run(int s, Value delta = 1) {
223        RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
224        Heap heap(heap_cross_ref);
225        heap.push(s, 0);
226        _pred[s] = -1;
227        _proc_nodes.clear();
228
229        // Process nodes
230        while (!heap.empty() && _excess[heap.top()] > -delta) {
231          int u = heap.top(), v;
232          Cost d = heap.prio() + _pi[u], dn;
233          _dist[u] = heap.prio();
234          _proc_nodes.push_back(u);
235          heap.pop();
236
237          // Traverse outgoing residual arcs
238          int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1;
239          for (int a = _first_out[u]; a != last_out; ++a) {
240            if (_res_cap[a] < delta) continue;
241            v = _target[a];
242            switch (heap.state(v)) {
243              case Heap::PRE_HEAP:
244                heap.push(v, d + _cost[a] - _pi[v]);
245                _pred[v] = a;
246                break;
247              case Heap::IN_HEAP:
248                dn = d + _cost[a] - _pi[v];
249                if (dn < heap[v]) {
250                  heap.decrease(v, dn);
251                  _pred[v] = a;
252                }
253                break;
254              case Heap::POST_HEAP:
255                break;
256            }
257          }
258        }
259        if (heap.empty()) return -1;
260
261        // Update potentials of processed nodes
262        int t = heap.top();
263        Cost dt = heap.prio();
264        for (int i = 0; i < int(_proc_nodes.size()); ++i) {
265          _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
266        }
267
268        return t;
269      }
270
271    }; //class ResidualDijkstra
272
273  public:
274
275    /// \name Named Template Parameters
276    /// @{
277
278    template <typename T>
279    struct SetHeapTraits : public Traits {
280      typedef T Heap;
281    };
282
283    /// \brief \ref named-templ-param "Named parameter" for setting
284    /// \c Heap type.
285    ///
286    /// \ref named-templ-param "Named parameter" for setting \c Heap
287    /// type, which is used for internal Dijkstra computations.
288    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
289    /// its priority type must be \c Cost and its cross reference type
290    /// must be \ref RangeMap "RangeMap<int>".
291    template <typename T>
292    struct SetHeap
293      : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
294      typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
295    };
296
297    /// @}
298
299  public:
300
301    /// \brief Constructor.
302    ///
303    /// The constructor of the class.
304    ///
305    /// \param graph The digraph the algorithm runs on.
306    CapacityScaling(const GR& graph) :
307      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
308      INF(std::numeric_limits<Value>::has_infinity ?
309          std::numeric_limits<Value>::infinity() :
310          std::numeric_limits<Value>::max())
311    {
312      // Check the number types
313      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
314        "The flow type of CapacityScaling must be signed");
315      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
316        "The cost type of CapacityScaling must be signed");
317
318      // Resize vectors
319      _node_num = countNodes(_graph);
320      _arc_num = countArcs(_graph);
321      _res_arc_num = 2 * (_arc_num + _node_num);
322      _root = _node_num;
323      ++_node_num;
324
325      _first_out.resize(_node_num + 1);
326      _forward.resize(_res_arc_num);
327      _source.resize(_res_arc_num);
328      _target.resize(_res_arc_num);
329      _reverse.resize(_res_arc_num);
330
331      _lower.resize(_res_arc_num);
332      _upper.resize(_res_arc_num);
333      _cost.resize(_res_arc_num);
334      _supply.resize(_node_num);
335     
336      _res_cap.resize(_res_arc_num);
337      _pi.resize(_node_num);
338      _excess.resize(_node_num);
339      _pred.resize(_node_num);
340
341      // Copy the graph
342      int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
343      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
344        _node_id[n] = i;
345      }
346      i = 0;
347      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
348        _first_out[i] = j;
349        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
350          _arc_idf[a] = j;
351          _forward[j] = true;
352          _source[j] = i;
353          _target[j] = _node_id[_graph.runningNode(a)];
354        }
355        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
356          _arc_idb[a] = j;
357          _forward[j] = false;
358          _source[j] = i;
359          _target[j] = _node_id[_graph.runningNode(a)];
360        }
361        _forward[j] = false;
362        _source[j] = i;
363        _target[j] = _root;
364        _reverse[j] = k;
365        _forward[k] = true;
366        _source[k] = _root;
367        _target[k] = i;
368        _reverse[k] = j;
369        ++j; ++k;
370      }
371      _first_out[i] = j;
372      _first_out[_node_num] = k;
373      for (ArcIt a(_graph); a != INVALID; ++a) {
374        int fi = _arc_idf[a];
375        int bi = _arc_idb[a];
376        _reverse[fi] = bi;
377        _reverse[bi] = fi;
378      }
379     
380      // Reset parameters
381      reset();
382    }
383
384    /// \name Parameters
385    /// The parameters of the algorithm can be specified using these
386    /// functions.
387
388    /// @{
389
390    /// \brief Set the lower bounds on the arcs.
391    ///
392    /// This function sets the lower bounds on the arcs.
393    /// If it is not used before calling \ref run(), the lower bounds
394    /// will be set to zero on all arcs.
395    ///
396    /// \param map An arc map storing the lower bounds.
397    /// Its \c Value type must be convertible to the \c Value type
398    /// of the algorithm.
399    ///
400    /// \return <tt>(*this)</tt>
401    template <typename LowerMap>
402    CapacityScaling& lowerMap(const LowerMap& map) {
403      _have_lower = true;
404      for (ArcIt a(_graph); a != INVALID; ++a) {
405        _lower[_arc_idf[a]] = map[a];
406        _lower[_arc_idb[a]] = map[a];
407      }
408      return *this;
409    }
410
411    /// \brief Set the upper bounds (capacities) on the arcs.
412    ///
413    /// This function sets the upper bounds (capacities) on the arcs.
414    /// If it is not used before calling \ref run(), the upper bounds
415    /// will be set to \ref INF on all arcs (i.e. the flow value will be
416    /// unbounded from above).
417    ///
418    /// \param map An arc map storing the upper bounds.
419    /// Its \c Value type must be convertible to the \c Value type
420    /// of the algorithm.
421    ///
422    /// \return <tt>(*this)</tt>
423    template<typename UpperMap>
424    CapacityScaling& upperMap(const UpperMap& map) {
425      for (ArcIt a(_graph); a != INVALID; ++a) {
426        _upper[_arc_idf[a]] = map[a];
427      }
428      return *this;
429    }
430
431    /// \brief Set the costs of the arcs.
432    ///
433    /// This function sets the costs of the arcs.
434    /// If it is not used before calling \ref run(), the costs
435    /// will be set to \c 1 on all arcs.
436    ///
437    /// \param map An arc map storing the costs.
438    /// Its \c Value type must be convertible to the \c Cost type
439    /// of the algorithm.
440    ///
441    /// \return <tt>(*this)</tt>
442    template<typename CostMap>
443    CapacityScaling& costMap(const CostMap& map) {
444      for (ArcIt a(_graph); a != INVALID; ++a) {
445        _cost[_arc_idf[a]] =  map[a];
446        _cost[_arc_idb[a]] = -map[a];
447      }
448      return *this;
449    }
450
451    /// \brief Set the supply values of the nodes.
452    ///
453    /// This function sets the supply values of the nodes.
454    /// If neither this function nor \ref stSupply() is used before
455    /// calling \ref run(), the supply of each node will be set to zero.
456    ///
457    /// \param map A node map storing the supply values.
458    /// Its \c Value type must be convertible to the \c Value type
459    /// of the algorithm.
460    ///
461    /// \return <tt>(*this)</tt>
462    template<typename SupplyMap>
463    CapacityScaling& supplyMap(const SupplyMap& map) {
464      for (NodeIt n(_graph); n != INVALID; ++n) {
465        _supply[_node_id[n]] = map[n];
466      }
467      return *this;
468    }
469
470    /// \brief Set single source and target nodes and a supply value.
471    ///
472    /// This function sets a single source node and a single target node
473    /// and the required flow value.
474    /// If neither this function nor \ref supplyMap() is used before
475    /// calling \ref run(), the supply of each node will be set to zero.
476    ///
477    /// Using this function has the same effect as using \ref supplyMap()
478    /// with such a map in which \c k is assigned to \c s, \c -k is
479    /// assigned to \c t and all other nodes have zero supply value.
480    ///
481    /// \param s The source node.
482    /// \param t The target node.
483    /// \param k The required amount of flow from node \c s to node \c t
484    /// (i.e. the supply of \c s and the demand of \c t).
485    ///
486    /// \return <tt>(*this)</tt>
487    CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
488      for (int i = 0; i != _node_num; ++i) {
489        _supply[i] = 0;
490      }
491      _supply[_node_id[s]] =  k;
492      _supply[_node_id[t]] = -k;
493      return *this;
494    }
495   
496    /// @}
497
498    /// \name Execution control
499    /// The algorithm can be executed using \ref run().
500
501    /// @{
502
503    /// \brief Run the algorithm.
504    ///
505    /// This function runs the algorithm.
506    /// The paramters can be specified using functions \ref lowerMap(),
507    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
508    /// For example,
509    /// \code
510    ///   CapacityScaling<ListDigraph> cs(graph);
511    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
512    ///     .supplyMap(sup).run();
513    /// \endcode
514    ///
515    /// This function can be called more than once. All the parameters
516    /// that have been given are kept for the next call, unless
517    /// \ref reset() is called, thus only the modified parameters
518    /// have to be set again. See \ref reset() for examples.
519    /// However, the underlying digraph must not be modified after this
520    /// class have been constructed, since it copies and extends the graph.
521    ///
522    /// \param factor The capacity scaling factor. It must be larger than
523    /// one to use scaling. If it is less or equal to one, then scaling
524    /// will be disabled.
525    ///
526    /// \return \c INFEASIBLE if no feasible flow exists,
527    /// \n \c OPTIMAL if the problem has optimal solution
528    /// (i.e. it is feasible and bounded), and the algorithm has found
529    /// optimal flow and node potentials (primal and dual solutions),
530    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
531    /// and infinite upper bound. It means that the objective function
532    /// is unbounded on that arc, however, note that it could actually be
533    /// bounded over the feasible flows, but this algroithm cannot handle
534    /// these cases.
535    ///
536    /// \see ProblemType
537    ProblemType run(int factor = 4) {
538      _factor = factor;
539      ProblemType pt = init();
540      if (pt != OPTIMAL) return pt;
541      return start();
542    }
543
544    /// \brief Reset all the parameters that have been given before.
545    ///
546    /// This function resets all the paramaters that have been given
547    /// before using functions \ref lowerMap(), \ref upperMap(),
548    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
549    ///
550    /// It is useful for multiple run() calls. If this function is not
551    /// used, all the parameters given before are kept for the next
552    /// \ref run() call.
553    /// However, the underlying digraph must not be modified after this
554    /// class have been constructed, since it copies and extends the graph.
555    ///
556    /// For example,
557    /// \code
558    ///   CapacityScaling<ListDigraph> cs(graph);
559    ///
560    ///   // First run
561    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
562    ///     .supplyMap(sup).run();
563    ///
564    ///   // Run again with modified cost map (reset() is not called,
565    ///   // so only the cost map have to be set again)
566    ///   cost[e] += 100;
567    ///   cs.costMap(cost).run();
568    ///
569    ///   // Run again from scratch using reset()
570    ///   // (the lower bounds will be set to zero on all arcs)
571    ///   cs.reset();
572    ///   cs.upperMap(capacity).costMap(cost)
573    ///     .supplyMap(sup).run();
574    /// \endcode
575    ///
576    /// \return <tt>(*this)</tt>
577    CapacityScaling& reset() {
578      for (int i = 0; i != _node_num; ++i) {
579        _supply[i] = 0;
580      }
581      for (int j = 0; j != _res_arc_num; ++j) {
582        _lower[j] = 0;
583        _upper[j] = INF;
584        _cost[j] = _forward[j] ? 1 : -1;
585      }
586      _have_lower = false;
587      return *this;
588    }
589
590    /// @}
591
592    /// \name Query Functions
593    /// The results of the algorithm can be obtained using these
594    /// functions.\n
595    /// The \ref run() function must be called before using them.
596
597    /// @{
598
599    /// \brief Return the total cost of the found flow.
600    ///
601    /// This function returns the total cost of the found flow.
602    /// Its complexity is O(e).
603    ///
604    /// \note The return type of the function can be specified as a
605    /// template parameter. For example,
606    /// \code
607    ///   cs.totalCost<double>();
608    /// \endcode
609    /// It is useful if the total cost cannot be stored in the \c Cost
610    /// type of the algorithm, which is the default return type of the
611    /// function.
612    ///
613    /// \pre \ref run() must be called before using this function.
614    template <typename Number>
615    Number totalCost() const {
616      Number c = 0;
617      for (ArcIt a(_graph); a != INVALID; ++a) {
618        int i = _arc_idb[a];
619        c += static_cast<Number>(_res_cap[i]) *
620             (-static_cast<Number>(_cost[i]));
621      }
622      return c;
623    }
624
625#ifndef DOXYGEN
626    Cost totalCost() const {
627      return totalCost<Cost>();
628    }
629#endif
630
631    /// \brief Return the flow on the given arc.
632    ///
633    /// This function returns the flow on the given arc.
634    ///
635    /// \pre \ref run() must be called before using this function.
636    Value flow(const Arc& a) const {
637      return _res_cap[_arc_idb[a]];
638    }
639
640    /// \brief Return the flow map (the primal solution).
641    ///
642    /// This function copies the flow value on each arc into the given
643    /// map. The \c Value type of the algorithm must be convertible to
644    /// the \c Value type of the map.
645    ///
646    /// \pre \ref run() must be called before using this function.
647    template <typename FlowMap>
648    void flowMap(FlowMap &map) const {
649      for (ArcIt a(_graph); a != INVALID; ++a) {
650        map.set(a, _res_cap[_arc_idb[a]]);
651      }
652    }
653
654    /// \brief Return the potential (dual value) of the given node.
655    ///
656    /// This function returns the potential (dual value) of the
657    /// given node.
658    ///
659    /// \pre \ref run() must be called before using this function.
660    Cost potential(const Node& n) const {
661      return _pi[_node_id[n]];
662    }
663
664    /// \brief Return the potential map (the dual solution).
665    ///
666    /// This function copies the potential (dual value) of each node
667    /// into the given map.
668    /// The \c Cost type of the algorithm must be convertible to the
669    /// \c Value type of the map.
670    ///
671    /// \pre \ref run() must be called before using this function.
672    template <typename PotentialMap>
673    void potentialMap(PotentialMap &map) const {
674      for (NodeIt n(_graph); n != INVALID; ++n) {
675        map.set(n, _pi[_node_id[n]]);
676      }
677    }
678
679    /// @}
680
681  private:
682
683    // Initialize the algorithm
684    ProblemType init() {
685      if (_node_num <= 1) return INFEASIBLE;
686
687      // Check the sum of supply values
688      _sum_supply = 0;
689      for (int i = 0; i != _root; ++i) {
690        _sum_supply += _supply[i];
691      }
692      if (_sum_supply > 0) return INFEASIBLE;
693     
694      // Initialize vectors
695      for (int i = 0; i != _root; ++i) {
696        _pi[i] = 0;
697        _excess[i] = _supply[i];
698      }
699
700      // Remove non-zero lower bounds
701      const Value MAX = std::numeric_limits<Value>::max();
702      int last_out;
703      if (_have_lower) {
704        for (int i = 0; i != _root; ++i) {
705          last_out = _first_out[i+1];
706          for (int j = _first_out[i]; j != last_out; ++j) {
707            if (_forward[j]) {
708              Value c = _lower[j];
709              if (c >= 0) {
710                _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
711              } else {
712                _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
713              }
714              _excess[i] -= c;
715              _excess[_target[j]] += c;
716            } else {
717              _res_cap[j] = 0;
718            }
719          }
720        }
721      } else {
722        for (int j = 0; j != _res_arc_num; ++j) {
723          _res_cap[j] = _forward[j] ? _upper[j] : 0;
724        }
725      }
726
727      // Handle negative costs
728      for (int i = 0; i != _root; ++i) {
729        last_out = _first_out[i+1] - 1;
730        for (int j = _first_out[i]; j != last_out; ++j) {
731          Value rc = _res_cap[j];
732          if (_cost[j] < 0 && rc > 0) {
733            if (rc >= MAX) return UNBOUNDED;
734            _excess[i] -= rc;
735            _excess[_target[j]] += rc;
736            _res_cap[j] = 0;
737            _res_cap[_reverse[j]] += rc;
738          }
739        }
740      }
741     
742      // Handle GEQ supply type
743      if (_sum_supply < 0) {
744        _pi[_root] = 0;
745        _excess[_root] = -_sum_supply;
746        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
747          int ra = _reverse[a];
748          _res_cap[a] = -_sum_supply + 1;
749          _res_cap[ra] = 0;
750          _cost[a] = 0;
751          _cost[ra] = 0;
752        }
753      } else {
754        _pi[_root] = 0;
755        _excess[_root] = 0;
756        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
757          int ra = _reverse[a];
758          _res_cap[a] = 1;
759          _res_cap[ra] = 0;
760          _cost[a] = 0;
761          _cost[ra] = 0;
762        }
763      }
764
765      // Initialize delta value
766      if (_factor > 1) {
767        // With scaling
768        Value max_sup = 0, max_dem = 0, max_cap = 0;
769        for (int i = 0; i != _root; ++i) {
770          Value ex = _excess[i];
771          if ( ex > max_sup) max_sup =  ex;
772          if (-ex > max_dem) max_dem = -ex;
773          int last_out = _first_out[i+1] - 1;
774          for (int j = _first_out[i]; j != last_out; ++j) {
775            if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
776          }
777        }
778        max_sup = std::min(std::min(max_sup, max_dem), max_cap);
779        for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
780      } else {
781        // Without scaling
782        _delta = 1;
783      }
784
785      return OPTIMAL;
786    }
787
788    ProblemType start() {
789      // Execute the algorithm
790      ProblemType pt;
791      if (_delta > 1)
792        pt = startWithScaling();
793      else
794        pt = startWithoutScaling();
795
796      // Handle non-zero lower bounds
797      if (_have_lower) {
798        int limit = _first_out[_root];
799        for (int j = 0; j != limit; ++j) {
800          if (!_forward[j]) _res_cap[j] += _lower[j];
801        }
802      }
803
804      // Shift potentials if necessary
805      Cost pr = _pi[_root];
806      if (_sum_supply < 0 || pr > 0) {
807        for (int i = 0; i != _node_num; ++i) {
808          _pi[i] -= pr;
809        }       
810      }
811     
812      return pt;
813    }
814
815    // Execute the capacity scaling algorithm
816    ProblemType startWithScaling() {
817      // Perform capacity scaling phases
818      int s, t;
819      ResidualDijkstra _dijkstra(*this);
820      while (true) {
821        // Saturate all arcs not satisfying the optimality condition
822        int last_out;
823        for (int u = 0; u != _node_num; ++u) {
824          last_out = _sum_supply < 0 ?
825            _first_out[u+1] : _first_out[u+1] - 1;
826          for (int a = _first_out[u]; a != last_out; ++a) {
827            int v = _target[a];
828            Cost c = _cost[a] + _pi[u] - _pi[v];
829            Value rc = _res_cap[a];
830            if (c < 0 && rc >= _delta) {
831              _excess[u] -= rc;
832              _excess[v] += rc;
833              _res_cap[a] = 0;
834              _res_cap[_reverse[a]] += rc;
835            }
836          }
837        }
838
839        // Find excess nodes and deficit nodes
840        _excess_nodes.clear();
841        _deficit_nodes.clear();
842        for (int u = 0; u != _node_num; ++u) {
843          Value ex = _excess[u];
844          if (ex >=  _delta) _excess_nodes.push_back(u);
845          if (ex <= -_delta) _deficit_nodes.push_back(u);
846        }
847        int next_node = 0, next_def_node = 0;
848
849        // Find augmenting shortest paths
850        while (next_node < int(_excess_nodes.size())) {
851          // Check deficit nodes
852          if (_delta > 1) {
853            bool delta_deficit = false;
854            for ( ; next_def_node < int(_deficit_nodes.size());
855                    ++next_def_node ) {
856              if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
857                delta_deficit = true;
858                break;
859              }
860            }
861            if (!delta_deficit) break;
862          }
863
864          // Run Dijkstra in the residual network
865          s = _excess_nodes[next_node];
866          if ((t = _dijkstra.run(s, _delta)) == -1) {
867            if (_delta > 1) {
868              ++next_node;
869              continue;
870            }
871            return INFEASIBLE;
872          }
873
874          // Augment along a shortest path from s to t
875          Value d = std::min(_excess[s], -_excess[t]);
876          int u = t;
877          int a;
878          if (d > _delta) {
879            while ((a = _pred[u]) != -1) {
880              if (_res_cap[a] < d) d = _res_cap[a];
881              u = _source[a];
882            }
883          }
884          u = t;
885          while ((a = _pred[u]) != -1) {
886            _res_cap[a] -= d;
887            _res_cap[_reverse[a]] += d;
888            u = _source[a];
889          }
890          _excess[s] -= d;
891          _excess[t] += d;
892
893          if (_excess[s] < _delta) ++next_node;
894        }
895
896        if (_delta == 1) break;
897        _delta = _delta <= _factor ? 1 : _delta / _factor;
898      }
899
900      return OPTIMAL;
901    }
902
903    // Execute the successive shortest path algorithm
904    ProblemType startWithoutScaling() {
905      // Find excess nodes
906      _excess_nodes.clear();
907      for (int i = 0; i != _node_num; ++i) {
908        if (_excess[i] > 0) _excess_nodes.push_back(i);
909      }
910      if (_excess_nodes.size() == 0) return OPTIMAL;
911      int next_node = 0;
912
913      // Find shortest paths
914      int s, t;
915      ResidualDijkstra _dijkstra(*this);
916      while ( _excess[_excess_nodes[next_node]] > 0 ||
917              ++next_node < int(_excess_nodes.size()) )
918      {
919        // Run Dijkstra in the residual network
920        s = _excess_nodes[next_node];
921        if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
922
923        // Augment along a shortest path from s to t
924        Value d = std::min(_excess[s], -_excess[t]);
925        int u = t;
926        int a;
927        if (d > 1) {
928          while ((a = _pred[u]) != -1) {
929            if (_res_cap[a] < d) d = _res_cap[a];
930            u = _source[a];
931          }
932        }
933        u = t;
934        while ((a = _pred[u]) != -1) {
935          _res_cap[a] -= d;
936          _res_cap[_reverse[a]] += d;
937          u = _source[a];
938        }
939        _excess[s] -= d;
940        _excess[t] += d;
941      }
942
943      return OPTIMAL;
944    }
945
946  }; //class CapacityScaling
947
948  ///@}
949
950} //namespace lemon
951
952#endif //LEMON_CAPACITY_SCALING_H
Note: See TracBrowser for help on using the repository browser.