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