COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/network_simplex.h @ 844:a6eb9698c321

Last change on this file since 844:a6eb9698c321 was 830:75c97c3786d6, checked in by Peter Kovacs <kpeter@…>, 15 years ago

Handle graph changes in the MCF algorithms (#327)

The reset() functions are renamed to resetParams() and the new reset()
functions handle the graph chnages, as well.

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