COIN-OR::LEMON - Graph Library

source: lemon/lemon/network_simplex.h @ 688:756a5ec551c8

Last change on this file since 688:756a5ec551c8 was 688:756a5ec551c8, checked in by Peter Kovacs <kpeter@…>, 15 years ago

Rename Flow to Value in the flow algorithms (#266)

We agreed that using Flow for the value type is misleading, since
a flow should be rather a function on the arcs, not a single value.

This patch reverts the changes of [dacc2cee2b4c] for Preflow and
Circulation.

File size: 47.3 KB
RevLine 
[648]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-2009
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_NETWORK_SIMPLEX_H
20#define LEMON_NETWORK_SIMPLEX_H
21
22/// \ingroup min_cost_flow
23///
24/// \file
[652]25/// \brief Network Simplex algorithm for finding a minimum cost flow.
[648]26
27#include <vector>
28#include <limits>
29#include <algorithm>
30
[650]31#include <lemon/core.h>
[648]32#include <lemon/math.h>
33
34namespace lemon {
35
36  /// \addtogroup min_cost_flow
37  /// @{
38
[652]39  /// \brief Implementation of the primal Network Simplex algorithm
[648]40  /// for finding a \ref min_cost_flow "minimum cost flow".
41  ///
[652]42  /// \ref NetworkSimplex implements the primal Network Simplex algorithm
[648]43  /// for finding a \ref min_cost_flow "minimum cost flow".
[653]44  /// This algorithm is a specialized version of the linear programming
45  /// simplex method directly for the minimum cost flow problem.
46  /// It is one of the most efficient solution methods.
47  ///
48  /// In general this class is the fastest implementation available
49  /// in LEMON for the minimum cost flow problem.
[687]50  /// Moreover it supports both directions of the supply/demand inequality
51  /// constraints. For more information see \ref SupplyType.
52  ///
53  /// Most of the parameters of the problem (except for the digraph)
54  /// can be given using separate functions, and the algorithm can be
55  /// executed using the \ref run() function. If some parameters are not
56  /// specified, then default values will be used.
[648]57  ///
[652]58  /// \tparam GR The digraph type the algorithm runs on.
[688]59  /// \tparam V The value type used for flow amounts, capacity bounds
[654]60  /// and supply values in the algorithm. By default it is \c int.
61  /// \tparam C The value type used for costs and potentials in the
[688]62  /// algorithm. By default it is the same as \c V.
[648]63  ///
[655]64  /// \warning Both value types must be signed and all input data must
65  /// be integer.
[648]66  ///
[652]67  /// \note %NetworkSimplex provides five different pivot rule
[656]68  /// implementations, from which the most efficient one is used
69  /// by default. For more information see \ref PivotRule.
[688]70  template <typename GR, typename V = int, typename C = V>
[648]71  class NetworkSimplex
72  {
[652]73  public:
[648]74
[654]75    /// The flow type of the algorithm
[688]76    typedef V Value;
[654]77    /// The cost type of the algorithm
78    typedef C Cost;
[656]79#ifdef DOXYGEN
80    /// The type of the flow map
[688]81    typedef GR::ArcMap<Value> FlowMap;
[656]82    /// The type of the potential map
83    typedef GR::NodeMap<Cost> PotentialMap;
84#else
[652]85    /// The type of the flow map
[688]86    typedef typename GR::template ArcMap<Value> FlowMap;
[652]87    /// The type of the potential map
[654]88    typedef typename GR::template NodeMap<Cost> PotentialMap;
[656]89#endif
[652]90
91  public:
92
[687]93    /// \brief Problem type constants for the \c run() function.
[652]94    ///
[687]95    /// Enum type containing the problem type constants that can be
96    /// returned by the \ref run() function of the algorithm.
97    enum ProblemType {
98      /// The problem has no feasible solution (flow).
99      INFEASIBLE,
100      /// The problem has optimal solution (i.e. it is feasible and
101      /// bounded), and the algorithm has found optimal flow and node
102      /// potentials (primal and dual solutions).
103      OPTIMAL,
104      /// The objective function of the problem is unbounded, i.e.
105      /// there is a directed cycle having negative total cost and
106      /// infinite upper bound.
107      UNBOUNDED
108    };
109   
110    /// \brief Constants for selecting the type of the supply constraints.
111    ///
112    /// Enum type containing constants for selecting the supply type,
113    /// i.e. the direction of the inequalities in the supply/demand
114    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
115    ///
116    /// The default supply type is \c GEQ, since this form is supported
117    /// by other minimum cost flow algorithms and the \ref Circulation
118    /// algorithm, as well.
119    /// The \c LEQ problem type can be selected using the \ref supplyType()
[652]120    /// function.
121    ///
[687]122    /// Note that the equality form is a special case of both supply types.
123    enum SupplyType {
124
125      /// This option means that there are <em>"greater or equal"</em>
126      /// supply/demand constraints in the definition, i.e. the exact
127      /// formulation of the problem is the following.
128      /**
129          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
130          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
131              sup(u) \quad \forall u\in V \f]
132          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
133      */
134      /// It means that the total demand must be greater or equal to the
135      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
136      /// negative) and all the supplies have to be carried out from
137      /// the supply nodes, but there could be demands that are not
138      /// satisfied.
139      GEQ,
140      /// It is just an alias for the \c GEQ option.
141      CARRY_SUPPLIES = GEQ,
142
143      /// This option means that there are <em>"less or equal"</em>
144      /// supply/demand constraints in the definition, i.e. the exact
145      /// formulation of the problem is the following.
146      /**
147          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
148          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
149              sup(u) \quad \forall u\in V \f]
150          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
151      */
152      /// It means that the total demand must be less or equal to the
153      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
154      /// positive) and all the demands have to be satisfied, but there
155      /// could be supplies that are not carried out from the supply
156      /// nodes.
157      LEQ,
158      /// It is just an alias for the \c LEQ option.
159      SATISFY_DEMANDS = LEQ
160    };
161   
162    /// \brief Constants for selecting the pivot rule.
163    ///
164    /// Enum type containing constants for selecting the pivot rule for
165    /// the \ref run() function.
166    ///
[652]167    /// \ref NetworkSimplex provides five different pivot rule
168    /// implementations that significantly affect the running time
169    /// of the algorithm.
170    /// By default \ref BLOCK_SEARCH "Block Search" is used, which
171    /// proved to be the most efficient and the most robust on various
172    /// test inputs according to our benchmark tests.
173    /// However another pivot rule can be selected using the \ref run()
174    /// function with the proper parameter.
175    enum PivotRule {
176
177      /// The First Eligible pivot rule.
178      /// The next eligible arc is selected in a wraparound fashion
179      /// in every iteration.
180      FIRST_ELIGIBLE,
181
182      /// The Best Eligible pivot rule.
183      /// The best eligible arc is selected in every iteration.
184      BEST_ELIGIBLE,
185
186      /// The Block Search pivot rule.
187      /// A specified number of arcs are examined in every iteration
188      /// in a wraparound fashion and the best eligible arc is selected
189      /// from this block.
190      BLOCK_SEARCH,
191
192      /// The Candidate List pivot rule.
193      /// In a major iteration a candidate list is built from eligible arcs
194      /// in a wraparound fashion and in the following minor iterations
195      /// the best eligible arc is selected from this list.
196      CANDIDATE_LIST,
197
198      /// The Altering Candidate List pivot rule.
199      /// It is a modified version of the Candidate List method.
200      /// It keeps only the several best eligible arcs from the former
201      /// candidate list and extends this list in every iteration.
202      ALTERING_LIST
203    };
[656]204   
[652]205  private:
206
207    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
208
[688]209    typedef typename GR::template ArcMap<Value> ValueArcMap;
[654]210    typedef typename GR::template ArcMap<Cost> CostArcMap;
[688]211    typedef typename GR::template NodeMap<Value> ValueNodeMap;
[648]212
213    typedef std::vector<Arc> ArcVector;
214    typedef std::vector<Node> NodeVector;
215    typedef std::vector<int> IntVector;
216    typedef std::vector<bool> BoolVector;
[688]217    typedef std::vector<Value> FlowVector;
[654]218    typedef std::vector<Cost> CostVector;
[648]219
220    // State constants for arcs
221    enum ArcStateEnum {
222      STATE_UPPER = -1,
223      STATE_TREE  =  0,
224      STATE_LOWER =  1
225    };
226
227  private:
228
[652]229    // Data related to the underlying digraph
230    const GR &_graph;
231    int _node_num;
232    int _arc_num;
233
234    // Parameters of the problem
[688]235    ValueArcMap *_plower;
236    ValueArcMap *_pupper;
[654]237    CostArcMap *_pcost;
[688]238    ValueNodeMap *_psupply;
[652]239    bool _pstsup;
240    Node _psource, _ptarget;
[688]241    Value _pstflow;
[687]242    SupplyType _stype;
243   
[688]244    Value _sum_supply;
[648]245
246    // Result maps
[650]247    FlowMap *_flow_map;
248    PotentialMap *_potential_map;
[648]249    bool _local_flow;
250    bool _local_potential;
251
[652]252    // Data structures for storing the digraph
[650]253    IntNodeMap _node_id;
254    ArcVector _arc_ref;
255    IntVector _source;
256    IntVector _target;
257
[652]258    // Node and arc data
[654]259    FlowVector _cap;
260    CostVector _cost;
261    FlowVector _supply;
262    FlowVector _flow;
263    CostVector _pi;
[648]264
[650]265    // Data for storing the spanning tree structure
[648]266    IntVector _parent;
267    IntVector _pred;
268    IntVector _thread;
[651]269    IntVector _rev_thread;
270    IntVector _succ_num;
271    IntVector _last_succ;
272    IntVector _dirty_revs;
[648]273    BoolVector _forward;
274    IntVector _state;
275    int _root;
276
277    // Temporary data used in the current pivot iteration
[650]278    int in_arc, join, u_in, v_in, u_out, v_out;
279    int first, second, right, last;
[648]280    int stem, par_stem, new_stem;
[688]281    Value delta;
[648]282
[687]283  public:
284 
285    /// \brief Constant for infinite upper bounds (capacities).
286    ///
287    /// Constant for infinite upper bounds (capacities).
[688]288    /// It is \c std::numeric_limits<Value>::infinity() if available,
289    /// \c std::numeric_limits<Value>::max() otherwise.
290    const Value INF;
[687]291
[648]292  private:
293
[652]294    // Implementation of the First Eligible pivot rule
[648]295    class FirstEligiblePivotRule
296    {
297    private:
298
299      // References to the NetworkSimplex class
300      const IntVector  &_source;
301      const IntVector  &_target;
[654]302      const CostVector &_cost;
[648]303      const IntVector  &_state;
[654]304      const CostVector &_pi;
[648]305      int &_in_arc;
306      int _arc_num;
307
308      // Pivot rule data
309      int _next_arc;
310
311    public:
312
[652]313      // Constructor
[648]314      FirstEligiblePivotRule(NetworkSimplex &ns) :
[650]315        _source(ns._source), _target(ns._target),
[648]316        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
[650]317        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
[648]318      {}
319
[652]320      // Find next entering arc
[648]321      bool findEnteringArc() {
[654]322        Cost c;
[648]323        for (int e = _next_arc; e < _arc_num; ++e) {
324          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
325          if (c < 0) {
326            _in_arc = e;
327            _next_arc = e + 1;
328            return true;
329          }
330        }
331        for (int e = 0; e < _next_arc; ++e) {
332          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
333          if (c < 0) {
334            _in_arc = e;
335            _next_arc = e + 1;
336            return true;
337          }
338        }
339        return false;
340      }
341
342    }; //class FirstEligiblePivotRule
343
344
[652]345    // Implementation of the Best Eligible pivot rule
[648]346    class BestEligiblePivotRule
347    {
348    private:
349
350      // References to the NetworkSimplex class
351      const IntVector  &_source;
352      const IntVector  &_target;
[654]353      const CostVector &_cost;
[648]354      const IntVector  &_state;
[654]355      const CostVector &_pi;
[648]356      int &_in_arc;
357      int _arc_num;
358
359    public:
360
[652]361      // Constructor
[648]362      BestEligiblePivotRule(NetworkSimplex &ns) :
[650]363        _source(ns._source), _target(ns._target),
[648]364        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
[650]365        _in_arc(ns.in_arc), _arc_num(ns._arc_num)
[648]366      {}
367
[652]368      // Find next entering arc
[648]369      bool findEnteringArc() {
[654]370        Cost c, min = 0;
[648]371        for (int e = 0; e < _arc_num; ++e) {
372          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
373          if (c < min) {
374            min = c;
375            _in_arc = e;
376          }
377        }
378        return min < 0;
379      }
380
381    }; //class BestEligiblePivotRule
382
383
[652]384    // Implementation of the Block Search pivot rule
[648]385    class BlockSearchPivotRule
386    {
387    private:
388
389      // References to the NetworkSimplex class
390      const IntVector  &_source;
391      const IntVector  &_target;
[654]392      const CostVector &_cost;
[648]393      const IntVector  &_state;
[654]394      const CostVector &_pi;
[648]395      int &_in_arc;
396      int _arc_num;
397
398      // Pivot rule data
399      int _block_size;
400      int _next_arc;
401
402    public:
403
[652]404      // Constructor
[648]405      BlockSearchPivotRule(NetworkSimplex &ns) :
[650]406        _source(ns._source), _target(ns._target),
[648]407        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
[650]408        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
[648]409      {
410        // The main parameters of the pivot rule
411        const double BLOCK_SIZE_FACTOR = 2.0;
412        const int MIN_BLOCK_SIZE = 10;
413
[659]414        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
415                                    std::sqrt(double(_arc_num))),
[648]416                                MIN_BLOCK_SIZE );
417      }
418
[652]419      // Find next entering arc
[648]420      bool findEnteringArc() {
[654]421        Cost c, min = 0;
[648]422        int cnt = _block_size;
423        int e, min_arc = _next_arc;
424        for (e = _next_arc; e < _arc_num; ++e) {
425          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
426          if (c < min) {
427            min = c;
428            min_arc = e;
429          }
430          if (--cnt == 0) {
431            if (min < 0) break;
432            cnt = _block_size;
433          }
434        }
435        if (min == 0 || cnt > 0) {
436          for (e = 0; e < _next_arc; ++e) {
437            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
438            if (c < min) {
439              min = c;
440              min_arc = e;
441            }
442            if (--cnt == 0) {
443              if (min < 0) break;
444              cnt = _block_size;
445            }
446          }
447        }
448        if (min >= 0) return false;
449        _in_arc = min_arc;
450        _next_arc = e;
451        return true;
452      }
453
454    }; //class BlockSearchPivotRule
455
456
[652]457    // Implementation of the Candidate List pivot rule
[648]458    class CandidateListPivotRule
459    {
460    private:
461
462      // References to the NetworkSimplex class
463      const IntVector  &_source;
464      const IntVector  &_target;
[654]465      const CostVector &_cost;
[648]466      const IntVector  &_state;
[654]467      const CostVector &_pi;
[648]468      int &_in_arc;
469      int _arc_num;
470
471      // Pivot rule data
472      IntVector _candidates;
473      int _list_length, _minor_limit;
474      int _curr_length, _minor_count;
475      int _next_arc;
476
477    public:
478
479      /// Constructor
480      CandidateListPivotRule(NetworkSimplex &ns) :
[650]481        _source(ns._source), _target(ns._target),
[648]482        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
[650]483        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
[648]484      {
485        // The main parameters of the pivot rule
486        const double LIST_LENGTH_FACTOR = 1.0;
487        const int MIN_LIST_LENGTH = 10;
488        const double MINOR_LIMIT_FACTOR = 0.1;
489        const int MIN_MINOR_LIMIT = 3;
490
[659]491        _list_length = std::max( int(LIST_LENGTH_FACTOR *
492                                     std::sqrt(double(_arc_num))),
[648]493                                 MIN_LIST_LENGTH );
494        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
495                                 MIN_MINOR_LIMIT );
496        _curr_length = _minor_count = 0;
497        _candidates.resize(_list_length);
498      }
499
500      /// Find next entering arc
501      bool findEnteringArc() {
[654]502        Cost min, c;
[648]503        int e, min_arc = _next_arc;
504        if (_curr_length > 0 && _minor_count < _minor_limit) {
505          // Minor iteration: select the best eligible arc from the
506          // current candidate list
507          ++_minor_count;
508          min = 0;
509          for (int i = 0; i < _curr_length; ++i) {
510            e = _candidates[i];
511            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
512            if (c < min) {
513              min = c;
514              min_arc = e;
515            }
516            if (c >= 0) {
517              _candidates[i--] = _candidates[--_curr_length];
518            }
519          }
520          if (min < 0) {
521            _in_arc = min_arc;
522            return true;
523          }
524        }
525
526        // Major iteration: build a new candidate list
527        min = 0;
528        _curr_length = 0;
529        for (e = _next_arc; e < _arc_num; ++e) {
530          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
531          if (c < 0) {
532            _candidates[_curr_length++] = e;
533            if (c < min) {
534              min = c;
535              min_arc = e;
536            }
537            if (_curr_length == _list_length) break;
538          }
539        }
540        if (_curr_length < _list_length) {
541          for (e = 0; e < _next_arc; ++e) {
542            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
543            if (c < 0) {
544              _candidates[_curr_length++] = e;
545              if (c < min) {
546                min = c;
547                min_arc = e;
548              }
549              if (_curr_length == _list_length) break;
550            }
551          }
552        }
553        if (_curr_length == 0) return false;
554        _minor_count = 1;
555        _in_arc = min_arc;
556        _next_arc = e;
557        return true;
558      }
559
560    }; //class CandidateListPivotRule
561
562
[652]563    // Implementation of the Altering Candidate List pivot rule
[648]564    class AlteringListPivotRule
565    {
566    private:
567
568      // References to the NetworkSimplex class
569      const IntVector  &_source;
570      const IntVector  &_target;
[654]571      const CostVector &_cost;
[648]572      const IntVector  &_state;
[654]573      const CostVector &_pi;
[648]574      int &_in_arc;
575      int _arc_num;
576
577      // Pivot rule data
578      int _block_size, _head_length, _curr_length;
579      int _next_arc;
580      IntVector _candidates;
[654]581      CostVector _cand_cost;
[648]582
583      // Functor class to compare arcs during sort of the candidate list
584      class SortFunc
585      {
586      private:
[654]587        const CostVector &_map;
[648]588      public:
[654]589        SortFunc(const CostVector &map) : _map(map) {}
[648]590        bool operator()(int left, int right) {
591          return _map[left] > _map[right];
592        }
593      };
594
595      SortFunc _sort_func;
596
597    public:
598
[652]599      // Constructor
[648]600      AlteringListPivotRule(NetworkSimplex &ns) :
[650]601        _source(ns._source), _target(ns._target),
[648]602        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
[650]603        _in_arc(ns.in_arc), _arc_num(ns._arc_num),
[648]604        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
605      {
606        // The main parameters of the pivot rule
607        const double BLOCK_SIZE_FACTOR = 1.5;
608        const int MIN_BLOCK_SIZE = 10;
609        const double HEAD_LENGTH_FACTOR = 0.1;
610        const int MIN_HEAD_LENGTH = 3;
611
[659]612        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
613                                    std::sqrt(double(_arc_num))),
[648]614                                MIN_BLOCK_SIZE );
615        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
616                                 MIN_HEAD_LENGTH );
617        _candidates.resize(_head_length + _block_size);
618        _curr_length = 0;
619      }
620
[652]621      // Find next entering arc
[648]622      bool findEnteringArc() {
623        // Check the current candidate list
624        int e;
625        for (int i = 0; i < _curr_length; ++i) {
626          e = _candidates[i];
627          _cand_cost[e] = _state[e] *
628            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
629          if (_cand_cost[e] >= 0) {
630            _candidates[i--] = _candidates[--_curr_length];
631          }
632        }
633
634        // Extend the list
635        int cnt = _block_size;
[650]636        int last_arc = 0;
[648]637        int limit = _head_length;
638
639        for (int e = _next_arc; e < _arc_num; ++e) {
640          _cand_cost[e] = _state[e] *
641            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
642          if (_cand_cost[e] < 0) {
643            _candidates[_curr_length++] = e;
[650]644            last_arc = e;
[648]645          }
646          if (--cnt == 0) {
647            if (_curr_length > limit) break;
648            limit = 0;
649            cnt = _block_size;
650          }
651        }
652        if (_curr_length <= limit) {
653          for (int e = 0; e < _next_arc; ++e) {
654            _cand_cost[e] = _state[e] *
655              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
656            if (_cand_cost[e] < 0) {
657              _candidates[_curr_length++] = e;
[650]658              last_arc = e;
[648]659            }
660            if (--cnt == 0) {
661              if (_curr_length > limit) break;
662              limit = 0;
663              cnt = _block_size;
664            }
665          }
666        }
667        if (_curr_length == 0) return false;
[650]668        _next_arc = last_arc + 1;
[648]669
670        // Make heap of the candidate list (approximating a partial sort)
671        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
672                   _sort_func );
673
674        // Pop the first element of the heap
675        _in_arc = _candidates[0];
676        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
677                  _sort_func );
678        _curr_length = std::min(_head_length, _curr_length - 1);
679        return true;
680      }
681
682    }; //class AlteringListPivotRule
683
684  public:
685
[652]686    /// \brief Constructor.
[648]687    ///
[656]688    /// The constructor of the class.
[648]689    ///
[650]690    /// \param graph The digraph the algorithm runs on.
[652]691    NetworkSimplex(const GR& graph) :
692      _graph(graph),
693      _plower(NULL), _pupper(NULL), _pcost(NULL),
[687]694      _psupply(NULL), _pstsup(false), _stype(GEQ),
[650]695      _flow_map(NULL), _potential_map(NULL),
[648]696      _local_flow(false), _local_potential(false),
[687]697      _node_id(graph),
[688]698      INF(std::numeric_limits<Value>::has_infinity ?
699          std::numeric_limits<Value>::infinity() :
700          std::numeric_limits<Value>::max())
[652]701    {
[687]702      // Check the value types
[688]703      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
[687]704        "The flow type of NetworkSimplex must be signed");
705      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
706        "The cost type of NetworkSimplex must be signed");
[652]707    }
[648]708
709    /// Destructor.
710    ~NetworkSimplex() {
[650]711      if (_local_flow) delete _flow_map;
712      if (_local_potential) delete _potential_map;
[648]713    }
714
[656]715    /// \name Parameters
716    /// The parameters of the algorithm can be specified using these
717    /// functions.
718
719    /// @{
720
[652]721    /// \brief Set the lower bounds on the arcs.
722    ///
723    /// This function sets the lower bounds on the arcs.
[687]724    /// If it is not used before calling \ref run(), the lower bounds
725    /// will be set to zero on all arcs.
[652]726    ///
727    /// \param map An arc map storing the lower bounds.
[688]728    /// Its \c Value type must be convertible to the \c Value type
[652]729    /// of the algorithm.
730    ///
731    /// \return <tt>(*this)</tt>
[687]732    template <typename LowerMap>
733    NetworkSimplex& lowerMap(const LowerMap& map) {
[652]734      delete _plower;
[688]735      _plower = new ValueArcMap(_graph);
[652]736      for (ArcIt a(_graph); a != INVALID; ++a) {
737        (*_plower)[a] = map[a];
738      }
739      return *this;
740    }
741
742    /// \brief Set the upper bounds (capacities) on the arcs.
743    ///
744    /// This function sets the upper bounds (capacities) on the arcs.
[687]745    /// If it is not used before calling \ref run(), the upper bounds
746    /// will be set to \ref INF on all arcs (i.e. the flow value will be
747    /// unbounded from above on each arc).
[652]748    ///
749    /// \param map An arc map storing the upper bounds.
[688]750    /// Its \c Value type must be convertible to the \c Value type
[652]751    /// of the algorithm.
752    ///
753    /// \return <tt>(*this)</tt>
[687]754    template<typename UpperMap>
755    NetworkSimplex& upperMap(const UpperMap& map) {
[652]756      delete _pupper;
[688]757      _pupper = new ValueArcMap(_graph);
[652]758      for (ArcIt a(_graph); a != INVALID; ++a) {
759        (*_pupper)[a] = map[a];
760      }
761      return *this;
762    }
763
764    /// \brief Set the costs of the arcs.
765    ///
766    /// This function sets the costs of the arcs.
767    /// If it is not used before calling \ref run(), the costs
768    /// will be set to \c 1 on all arcs.
769    ///
770    /// \param map An arc map storing the costs.
[654]771    /// Its \c Value type must be convertible to the \c Cost type
[652]772    /// of the algorithm.
773    ///
774    /// \return <tt>(*this)</tt>
[687]775    template<typename CostMap>
776    NetworkSimplex& costMap(const CostMap& map) {
[652]777      delete _pcost;
[654]778      _pcost = new CostArcMap(_graph);
[652]779      for (ArcIt a(_graph); a != INVALID; ++a) {
780        (*_pcost)[a] = map[a];
781      }
782      return *this;
783    }
784
785    /// \brief Set the supply values of the nodes.
786    ///
787    /// This function sets the supply values of the nodes.
788    /// If neither this function nor \ref stSupply() is used before
789    /// calling \ref run(), the supply of each node will be set to zero.
790    /// (It makes sense only if non-zero lower bounds are given.)
791    ///
792    /// \param map A node map storing the supply values.
[688]793    /// Its \c Value type must be convertible to the \c Value type
[652]794    /// of the algorithm.
795    ///
796    /// \return <tt>(*this)</tt>
[687]797    template<typename SupplyMap>
798    NetworkSimplex& supplyMap(const SupplyMap& map) {
[652]799      delete _psupply;
800      _pstsup = false;
[688]801      _psupply = new ValueNodeMap(_graph);
[652]802      for (NodeIt n(_graph); n != INVALID; ++n) {
803        (*_psupply)[n] = map[n];
804      }
805      return *this;
806    }
807
808    /// \brief Set single source and target nodes and a supply value.
809    ///
810    /// This function sets a single source node and a single target node
811    /// and the required flow value.
812    /// If neither this function nor \ref supplyMap() is used before
813    /// calling \ref run(), the supply of each node will be set to zero.
814    /// (It makes sense only if non-zero lower bounds are given.)
815    ///
[687]816    /// Using this function has the same effect as using \ref supplyMap()
817    /// with such a map in which \c k is assigned to \c s, \c -k is
818    /// assigned to \c t and all other nodes have zero supply value.
819    ///
[652]820    /// \param s The source node.
821    /// \param t The target node.
822    /// \param k The required amount of flow from node \c s to node \c t
823    /// (i.e. the supply of \c s and the demand of \c t).
824    ///
825    /// \return <tt>(*this)</tt>
[688]826    NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
[652]827      delete _psupply;
828      _psupply = NULL;
829      _pstsup = true;
830      _psource = s;
831      _ptarget = t;
832      _pstflow = k;
833      return *this;
834    }
[656]835   
[687]836    /// \brief Set the type of the supply constraints.
[656]837    ///
[687]838    /// This function sets the type of the supply/demand constraints.
839    /// If it is not used before calling \ref run(), the \ref GEQ supply
[656]840    /// type will be used.
841    ///
[687]842    /// For more information see \ref SupplyType.
[656]843    ///
844    /// \return <tt>(*this)</tt>
[687]845    NetworkSimplex& supplyType(SupplyType supply_type) {
846      _stype = supply_type;
[656]847      return *this;
848    }
[652]849
[648]850    /// \brief Set the flow map.
851    ///
852    /// This function sets the flow map.
[652]853    /// If it is not used before calling \ref run(), an instance will
854    /// be allocated automatically. The destructor deallocates this
855    /// automatically allocated map, of course.
[648]856    ///
857    /// \return <tt>(*this)</tt>
[652]858    NetworkSimplex& flowMap(FlowMap& map) {
[648]859      if (_local_flow) {
[650]860        delete _flow_map;
[648]861        _local_flow = false;
862      }
[650]863      _flow_map = &map;
[648]864      return *this;
865    }
866
867    /// \brief Set the potential map.
868    ///
[652]869    /// This function sets the potential map, which is used for storing
870    /// the dual solution.
871    /// If it is not used before calling \ref run(), an instance will
872    /// be allocated automatically. The destructor deallocates this
873    /// automatically allocated map, of course.
[648]874    ///
875    /// \return <tt>(*this)</tt>
[652]876    NetworkSimplex& potentialMap(PotentialMap& map) {
[648]877      if (_local_potential) {
[650]878        delete _potential_map;
[648]879        _local_potential = false;
880      }
[650]881      _potential_map = &map;
[648]882      return *this;
883    }
[656]884   
885    /// @}
[648]886
[652]887    /// \name Execution Control
888    /// The algorithm can be executed using \ref run().
889
[648]890    /// @{
891
892    /// \brief Run the algorithm.
893    ///
894    /// This function runs the algorithm.
[656]895    /// The paramters can be specified using functions \ref lowerMap(),
[687]896    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
897    /// \ref supplyType(), \ref flowMap() and \ref potentialMap().
[656]898    /// For example,
[652]899    /// \code
900    ///   NetworkSimplex<ListDigraph> ns(graph);
[687]901    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
[652]902    ///     .supplyMap(sup).run();
903    /// \endcode
[648]904    ///
[653]905    /// This function can be called more than once. All the parameters
906    /// that have been given are kept for the next call, unless
907    /// \ref reset() is called, thus only the modified parameters
908    /// have to be set again. See \ref reset() for examples.
909    ///
[652]910    /// \param pivot_rule The pivot rule that will be used during the
911    /// algorithm. For more information see \ref PivotRule.
[648]912    ///
[687]913    /// \return \c INFEASIBLE if no feasible flow exists,
914    /// \n \c OPTIMAL if the problem has optimal solution
915    /// (i.e. it is feasible and bounded), and the algorithm has found
916    /// optimal flow and node potentials (primal and dual solutions),
917    /// \n \c UNBOUNDED if the objective function of the problem is
918    /// unbounded, i.e. there is a directed cycle having negative total
919    /// cost and infinite upper bound.
920    ///
921    /// \see ProblemType, PivotRule
922    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
923      if (!init()) return INFEASIBLE;
924      return start(pivot_rule);
[648]925    }
926
[653]927    /// \brief Reset all the parameters that have been given before.
928    ///
929    /// This function resets all the paramaters that have been given
[656]930    /// before using functions \ref lowerMap(), \ref upperMap(),
[687]931    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType(),
[656]932    /// \ref flowMap() and \ref potentialMap().
[653]933    ///
934    /// It is useful for multiple run() calls. If this function is not
935    /// used, all the parameters given before are kept for the next
936    /// \ref run() call.
937    ///
938    /// For example,
939    /// \code
940    ///   NetworkSimplex<ListDigraph> ns(graph);
941    ///
942    ///   // First run
[687]943    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
[653]944    ///     .supplyMap(sup).run();
945    ///
946    ///   // Run again with modified cost map (reset() is not called,
947    ///   // so only the cost map have to be set again)
948    ///   cost[e] += 100;
949    ///   ns.costMap(cost).run();
950    ///
951    ///   // Run again from scratch using reset()
952    ///   // (the lower bounds will be set to zero on all arcs)
953    ///   ns.reset();
[687]954    ///   ns.upperMap(capacity).costMap(cost)
[653]955    ///     .supplyMap(sup).run();
956    /// \endcode
957    ///
958    /// \return <tt>(*this)</tt>
959    NetworkSimplex& reset() {
960      delete _plower;
961      delete _pupper;
962      delete _pcost;
963      delete _psupply;
964      _plower = NULL;
965      _pupper = NULL;
966      _pcost = NULL;
967      _psupply = NULL;
968      _pstsup = false;
[687]969      _stype = GEQ;
[656]970      if (_local_flow) delete _flow_map;
971      if (_local_potential) delete _potential_map;
972      _flow_map = NULL;
973      _potential_map = NULL;
974      _local_flow = false;
975      _local_potential = false;
976
[653]977      return *this;
978    }
979
[648]980    /// @}
981
982    /// \name Query Functions
983    /// The results of the algorithm can be obtained using these
984    /// functions.\n
[652]985    /// The \ref run() function must be called before using them.
986
[648]987    /// @{
988
[652]989    /// \brief Return the total cost of the found flow.
990    ///
991    /// This function returns the total cost of the found flow.
[687]992    /// Its complexity is O(e).
[652]993    ///
994    /// \note The return type of the function can be specified as a
995    /// template parameter. For example,
996    /// \code
997    ///   ns.totalCost<double>();
998    /// \endcode
[654]999    /// It is useful if the total cost cannot be stored in the \c Cost
[652]1000    /// type of the algorithm, which is the default return type of the
1001    /// function.
1002    ///
1003    /// \pre \ref run() must be called before using this function.
[687]1004    template <typename Value>
1005    Value totalCost() const {
1006      Value c = 0;
[652]1007      if (_pcost) {
1008        for (ArcIt e(_graph); e != INVALID; ++e)
1009          c += (*_flow_map)[e] * (*_pcost)[e];
1010      } else {
1011        for (ArcIt e(_graph); e != INVALID; ++e)
1012          c += (*_flow_map)[e];
1013      }
1014      return c;
1015    }
1016
1017#ifndef DOXYGEN
[654]1018    Cost totalCost() const {
1019      return totalCost<Cost>();
[652]1020    }
1021#endif
1022
1023    /// \brief Return the flow on the given arc.
1024    ///
1025    /// This function returns the flow on the given arc.
1026    ///
1027    /// \pre \ref run() must be called before using this function.
[688]1028    Value flow(const Arc& a) const {
[652]1029      return (*_flow_map)[a];
1030    }
1031
[648]1032    /// \brief Return a const reference to the flow map.
1033    ///
1034    /// This function returns a const reference to an arc map storing
1035    /// the found flow.
1036    ///
1037    /// \pre \ref run() must be called before using this function.
1038    const FlowMap& flowMap() const {
[650]1039      return *_flow_map;
[648]1040    }
1041
[652]1042    /// \brief Return the potential (dual value) of the given node.
1043    ///
1044    /// This function returns the potential (dual value) of the
1045    /// given node.
1046    ///
1047    /// \pre \ref run() must be called before using this function.
[654]1048    Cost potential(const Node& n) const {
[652]1049      return (*_potential_map)[n];
1050    }
1051
[648]1052    /// \brief Return a const reference to the potential map
1053    /// (the dual solution).
1054    ///
1055    /// This function returns a const reference to a node map storing
[652]1056    /// the found potentials, which form the dual solution of the
[687]1057    /// \ref min_cost_flow "minimum cost flow problem".
[648]1058    ///
1059    /// \pre \ref run() must be called before using this function.
1060    const PotentialMap& potentialMap() const {
[650]1061      return *_potential_map;
[648]1062    }
1063
1064    /// @}
1065
1066  private:
1067
1068    // Initialize internal data structures
1069    bool init() {
1070      // Initialize result maps
[650]1071      if (!_flow_map) {
1072        _flow_map = new FlowMap(_graph);
[648]1073        _local_flow = true;
1074      }
[650]1075      if (!_potential_map) {
1076        _potential_map = new PotentialMap(_graph);
[648]1077        _local_potential = true;
1078      }
1079
1080      // Initialize vectors
[650]1081      _node_num = countNodes(_graph);
1082      _arc_num = countArcs(_graph);
[648]1083      int all_node_num = _node_num + 1;
[650]1084      int all_arc_num = _arc_num + _node_num;
[652]1085      if (_node_num == 0) return false;
[648]1086
[650]1087      _arc_ref.resize(_arc_num);
1088      _source.resize(all_arc_num);
1089      _target.resize(all_arc_num);
[648]1090
[650]1091      _cap.resize(all_arc_num);
1092      _cost.resize(all_arc_num);
[648]1093      _supply.resize(all_node_num);
[653]1094      _flow.resize(all_arc_num);
1095      _pi.resize(all_node_num);
[648]1096
1097      _parent.resize(all_node_num);
1098      _pred.resize(all_node_num);
[650]1099      _forward.resize(all_node_num);
[648]1100      _thread.resize(all_node_num);
[651]1101      _rev_thread.resize(all_node_num);
1102      _succ_num.resize(all_node_num);
1103      _last_succ.resize(all_node_num);
[653]1104      _state.resize(all_arc_num);
[648]1105
1106      // Initialize node related data
1107      bool valid_supply = true;
[687]1108      _sum_supply = 0;
[652]1109      if (!_pstsup && !_psupply) {
1110        _pstsup = true;
1111        _psource = _ptarget = NodeIt(_graph);
1112        _pstflow = 0;
1113      }
1114      if (_psupply) {
[648]1115        int i = 0;
[650]1116        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
[648]1117          _node_id[n] = i;
[652]1118          _supply[i] = (*_psupply)[n];
[687]1119          _sum_supply += _supply[i];
[648]1120        }
[687]1121        valid_supply = (_stype == GEQ && _sum_supply <= 0) ||
1122                       (_stype == LEQ && _sum_supply >= 0);
[648]1123      } else {
1124        int i = 0;
[650]1125        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
[648]1126          _node_id[n] = i;
1127          _supply[i] = 0;
1128        }
[652]1129        _supply[_node_id[_psource]] =  _pstflow;
[656]1130        _supply[_node_id[_ptarget]] = -_pstflow;
[648]1131      }
1132      if (!valid_supply) return false;
1133
[656]1134      // Initialize artifical cost
[687]1135      Cost ART_COST;
[656]1136      if (std::numeric_limits<Cost>::is_exact) {
[687]1137        ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
[656]1138      } else {
[687]1139        ART_COST = std::numeric_limits<Cost>::min();
[656]1140        for (int i = 0; i != _arc_num; ++i) {
[687]1141          if (_cost[i] > ART_COST) ART_COST = _cost[i];
[656]1142        }
[687]1143        ART_COST = (ART_COST + 1) * _node_num;
[656]1144      }
1145
[648]1146      // Set data for the artificial root node
1147      _root = _node_num;
1148      _parent[_root] = -1;
1149      _pred[_root] = -1;
1150      _thread[_root] = 0;
[651]1151      _rev_thread[0] = _root;
1152      _succ_num[_root] = all_node_num;
1153      _last_succ[_root] = _root - 1;
[687]1154      _supply[_root] = -_sum_supply;
1155      if (_sum_supply < 0) {
1156        _pi[_root] = -ART_COST;
[656]1157      } else {
[687]1158        _pi[_root] = ART_COST;
[656]1159      }
[648]1160
1161      // Store the arcs in a mixed order
[659]1162      int k = std::max(int(std::sqrt(double(_arc_num))), 10);
[648]1163      int i = 0;
[650]1164      for (ArcIt e(_graph); e != INVALID; ++e) {
1165        _arc_ref[i] = e;
[648]1166        if ((i += k) >= _arc_num) i = (i % k) + 1;
1167      }
1168
1169      // Initialize arc maps
[652]1170      if (_pupper && _pcost) {
1171        for (int i = 0; i != _arc_num; ++i) {
1172          Arc e = _arc_ref[i];
1173          _source[i] = _node_id[_graph.source(e)];
1174          _target[i] = _node_id[_graph.target(e)];
1175          _cap[i] = (*_pupper)[e];
1176          _cost[i] = (*_pcost)[e];
[653]1177          _flow[i] = 0;
1178          _state[i] = STATE_LOWER;
[652]1179        }
1180      } else {
1181        for (int i = 0; i != _arc_num; ++i) {
1182          Arc e = _arc_ref[i];
1183          _source[i] = _node_id[_graph.source(e)];
1184          _target[i] = _node_id[_graph.target(e)];
[653]1185          _flow[i] = 0;
1186          _state[i] = STATE_LOWER;
[652]1187        }
1188        if (_pupper) {
1189          for (int i = 0; i != _arc_num; ++i)
1190            _cap[i] = (*_pupper)[_arc_ref[i]];
1191        } else {
1192          for (int i = 0; i != _arc_num; ++i)
[687]1193            _cap[i] = INF;
[652]1194        }
1195        if (_pcost) {
1196          for (int i = 0; i != _arc_num; ++i)
1197            _cost[i] = (*_pcost)[_arc_ref[i]];
1198        } else {
1199          for (int i = 0; i != _arc_num; ++i)
1200            _cost[i] = 1;
1201        }
[648]1202      }
[655]1203     
[648]1204      // Remove non-zero lower bounds
[652]1205      if (_plower) {
[648]1206        for (int i = 0; i != _arc_num; ++i) {
[688]1207          Value c = (*_plower)[_arc_ref[i]];
[687]1208          if (c > 0) {
1209            if (_cap[i] < INF) _cap[i] -= c;
1210            _supply[_source[i]] -= c;
1211            _supply[_target[i]] += c;
1212          }
1213          else if (c < 0) {
1214            if (_cap[i] < INF + c) {
1215              _cap[i] -= c;
1216            } else {
1217              _cap[i] = INF;
1218            }
[648]1219            _supply[_source[i]] -= c;
1220            _supply[_target[i]] += c;
1221          }
1222        }
1223      }
1224
1225      // Add artificial arcs and initialize the spanning tree data structure
1226      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1227        _thread[u] = u + 1;
[651]1228        _rev_thread[u + 1] = u;
1229        _succ_num[u] = 1;
1230        _last_succ[u] = u;
[648]1231        _parent[u] = _root;
1232        _pred[u] = e;
[687]1233        _cost[e] = ART_COST;
1234        _cap[e] = INF;
[653]1235        _state[e] = STATE_TREE;
[687]1236        if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
[648]1237          _flow[e] = _supply[u];
1238          _forward[u] = true;
[687]1239          _pi[u] = -ART_COST + _pi[_root];
[648]1240        } else {
1241          _flow[e] = -_supply[u];
1242          _forward[u] = false;
[687]1243          _pi[u] = ART_COST + _pi[_root];
[648]1244        }
1245      }
1246
1247      return true;
1248    }
1249
1250    // Find the join node
1251    void findJoinNode() {
[650]1252      int u = _source[in_arc];
1253      int v = _target[in_arc];
[648]1254      while (u != v) {
[651]1255        if (_succ_num[u] < _succ_num[v]) {
1256          u = _parent[u];
1257        } else {
1258          v = _parent[v];
1259        }
[648]1260      }
1261      join = u;
1262    }
1263
1264    // Find the leaving arc of the cycle and returns true if the
1265    // leaving arc is not the same as the entering arc
1266    bool findLeavingArc() {
1267      // Initialize first and second nodes according to the direction
1268      // of the cycle
[650]1269      if (_state[in_arc] == STATE_LOWER) {
1270        first  = _source[in_arc];
1271        second = _target[in_arc];
[648]1272      } else {
[650]1273        first  = _target[in_arc];
1274        second = _source[in_arc];
[648]1275      }
[650]1276      delta = _cap[in_arc];
[648]1277      int result = 0;
[688]1278      Value d;
[648]1279      int e;
1280
1281      // Search the cycle along the path form the first node to the root
1282      for (int u = first; u != join; u = _parent[u]) {
1283        e = _pred[u];
[687]1284        d = _forward[u] ?
1285          _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
[648]1286        if (d < delta) {
1287          delta = d;
1288          u_out = u;
1289          result = 1;
1290        }
1291      }
1292      // Search the cycle along the path form the second node to the root
1293      for (int u = second; u != join; u = _parent[u]) {
1294        e = _pred[u];
[687]1295        d = _forward[u] ?
1296          (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
[648]1297        if (d <= delta) {
1298          delta = d;
1299          u_out = u;
1300          result = 2;
1301        }
1302      }
1303
1304      if (result == 1) {
1305        u_in = first;
1306        v_in = second;
1307      } else {
1308        u_in = second;
1309        v_in = first;
1310      }
1311      return result != 0;
1312    }
1313
1314    // Change _flow and _state vectors
1315    void changeFlow(bool change) {
1316      // Augment along the cycle
1317      if (delta > 0) {
[688]1318        Value val = _state[in_arc] * delta;
[650]1319        _flow[in_arc] += val;
1320        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
[648]1321          _flow[_pred[u]] += _forward[u] ? -val : val;
1322        }
[650]1323        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
[648]1324          _flow[_pred[u]] += _forward[u] ? val : -val;
1325        }
1326      }
1327      // Update the state of the entering and leaving arcs
1328      if (change) {
[650]1329        _state[in_arc] = STATE_TREE;
[648]1330        _state[_pred[u_out]] =
1331          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1332      } else {
[650]1333        _state[in_arc] = -_state[in_arc];
[648]1334      }
1335    }
1336
[651]1337    // Update the tree structure
1338    void updateTreeStructure() {
1339      int u, w;
1340      int old_rev_thread = _rev_thread[u_out];
1341      int old_succ_num = _succ_num[u_out];
1342      int old_last_succ = _last_succ[u_out];
[648]1343      v_out = _parent[u_out];
1344
[651]1345      u = _last_succ[u_in];  // the last successor of u_in
1346      right = _thread[u];    // the node after it
1347
1348      // Handle the case when old_rev_thread equals to v_in
1349      // (it also means that join and v_out coincide)
1350      if (old_rev_thread == v_in) {
1351        last = _thread[_last_succ[u_out]];
1352      } else {
1353        last = _thread[v_in];
[648]1354      }
1355
[651]1356      // Update _thread and _parent along the stem nodes (i.e. the nodes
1357      // between u_in and u_out, whose parent have to be changed)
[648]1358      _thread[v_in] = stem = u_in;
[651]1359      _dirty_revs.clear();
1360      _dirty_revs.push_back(v_in);
[648]1361      par_stem = v_in;
1362      while (stem != u_out) {
[651]1363        // Insert the next stem node into the thread list
1364        new_stem = _parent[stem];
1365        _thread[u] = new_stem;
1366        _dirty_revs.push_back(u);
[648]1367
[651]1368        // Remove the subtree of stem from the thread list
1369        w = _rev_thread[stem];
1370        _thread[w] = right;
1371        _rev_thread[right] = w;
[648]1372
[651]1373        // Change the parent node and shift stem nodes
[648]1374        _parent[stem] = par_stem;
1375        par_stem = stem;
1376        stem = new_stem;
1377
[651]1378        // Update u and right
1379        u = _last_succ[stem] == _last_succ[par_stem] ?
1380          _rev_thread[par_stem] : _last_succ[stem];
[648]1381        right = _thread[u];
1382      }
1383      _parent[u_out] = par_stem;
1384      _thread[u] = last;
[651]1385      _rev_thread[last] = u;
1386      _last_succ[u_out] = u;
[648]1387
[651]1388      // Remove the subtree of u_out from the thread list except for
1389      // the case when old_rev_thread equals to v_in
1390      // (it also means that join and v_out coincide)
1391      if (old_rev_thread != v_in) {
1392        _thread[old_rev_thread] = right;
1393        _rev_thread[right] = old_rev_thread;
1394      }
1395
1396      // Update _rev_thread using the new _thread values
1397      for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1398        u = _dirty_revs[i];
1399        _rev_thread[_thread[u]] = u;
1400      }
1401
1402      // Update _pred, _forward, _last_succ and _succ_num for the
1403      // stem nodes from u_out to u_in
1404      int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1405      u = u_out;
1406      while (u != u_in) {
1407        w = _parent[u];
1408        _pred[u] = _pred[w];
1409        _forward[u] = !_forward[w];
1410        tmp_sc += _succ_num[u] - _succ_num[w];
1411        _succ_num[u] = tmp_sc;
1412        _last_succ[w] = tmp_ls;
1413        u = w;
1414      }
1415      _pred[u_in] = in_arc;
1416      _forward[u_in] = (u_in == _source[in_arc]);
1417      _succ_num[u_in] = old_succ_num;
1418
1419      // Set limits for updating _last_succ form v_in and v_out
1420      // towards the root
1421      int up_limit_in = -1;
1422      int up_limit_out = -1;
1423      if (_last_succ[join] == v_in) {
1424        up_limit_out = join;
[648]1425      } else {
[651]1426        up_limit_in = join;
1427      }
1428
1429      // Update _last_succ from v_in towards the root
1430      for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1431           u = _parent[u]) {
1432        _last_succ[u] = _last_succ[u_out];
1433      }
1434      // Update _last_succ from v_out towards the root
1435      if (join != old_rev_thread && v_in != old_rev_thread) {
1436        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1437             u = _parent[u]) {
1438          _last_succ[u] = old_rev_thread;
1439        }
1440      } else {
1441        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1442             u = _parent[u]) {
1443          _last_succ[u] = _last_succ[u_out];
1444        }
1445      }
1446
1447      // Update _succ_num from v_in to join
1448      for (u = v_in; u != join; u = _parent[u]) {
1449        _succ_num[u] += old_succ_num;
1450      }
1451      // Update _succ_num from v_out to join
1452      for (u = v_out; u != join; u = _parent[u]) {
1453        _succ_num[u] -= old_succ_num;
[648]1454      }
1455    }
1456
[651]1457    // Update potentials
1458    void updatePotential() {
[654]1459      Cost sigma = _forward[u_in] ?
[648]1460        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1461        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
[655]1462      // Update potentials in the subtree, which has been moved
1463      int end = _thread[_last_succ[u_in]];
1464      for (int u = u_in; u != end; u = _thread[u]) {
1465        _pi[u] += sigma;
[648]1466      }
1467    }
1468
1469    // Execute the algorithm
[687]1470    ProblemType start(PivotRule pivot_rule) {
[648]1471      // Select the pivot rule implementation
1472      switch (pivot_rule) {
[652]1473        case FIRST_ELIGIBLE:
[648]1474          return start<FirstEligiblePivotRule>();
[652]1475        case BEST_ELIGIBLE:
[648]1476          return start<BestEligiblePivotRule>();
[652]1477        case BLOCK_SEARCH:
[648]1478          return start<BlockSearchPivotRule>();
[652]1479        case CANDIDATE_LIST:
[648]1480          return start<CandidateListPivotRule>();
[652]1481        case ALTERING_LIST:
[648]1482          return start<AlteringListPivotRule>();
1483      }
[687]1484      return INFEASIBLE; // avoid warning
[648]1485    }
1486
[652]1487    template <typename PivotRuleImpl>
[687]1488    ProblemType start() {
[652]1489      PivotRuleImpl pivot(*this);
[648]1490
[652]1491      // Execute the Network Simplex algorithm
[648]1492      while (pivot.findEnteringArc()) {
1493        findJoinNode();
1494        bool change = findLeavingArc();
[687]1495        if (delta >= INF) return UNBOUNDED;
[648]1496        changeFlow(change);
1497        if (change) {
[651]1498          updateTreeStructure();
1499          updatePotential();
[648]1500        }
1501      }
[687]1502     
1503      // Check feasibility
1504      if (_sum_supply < 0) {
1505        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1506          if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
1507        }
1508      }
1509      else if (_sum_supply > 0) {
1510        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1511          if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
1512        }
1513      }
1514      else {
1515        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1516          if (_flow[e] != 0) return INFEASIBLE;
1517        }
1518      }
[648]1519
[650]1520      // Copy flow values to _flow_map
[652]1521      if (_plower) {
[648]1522        for (int i = 0; i != _arc_num; ++i) {
[650]1523          Arc e = _arc_ref[i];
[652]1524          _flow_map->set(e, (*_plower)[e] + _flow[i]);
[648]1525        }
1526      } else {
1527        for (int i = 0; i != _arc_num; ++i) {
[650]1528          _flow_map->set(_arc_ref[i], _flow[i]);
[648]1529        }
1530      }
[650]1531      // Copy potential values to _potential_map
1532      for (NodeIt n(_graph); n != INVALID; ++n) {
1533        _potential_map->set(n, _pi[_node_id[n]]);
[648]1534      }
1535
[687]1536      return OPTIMAL;
[648]1537    }
1538
1539  }; //class NetworkSimplex
1540
1541  ///@}
1542
1543} //namespace lemon
1544
1545#endif //LEMON_NETWORK_SIMPLEX_H
Note: See TracBrowser for help on using the repository browser.