COIN-OR::LEMON - Graph Library

source: lemon/lemon/capacity_scaling.h @ 876:3b53491bf643

Last change on this file since 876:3b53491bf643 was 876:3b53491bf643, checked in by Peter Kovacs <kpeter@…>, 14 years ago

More options for run() in scaling MCF algorithms (#180)

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