COIN-OR::LEMON - Graph Library

source: lemon/lemon/capacity_scaling.h @ 911:2914b6f0fde0

Last change on this file since 911:2914b6f0fde0 was 911:2914b6f0fde0, checked in by Alpar Juttner <alpar@…>, 14 years ago

Merge #340

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