COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/capacity_scaling.h @ 1211:a278d16bd2d0

Last change on this file since 1211:a278d16bd2d0 was 1155:9fd86ec2cb81, checked in by Alpar Juttner <alpar@…>, 9 years ago

Merge #600

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