COIN-OR::LEMON - Graph Library

source: lemon/lemon/capacity_scaling.h @ 898:75c97c3786d6

Last change on this file since 898:75c97c3786d6 was 898:75c97c3786d6, checked in by Peter Kovacs <kpeter@…>, 14 years ago

Handle graph changes in the MCF algorithms (#327)

The reset() functions are renamed to resetParams() and the new reset()
functions handle the graph chnages, as well.

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