lemon/network_simplex.h
author Peter Kovacs <kpeter@inf.elte.hu>
Wed, 29 Apr 2009 03:15:24 +0200
changeset 687 6c408d864fa1
parent 665 b95898314e09
child 688 756a5ec551c8
permissions -rw-r--r--
Support negative costs and bounds in NetworkSimplex (#270)

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