COIN-OR::LEMON - Graph Library

source: lemon/lemon/network_simplex.h @ 910:f3bc4e9b5f3a

Last change on this file since 910:f3bc4e9b5f3a was 910:f3bc4e9b5f3a, checked in by Peter Kovacs <kpeter@…>, 14 years ago

New heuristics for MCF algorithms (#340)
and some implementation improvements.

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