COIN-OR::LEMON - Graph Library

source: lemon/lemon/capacity_scaling.h @ 1337:4add05447ca0

Last change on this file since 1337:4add05447ca0 was 1298:a78e5b779b69, checked in by Alpar Juttner <alpar@…>, 10 years ago

Merge bugfix #478

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