COIN-OR::LEMON - Graph Library

source: lemon/lemon/capacity_scaling.h @ 1298:a78e5b779b69

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

Merge bugfix #478

File size: 31.7 KB
RevLine 
[956]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
[871]2 *
[956]3 * This file is a part of LEMON, a generic C++ optimization library.
[871]4 *
[1270]5 * Copyright (C) 2003-2013
[871]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
[1221]69  /// \ref min_cost_flow "minimum cost flow" \cite amo93networkflows,
70  /// \cite edmondskarp72theoretical. It is an efficient dual
[1217]71  /// solution method, which runs in polynomial time
[1254]72  /// \f$O(m\log U (n+m)\log n)\f$, where <i>U</i> denotes the maximum
[1217]73  /// of node supply and arc capacity values.
[871]74  ///
[1165]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  ///
[872]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.
[871]84  ///
[872]85  /// \tparam GR The digraph type the algorithm runs on.
[878]86  /// \tparam V The number type used for flow amounts, capacity bounds
[891]87  /// and supply values in the algorithm. By default, it is \c int.
[878]88  /// \tparam C The number type used for costs and potentials in the
[891]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.
[871]95  ///
[1025]96  /// \warning Both \c V and \c C must be signed number types.
[1137]97  /// \warning Capacity bounds and supply values must be integer, but
98  /// arc costs can be arbitrary real numbers.
[1023]99  /// \warning This algorithm does not support negative costs for
100  /// arcs having infinite upper bound.
[873]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
[871]107  class CapacityScaling
108  {
[872]109  public:
[871]110
[873]111    /// The type of the digraph
112    typedef typename TR::Digraph Digraph;
[872]113    /// The type of the flow amounts, capacity bounds and supply values
[873]114    typedef typename TR::Value Value;
[872]115    /// The type of the arc costs
[873]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
[1250]121    /// \brief The \ref lemon::CapacityScalingDefaultTraits "traits class"
122    /// of the algorithm
[873]123    typedef TR Traits;
[871]124
125  public:
126
[872]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
[878]140      /// on that arc, however, note that it could actually be bounded
[872]141      /// over the feasible flows, but this algroithm cannot handle
142      /// these cases.
143      UNBOUNDED
144    };
[956]145
[872]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;
[910]153    typedef std::vector<char> BoolVector;
154    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
[871]155
156  private:
157
[872]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
[1297]166    bool _has_lower;
[872]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;
[876]192    int _factor;
[872]193    IntVector _pred;
194
195  public:
[956]196
[872]197    /// \brief Constant for infinite upper bounds (capacities).
[871]198    ///
[872]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.
[871]210    class ResidualDijkstra
211    {
212    private:
213
[872]214      int _node_num;
[877]215      bool _geq;
[872]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;
[956]223
[872]224      IntVector _proc_nodes;
225      CostVector _dist;
[956]226
[871]227    public:
228
[872]229      ResidualDijkstra(CapacityScaling& cs) :
[877]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)
[871]234      {}
235
[872]236      int run(int s, Value delta = 1) {
[873]237        RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
[871]238        Heap heap(heap_cross_ref);
239        heap.push(s, 0);
[872]240        _pred[s] = -1;
[871]241        _proc_nodes.clear();
242
[872]243        // Process nodes
[871]244        while (!heap.empty() && _excess[heap.top()] > -delta) {
[872]245          int u = heap.top(), v;
246          Cost d = heap.prio() + _pi[u], dn;
[871]247          _dist[u] = heap.prio();
[872]248          _proc_nodes.push_back(u);
[871]249          heap.pop();
250
[872]251          // Traverse outgoing residual arcs
[877]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) {
[872]254            if (_res_cap[a] < delta) continue;
255            v = _target[a];
256            switch (heap.state(v)) {
[871]257              case Heap::PRE_HEAP:
[872]258                heap.push(v, d + _cost[a] - _pi[v]);
259                _pred[v] = a;
[871]260                break;
261              case Heap::IN_HEAP:
[872]262                dn = d + _cost[a] - _pi[v];
263                if (dn < heap[v]) {
264                  heap.decrease(v, dn);
265                  _pred[v] = a;
[871]266                }
267                break;
268              case Heap::POST_HEAP:
269                break;
270            }
271          }
272        }
[872]273        if (heap.empty()) return -1;
[871]274
[872]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        }
[871]281
282        return t;
283      }
284
285    }; //class ResidualDijkstra
286
287  public:
288
[873]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
[941]313  protected:
314
315    CapacityScaling() {}
316
[873]317  public:
318
[872]319    /// \brief Constructor.
[871]320    ///
[872]321    /// The constructor of the class.
[871]322    ///
[872]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())
[871]329    {
[878]330      // Check the number types
[872]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
[898]336      // Reset data structures
[872]337      reset();
[871]338    }
339
[872]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.
[871]347    ///
[872]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.
[871]351    ///
[872]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) {
[1297]359      _has_lower = true;
[872]360      for (ArcIt a(_graph); a != INVALID; ++a) {
361        _lower[_arc_idf[a]] = map[a];
[871]362      }
363      return *this;
364    }
365
[872]366    /// \brief Set the upper bounds (capacities) on the arcs.
[871]367    ///
[872]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
[878]371    /// unbounded from above).
[871]372    ///
[872]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];
[871]382      }
383      return *this;
384    }
385
[872]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()
[1023]433    /// with a map in which \c k is assigned to \c s, \c -k is
[872]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    }
[956]450
[872]451    /// @}
452
[871]453    /// \name Execution control
[873]454    /// The algorithm can be executed using \ref run().
[871]455
456    /// @{
457
458    /// \brief Run the algorithm.
459    ///
460    /// This function runs the algorithm.
[872]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    ///
[898]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.
[871]476    ///
[876]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.
[871]480    ///
[872]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
[878]487    /// is unbounded on that arc, however, note that it could actually be
[872]488    /// bounded over the feasible flows, but this algroithm cannot handle
489    /// these cases.
490    ///
491    /// \see ProblemType
[898]492    /// \see resetParams(), reset()
[876]493    ProblemType run(int factor = 4) {
494      _factor = factor;
495      ProblemType pt = init();
[872]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    ///
[898]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.
[872]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    ///
[898]521    ///   // Run again with modified cost map (resetParams() is not called,
[872]522    ///   // so only the cost map have to be set again)
523    ///   cost[e] += 100;
524    ///   cs.costMap(cost).run();
525    ///
[898]526    ///   // Run again from scratch using resetParams()
[872]527    ///   // (the lower bounds will be set to zero on all arcs)
[898]528    ///   cs.resetParams();
[872]529    ///   cs.upperMap(capacity).costMap(cost)
530    ///     .supplyMap(sup).run();
531    /// \endcode
532    ///
533    /// \return <tt>(*this)</tt>
[898]534    ///
535    /// \see reset(), run()
536    CapacityScaling& resetParams() {
[872]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      }
[1297]545      _has_lower = false;
[872]546      return *this;
[871]547    }
548
[898]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);
[956]586
[898]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      }
[956]630
[898]631      // Reset parameters
632      resetParams();
633      return *this;
634    }
635
[871]636    /// @}
637
638    /// \name Query Functions
639    /// The results of the algorithm can be obtained using these
640    /// functions.\n
[872]641    /// The \ref run() function must be called before using them.
[871]642
643    /// @{
644
[872]645    /// \brief Return the total cost of the found flow.
[871]646    ///
[872]647    /// This function returns the total cost of the found flow.
[1254]648    /// Its complexity is O(m).
[872]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.
[871]658    ///
659    /// \pre \ref run() must be called before using this function.
[872]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;
[871]669    }
670
[872]671#ifndef DOXYGEN
672    Cost totalCost() const {
673      return totalCost<Cost>();
[871]674    }
[872]675#endif
[871]676
677    /// \brief Return the flow on the given arc.
678    ///
[872]679    /// This function returns the flow on the given arc.
[871]680    ///
681    /// \pre \ref run() must be called before using this function.
[872]682    Value flow(const Arc& a) const {
683      return _res_cap[_arc_idb[a]];
[871]684    }
685
[1165]686    /// \brief Copy the flow values (the primal solution) into the
687    /// given map.
[871]688    ///
[872]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.
[871]692    ///
693    /// \pre \ref run() must be called before using this function.
[872]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      }
[871]699    }
700
[872]701    /// \brief Return the potential (dual value) of the given node.
[871]702    ///
[872]703    /// This function returns the potential (dual value) of the
704    /// given node.
[871]705    ///
706    /// \pre \ref run() must be called before using this function.
[872]707    Cost potential(const Node& n) const {
708      return _pi[_node_id[n]];
709    }
710
[1165]711    /// \brief Copy the potential values (the dual solution) into the
712    /// given map.
[872]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      }
[871]725    }
726
727    /// @}
728
729  private:
730
[872]731    // Initialize the algorithm
[876]732    ProblemType init() {
[887]733      if (_node_num <= 1) return INFEASIBLE;
[871]734
[872]735      // Check the sum of supply values
736      _sum_supply = 0;
737      for (int i = 0; i != _root; ++i) {
738        _sum_supply += _supply[i];
[871]739      }
[872]740      if (_sum_supply > 0) return INFEASIBLE;
[956]741
[1240]742      // Check lower and upper bounds
743      LEMON_DEBUG(checkBoundMaps(),
744          "Upper bounds must be greater or equal to the lower bounds");
745
746
[877]747      // Initialize vectors
[872]748      for (int i = 0; i != _root; ++i) {
749        _pi[i] = 0;
750        _excess[i] = _supply[i];
[871]751      }
752
[872]753      // Remove non-zero lower bounds
[877]754      const Value MAX = std::numeric_limits<Value>::max();
755      int last_out;
[1297]756      if (_has_lower) {
[872]757        for (int i = 0; i != _root; ++i) {
[877]758          last_out = _first_out[i+1];
759          for (int j = _first_out[i]; j != last_out; ++j) {
[872]760            if (_forward[j]) {
761              Value c = _lower[j];
762              if (c >= 0) {
[877]763                _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
[872]764              } else {
[877]765                _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
[872]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      }
[871]779
[872]780      // Handle negative costs
[877]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;
[872]791          }
792        }
793      }
[956]794
[872]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) {
[877]800          int ra = _reverse[a];
801          _res_cap[a] = -_sum_supply + 1;
802          _res_cap[ra] = 0;
[872]803          _cost[a] = 0;
[877]804          _cost[ra] = 0;
[872]805        }
806      } else {
807        _pi[_root] = 0;
808        _excess[_root] = 0;
809        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
[877]810          int ra = _reverse[a];
[872]811          _res_cap[a] = 1;
[877]812          _res_cap[ra] = 0;
[872]813          _cost[a] = 0;
[877]814          _cost[ra] = 0;
[872]815        }
816      }
817
818      // Initialize delta value
[876]819      if (_factor > 1) {
[871]820        // With scaling
[910]821        Value max_sup = 0, max_dem = 0, max_cap = 0;
822        for (int i = 0; i != _root; ++i) {
[877]823          Value ex = _excess[i];
824          if ( ex > max_sup) max_sup =  ex;
825          if (-ex > max_dem) max_dem = -ex;
[910]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          }
[871]830        }
831        max_sup = std::min(std::min(max_sup, max_dem), max_cap);
[876]832        for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
[871]833      } else {
834        // Without scaling
835        _delta = 1;
836      }
837
[872]838      return OPTIMAL;
[871]839    }
[1270]840
[1296]841    // Check if the upper bound is greater than or equal to the lower bound
842    // on each forward arc.
[1240]843    bool checkBoundMaps() {
844      for (int j = 0; j != _res_arc_num; ++j) {
[1296]845        if (_forward[j] && _upper[j] < _lower[j]) return false;
[1240]846      }
847      return true;
848    }
[871]849
[872]850    ProblemType start() {
851      // Execute the algorithm
852      ProblemType pt;
[871]853      if (_delta > 1)
[872]854        pt = startWithScaling();
[871]855      else
[872]856        pt = startWithoutScaling();
857
858      // Handle non-zero lower bounds
[1297]859      if (_has_lower) {
[877]860        int limit = _first_out[_root];
861        for (int j = 0; j != limit; ++j) {
[1296]862          if (_forward[j]) _res_cap[_reverse[j]] += _lower[j];
[872]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;
[956]871        }
[872]872      }
[956]873
[872]874      return pt;
[871]875    }
876
[872]877    // Execute the capacity scaling algorithm
878    ProblemType startWithScaling() {
[873]879      // Perform capacity scaling phases
[872]880      int s, t;
881      ResidualDijkstra _dijkstra(*this);
[871]882      while (true) {
[872]883        // Saturate all arcs not satisfying the optimality condition
[877]884        int last_out;
[872]885        for (int u = 0; u != _node_num; ++u) {
[877]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) {
[872]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            }
[871]898          }
899        }
900
[872]901        // Find excess nodes and deficit nodes
[871]902        _excess_nodes.clear();
903        _deficit_nodes.clear();
[872]904        for (int u = 0; u != _node_num; ++u) {
[877]905          Value ex = _excess[u];
906          if (ex >=  _delta) _excess_nodes.push_back(u);
907          if (ex <= -_delta) _deficit_nodes.push_back(u);
[871]908        }
909        int next_node = 0, next_def_node = 0;
910
[872]911        // Find augmenting shortest paths
[871]912        while (next_node < int(_excess_nodes.size())) {
[872]913          // Check deficit nodes
[871]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
[872]926          // Run Dijkstra in the residual network
[871]927          s = _excess_nodes[next_node];
[872]928          if ((t = _dijkstra.run(s, _delta)) == -1) {
[871]929            if (_delta > 1) {
930              ++next_node;
931              continue;
932            }
[872]933            return INFEASIBLE;
[871]934          }
935
[872]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;
[871]940          if (d > _delta) {
[872]941            while ((a = _pred[u]) != -1) {
942              if (_res_cap[a] < d) d = _res_cap[a];
943              u = _source[a];
[871]944            }
945          }
946          u = t;
[872]947          while ((a = _pred[u]) != -1) {
948            _res_cap[a] -= d;
949            _res_cap[_reverse[a]] += d;
950            u = _source[a];
[871]951          }
952          _excess[s] -= d;
953          _excess[t] += d;
954
955          if (_excess[s] < _delta) ++next_node;
956        }
957
958        if (_delta == 1) break;
[876]959        _delta = _delta <= _factor ? 1 : _delta / _factor;
[871]960      }
961
[872]962      return OPTIMAL;
[871]963    }
964
[872]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;
[871]973      int next_node = 0;
974
[872]975      // Find shortest paths
976      int s, t;
977      ResidualDijkstra _dijkstra(*this);
[871]978      while ( _excess[_excess_nodes[next_node]] > 0 ||
979              ++next_node < int(_excess_nodes.size()) )
980      {
[872]981        // Run Dijkstra in the residual network
[871]982        s = _excess_nodes[next_node];
[872]983        if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
[871]984
[872]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;
[871]989        if (d > 1) {
[872]990          while ((a = _pred[u]) != -1) {
991            if (_res_cap[a] < d) d = _res_cap[a];
992            u = _source[a];
[871]993          }
994        }
995        u = t;
[872]996        while ((a = _pred[u]) != -1) {
997          _res_cap[a] -= d;
998          _res_cap[_reverse[a]] += d;
999          u = _source[a];
[871]1000        }
1001        _excess[s] -= d;
1002        _excess[t] += d;
1003      }
1004
[872]1005      return OPTIMAL;
[871]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.