lemon/network_simplex.h
author Peter Kovacs <kpeter@inf.elte.hu>
Mon, 23 Mar 2009 23:54:42 +0100
changeset 603 425cc8328c0e
parent 601 e8349c6f12ca
child 604 8c3112a66878
permissions -rw-r--r--
Internal restructuring and renamings in NetworkSimplex (#234)
kpeter@601
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@601
     2
 *
kpeter@601
     3
 * This file is a part of LEMON, a generic C++ optimization library.
kpeter@601
     4
 *
kpeter@601
     5
 * Copyright (C) 2003-2009
kpeter@601
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@601
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@601
     8
 *
kpeter@601
     9
 * Permission to use, modify and distribute this software is granted
kpeter@601
    10
 * provided that this copyright notice appears in all copies. For
kpeter@601
    11
 * precise terms see the accompanying LICENSE file.
kpeter@601
    12
 *
kpeter@601
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@601
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@601
    15
 * purpose.
kpeter@601
    16
 *
kpeter@601
    17
 */
kpeter@601
    18
kpeter@601
    19
#ifndef LEMON_NETWORK_SIMPLEX_H
kpeter@601
    20
#define LEMON_NETWORK_SIMPLEX_H
kpeter@601
    21
kpeter@601
    22
/// \ingroup min_cost_flow
kpeter@601
    23
///
kpeter@601
    24
/// \file
kpeter@601
    25
/// \brief Network simplex algorithm for finding a minimum cost flow.
kpeter@601
    26
kpeter@601
    27
#include <vector>
kpeter@601
    28
#include <limits>
kpeter@601
    29
#include <algorithm>
kpeter@601
    30
kpeter@603
    31
#include <lemon/core.h>
kpeter@601
    32
#include <lemon/math.h>
kpeter@601
    33
kpeter@601
    34
namespace lemon {
kpeter@601
    35
kpeter@601
    36
  /// \addtogroup min_cost_flow
kpeter@601
    37
  /// @{
kpeter@601
    38
kpeter@601
    39
  /// \brief Implementation of the primal network simplex algorithm
kpeter@601
    40
  /// for finding a \ref min_cost_flow "minimum cost flow".
kpeter@601
    41
  ///
kpeter@601
    42
  /// \ref NetworkSimplex implements the primal network simplex algorithm
kpeter@601
    43
  /// for finding a \ref min_cost_flow "minimum cost flow".
kpeter@601
    44
  ///
kpeter@601
    45
  /// \tparam Digraph The digraph type the algorithm runs on.
kpeter@601
    46
  /// \tparam LowerMap The type of the lower bound map.
kpeter@601
    47
  /// \tparam CapacityMap The type of the capacity (upper bound) map.
kpeter@601
    48
  /// \tparam CostMap The type of the cost (length) map.
kpeter@601
    49
  /// \tparam SupplyMap The type of the supply map.
kpeter@601
    50
  ///
kpeter@601
    51
  /// \warning
kpeter@601
    52
  /// - Arc capacities and costs should be \e non-negative \e integers.
kpeter@601
    53
  /// - Supply values should be \e signed \e integers.
kpeter@601
    54
  /// - The value types of the maps should be convertible to each other.
kpeter@601
    55
  /// - \c CostMap::Value must be signed type.
kpeter@601
    56
  ///
kpeter@601
    57
  /// \note \ref NetworkSimplex provides five different pivot rule
kpeter@601
    58
  /// implementations that significantly affect the efficiency of the
kpeter@601
    59
  /// algorithm.
kpeter@601
    60
  /// By default "Block Search" pivot rule is used, which proved to be
kpeter@601
    61
  /// by far the most efficient according to our benchmark tests.
kpeter@601
    62
  /// However another pivot rule can be selected using \ref run()
kpeter@601
    63
  /// function with the proper parameter.
kpeter@601
    64
#ifdef DOXYGEN
kpeter@601
    65
  template < typename Digraph,
kpeter@601
    66
             typename LowerMap,
kpeter@601
    67
             typename CapacityMap,
kpeter@601
    68
             typename CostMap,
kpeter@601
    69
             typename SupplyMap >
kpeter@601
    70
kpeter@601
    71
#else
kpeter@601
    72
  template < typename Digraph,
kpeter@601
    73
             typename LowerMap = typename Digraph::template ArcMap<int>,
kpeter@601
    74
             typename CapacityMap = typename Digraph::template ArcMap<int>,
kpeter@601
    75
             typename CostMap = typename Digraph::template ArcMap<int>,
kpeter@601
    76
             typename SupplyMap = typename Digraph::template NodeMap<int> >
kpeter@601
    77
#endif
kpeter@601
    78
  class NetworkSimplex
kpeter@601
    79
  {
kpeter@601
    80
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
kpeter@601
    81
kpeter@601
    82
    typedef typename CapacityMap::Value Capacity;
kpeter@601
    83
    typedef typename CostMap::Value Cost;
kpeter@601
    84
    typedef typename SupplyMap::Value Supply;
kpeter@601
    85
kpeter@601
    86
    typedef std::vector<Arc> ArcVector;
kpeter@601
    87
    typedef std::vector<Node> NodeVector;
kpeter@601
    88
    typedef std::vector<int> IntVector;
kpeter@601
    89
    typedef std::vector<bool> BoolVector;
kpeter@601
    90
    typedef std::vector<Capacity> CapacityVector;
kpeter@601
    91
    typedef std::vector<Cost> CostVector;
kpeter@601
    92
    typedef std::vector<Supply> SupplyVector;
kpeter@601
    93
kpeter@601
    94
  public:
kpeter@601
    95
kpeter@601
    96
    /// The type of the flow map
kpeter@601
    97
    typedef typename Digraph::template ArcMap<Capacity> FlowMap;
kpeter@601
    98
    /// The type of the potential map
kpeter@601
    99
    typedef typename Digraph::template NodeMap<Cost> PotentialMap;
kpeter@601
   100
kpeter@601
   101
  public:
kpeter@601
   102
kpeter@601
   103
    /// Enum type for selecting the pivot rule used by \ref run()
kpeter@601
   104
    enum PivotRuleEnum {
kpeter@601
   105
      FIRST_ELIGIBLE_PIVOT,
kpeter@601
   106
      BEST_ELIGIBLE_PIVOT,
kpeter@601
   107
      BLOCK_SEARCH_PIVOT,
kpeter@601
   108
      CANDIDATE_LIST_PIVOT,
kpeter@601
   109
      ALTERING_LIST_PIVOT
kpeter@601
   110
    };
kpeter@601
   111
kpeter@601
   112
  private:
kpeter@601
   113
kpeter@601
   114
    // State constants for arcs
kpeter@601
   115
    enum ArcStateEnum {
kpeter@601
   116
      STATE_UPPER = -1,
kpeter@601
   117
      STATE_TREE  =  0,
kpeter@601
   118
      STATE_LOWER =  1
kpeter@601
   119
    };
kpeter@601
   120
kpeter@601
   121
  private:
kpeter@601
   122
kpeter@601
   123
    // References for the original data
kpeter@603
   124
    const Digraph &_graph;
kpeter@601
   125
    const LowerMap *_orig_lower;
kpeter@601
   126
    const CapacityMap &_orig_cap;
kpeter@601
   127
    const CostMap &_orig_cost;
kpeter@601
   128
    const SupplyMap *_orig_supply;
kpeter@601
   129
    Node _orig_source;
kpeter@601
   130
    Node _orig_target;
kpeter@601
   131
    Capacity _orig_flow_value;
kpeter@601
   132
kpeter@601
   133
    // Result maps
kpeter@603
   134
    FlowMap *_flow_map;
kpeter@603
   135
    PotentialMap *_potential_map;
kpeter@601
   136
    bool _local_flow;
kpeter@601
   137
    bool _local_potential;
kpeter@601
   138
kpeter@601
   139
    // The number of nodes and arcs in the original graph
kpeter@601
   140
    int _node_num;
kpeter@601
   141
    int _arc_num;
kpeter@601
   142
kpeter@603
   143
    // Data structures for storing the graph
kpeter@603
   144
    IntNodeMap _node_id;
kpeter@603
   145
    ArcVector _arc_ref;
kpeter@603
   146
    IntVector _source;
kpeter@603
   147
    IntVector _target;
kpeter@603
   148
kpeter@601
   149
    // Node and arc maps
kpeter@601
   150
    CapacityVector _cap;
kpeter@601
   151
    CostVector _cost;
kpeter@601
   152
    CostVector _supply;
kpeter@601
   153
    CapacityVector _flow;
kpeter@601
   154
    CostVector _pi;
kpeter@601
   155
kpeter@603
   156
    // Data for storing the spanning tree structure
kpeter@601
   157
    IntVector _depth;
kpeter@601
   158
    IntVector _parent;
kpeter@601
   159
    IntVector _pred;
kpeter@601
   160
    IntVector _thread;
kpeter@601
   161
    BoolVector _forward;
kpeter@601
   162
    IntVector _state;
kpeter@601
   163
    int _root;
kpeter@601
   164
kpeter@601
   165
    // Temporary data used in the current pivot iteration
kpeter@603
   166
    int in_arc, join, u_in, v_in, u_out, v_out;
kpeter@603
   167
    int first, second, right, last;
kpeter@601
   168
    int stem, par_stem, new_stem;
kpeter@601
   169
    Capacity delta;
kpeter@601
   170
kpeter@601
   171
  private:
kpeter@601
   172
kpeter@601
   173
    /// \brief Implementation of the "First Eligible" pivot rule for the
kpeter@601
   174
    /// \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   175
    ///
kpeter@601
   176
    /// This class implements the "First Eligible" pivot rule
kpeter@601
   177
    /// for the \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   178
    ///
kpeter@601
   179
    /// For more information see \ref NetworkSimplex::run().
kpeter@601
   180
    class FirstEligiblePivotRule
kpeter@601
   181
    {
kpeter@601
   182
    private:
kpeter@601
   183
kpeter@601
   184
      // References to the NetworkSimplex class
kpeter@601
   185
      const IntVector  &_source;
kpeter@601
   186
      const IntVector  &_target;
kpeter@601
   187
      const CostVector &_cost;
kpeter@601
   188
      const IntVector  &_state;
kpeter@601
   189
      const CostVector &_pi;
kpeter@601
   190
      int &_in_arc;
kpeter@601
   191
      int _arc_num;
kpeter@601
   192
kpeter@601
   193
      // Pivot rule data
kpeter@601
   194
      int _next_arc;
kpeter@601
   195
kpeter@601
   196
    public:
kpeter@601
   197
kpeter@601
   198
      /// Constructor
kpeter@601
   199
      FirstEligiblePivotRule(NetworkSimplex &ns) :
kpeter@603
   200
        _source(ns._source), _target(ns._target),
kpeter@601
   201
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603
   202
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
kpeter@601
   203
      {}
kpeter@601
   204
kpeter@601
   205
      /// Find next entering arc
kpeter@601
   206
      bool findEnteringArc() {
kpeter@601
   207
        Cost c;
kpeter@601
   208
        for (int e = _next_arc; e < _arc_num; ++e) {
kpeter@601
   209
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   210
          if (c < 0) {
kpeter@601
   211
            _in_arc = e;
kpeter@601
   212
            _next_arc = e + 1;
kpeter@601
   213
            return true;
kpeter@601
   214
          }
kpeter@601
   215
        }
kpeter@601
   216
        for (int e = 0; e < _next_arc; ++e) {
kpeter@601
   217
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   218
          if (c < 0) {
kpeter@601
   219
            _in_arc = e;
kpeter@601
   220
            _next_arc = e + 1;
kpeter@601
   221
            return true;
kpeter@601
   222
          }
kpeter@601
   223
        }
kpeter@601
   224
        return false;
kpeter@601
   225
      }
kpeter@601
   226
kpeter@601
   227
    }; //class FirstEligiblePivotRule
kpeter@601
   228
kpeter@601
   229
kpeter@601
   230
    /// \brief Implementation of the "Best Eligible" pivot rule for the
kpeter@601
   231
    /// \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   232
    ///
kpeter@601
   233
    /// This class implements the "Best Eligible" pivot rule
kpeter@601
   234
    /// for the \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   235
    ///
kpeter@601
   236
    /// For more information see \ref NetworkSimplex::run().
kpeter@601
   237
    class BestEligiblePivotRule
kpeter@601
   238
    {
kpeter@601
   239
    private:
kpeter@601
   240
kpeter@601
   241
      // References to the NetworkSimplex class
kpeter@601
   242
      const IntVector  &_source;
kpeter@601
   243
      const IntVector  &_target;
kpeter@601
   244
      const CostVector &_cost;
kpeter@601
   245
      const IntVector  &_state;
kpeter@601
   246
      const CostVector &_pi;
kpeter@601
   247
      int &_in_arc;
kpeter@601
   248
      int _arc_num;
kpeter@601
   249
kpeter@601
   250
    public:
kpeter@601
   251
kpeter@601
   252
      /// Constructor
kpeter@601
   253
      BestEligiblePivotRule(NetworkSimplex &ns) :
kpeter@603
   254
        _source(ns._source), _target(ns._target),
kpeter@601
   255
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603
   256
        _in_arc(ns.in_arc), _arc_num(ns._arc_num)
kpeter@601
   257
      {}
kpeter@601
   258
kpeter@601
   259
      /// Find next entering arc
kpeter@601
   260
      bool findEnteringArc() {
kpeter@601
   261
        Cost c, min = 0;
kpeter@601
   262
        for (int e = 0; e < _arc_num; ++e) {
kpeter@601
   263
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   264
          if (c < min) {
kpeter@601
   265
            min = c;
kpeter@601
   266
            _in_arc = e;
kpeter@601
   267
          }
kpeter@601
   268
        }
kpeter@601
   269
        return min < 0;
kpeter@601
   270
      }
kpeter@601
   271
kpeter@601
   272
    }; //class BestEligiblePivotRule
kpeter@601
   273
kpeter@601
   274
kpeter@601
   275
    /// \brief Implementation of the "Block Search" pivot rule for the
kpeter@601
   276
    /// \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   277
    ///
kpeter@601
   278
    /// This class implements the "Block Search" pivot rule
kpeter@601
   279
    /// for the \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   280
    ///
kpeter@601
   281
    /// For more information see \ref NetworkSimplex::run().
kpeter@601
   282
    class BlockSearchPivotRule
kpeter@601
   283
    {
kpeter@601
   284
    private:
kpeter@601
   285
kpeter@601
   286
      // References to the NetworkSimplex class
kpeter@601
   287
      const IntVector  &_source;
kpeter@601
   288
      const IntVector  &_target;
kpeter@601
   289
      const CostVector &_cost;
kpeter@601
   290
      const IntVector  &_state;
kpeter@601
   291
      const CostVector &_pi;
kpeter@601
   292
      int &_in_arc;
kpeter@601
   293
      int _arc_num;
kpeter@601
   294
kpeter@601
   295
      // Pivot rule data
kpeter@601
   296
      int _block_size;
kpeter@601
   297
      int _next_arc;
kpeter@601
   298
kpeter@601
   299
    public:
kpeter@601
   300
kpeter@601
   301
      /// Constructor
kpeter@601
   302
      BlockSearchPivotRule(NetworkSimplex &ns) :
kpeter@603
   303
        _source(ns._source), _target(ns._target),
kpeter@601
   304
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603
   305
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
kpeter@601
   306
      {
kpeter@601
   307
        // The main parameters of the pivot rule
kpeter@601
   308
        const double BLOCK_SIZE_FACTOR = 2.0;
kpeter@601
   309
        const int MIN_BLOCK_SIZE = 10;
kpeter@601
   310
kpeter@601
   311
        _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
kpeter@601
   312
                                MIN_BLOCK_SIZE );
kpeter@601
   313
      }
kpeter@601
   314
kpeter@601
   315
      /// Find next entering arc
kpeter@601
   316
      bool findEnteringArc() {
kpeter@601
   317
        Cost c, min = 0;
kpeter@601
   318
        int cnt = _block_size;
kpeter@601
   319
        int e, min_arc = _next_arc;
kpeter@601
   320
        for (e = _next_arc; e < _arc_num; ++e) {
kpeter@601
   321
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   322
          if (c < min) {
kpeter@601
   323
            min = c;
kpeter@601
   324
            min_arc = e;
kpeter@601
   325
          }
kpeter@601
   326
          if (--cnt == 0) {
kpeter@601
   327
            if (min < 0) break;
kpeter@601
   328
            cnt = _block_size;
kpeter@601
   329
          }
kpeter@601
   330
        }
kpeter@601
   331
        if (min == 0 || cnt > 0) {
kpeter@601
   332
          for (e = 0; e < _next_arc; ++e) {
kpeter@601
   333
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   334
            if (c < min) {
kpeter@601
   335
              min = c;
kpeter@601
   336
              min_arc = e;
kpeter@601
   337
            }
kpeter@601
   338
            if (--cnt == 0) {
kpeter@601
   339
              if (min < 0) break;
kpeter@601
   340
              cnt = _block_size;
kpeter@601
   341
            }
kpeter@601
   342
          }
kpeter@601
   343
        }
kpeter@601
   344
        if (min >= 0) return false;
kpeter@601
   345
        _in_arc = min_arc;
kpeter@601
   346
        _next_arc = e;
kpeter@601
   347
        return true;
kpeter@601
   348
      }
kpeter@601
   349
kpeter@601
   350
    }; //class BlockSearchPivotRule
kpeter@601
   351
kpeter@601
   352
kpeter@601
   353
    /// \brief Implementation of the "Candidate List" pivot rule for the
kpeter@601
   354
    /// \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   355
    ///
kpeter@601
   356
    /// This class implements the "Candidate List" pivot rule
kpeter@601
   357
    /// for the \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   358
    ///
kpeter@601
   359
    /// For more information see \ref NetworkSimplex::run().
kpeter@601
   360
    class CandidateListPivotRule
kpeter@601
   361
    {
kpeter@601
   362
    private:
kpeter@601
   363
kpeter@601
   364
      // References to the NetworkSimplex class
kpeter@601
   365
      const IntVector  &_source;
kpeter@601
   366
      const IntVector  &_target;
kpeter@601
   367
      const CostVector &_cost;
kpeter@601
   368
      const IntVector  &_state;
kpeter@601
   369
      const CostVector &_pi;
kpeter@601
   370
      int &_in_arc;
kpeter@601
   371
      int _arc_num;
kpeter@601
   372
kpeter@601
   373
      // Pivot rule data
kpeter@601
   374
      IntVector _candidates;
kpeter@601
   375
      int _list_length, _minor_limit;
kpeter@601
   376
      int _curr_length, _minor_count;
kpeter@601
   377
      int _next_arc;
kpeter@601
   378
kpeter@601
   379
    public:
kpeter@601
   380
kpeter@601
   381
      /// Constructor
kpeter@601
   382
      CandidateListPivotRule(NetworkSimplex &ns) :
kpeter@603
   383
        _source(ns._source), _target(ns._target),
kpeter@601
   384
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603
   385
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
kpeter@601
   386
      {
kpeter@601
   387
        // The main parameters of the pivot rule
kpeter@601
   388
        const double LIST_LENGTH_FACTOR = 1.0;
kpeter@601
   389
        const int MIN_LIST_LENGTH = 10;
kpeter@601
   390
        const double MINOR_LIMIT_FACTOR = 0.1;
kpeter@601
   391
        const int MIN_MINOR_LIMIT = 3;
kpeter@601
   392
kpeter@601
   393
        _list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_arc_num)),
kpeter@601
   394
                                 MIN_LIST_LENGTH );
kpeter@601
   395
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
kpeter@601
   396
                                 MIN_MINOR_LIMIT );
kpeter@601
   397
        _curr_length = _minor_count = 0;
kpeter@601
   398
        _candidates.resize(_list_length);
kpeter@601
   399
      }
kpeter@601
   400
kpeter@601
   401
      /// Find next entering arc
kpeter@601
   402
      bool findEnteringArc() {
kpeter@601
   403
        Cost min, c;
kpeter@601
   404
        int e, min_arc = _next_arc;
kpeter@601
   405
        if (_curr_length > 0 && _minor_count < _minor_limit) {
kpeter@601
   406
          // Minor iteration: select the best eligible arc from the
kpeter@601
   407
          // current candidate list
kpeter@601
   408
          ++_minor_count;
kpeter@601
   409
          min = 0;
kpeter@601
   410
          for (int i = 0; i < _curr_length; ++i) {
kpeter@601
   411
            e = _candidates[i];
kpeter@601
   412
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   413
            if (c < min) {
kpeter@601
   414
              min = c;
kpeter@601
   415
              min_arc = e;
kpeter@601
   416
            }
kpeter@601
   417
            if (c >= 0) {
kpeter@601
   418
              _candidates[i--] = _candidates[--_curr_length];
kpeter@601
   419
            }
kpeter@601
   420
          }
kpeter@601
   421
          if (min < 0) {
kpeter@601
   422
            _in_arc = min_arc;
kpeter@601
   423
            return true;
kpeter@601
   424
          }
kpeter@601
   425
        }
kpeter@601
   426
kpeter@601
   427
        // Major iteration: build a new candidate list
kpeter@601
   428
        min = 0;
kpeter@601
   429
        _curr_length = 0;
kpeter@601
   430
        for (e = _next_arc; e < _arc_num; ++e) {
kpeter@601
   431
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   432
          if (c < 0) {
kpeter@601
   433
            _candidates[_curr_length++] = e;
kpeter@601
   434
            if (c < min) {
kpeter@601
   435
              min = c;
kpeter@601
   436
              min_arc = e;
kpeter@601
   437
            }
kpeter@601
   438
            if (_curr_length == _list_length) break;
kpeter@601
   439
          }
kpeter@601
   440
        }
kpeter@601
   441
        if (_curr_length < _list_length) {
kpeter@601
   442
          for (e = 0; e < _next_arc; ++e) {
kpeter@601
   443
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   444
            if (c < 0) {
kpeter@601
   445
              _candidates[_curr_length++] = e;
kpeter@601
   446
              if (c < min) {
kpeter@601
   447
                min = c;
kpeter@601
   448
                min_arc = e;
kpeter@601
   449
              }
kpeter@601
   450
              if (_curr_length == _list_length) break;
kpeter@601
   451
            }
kpeter@601
   452
          }
kpeter@601
   453
        }
kpeter@601
   454
        if (_curr_length == 0) return false;
kpeter@601
   455
        _minor_count = 1;
kpeter@601
   456
        _in_arc = min_arc;
kpeter@601
   457
        _next_arc = e;
kpeter@601
   458
        return true;
kpeter@601
   459
      }
kpeter@601
   460
kpeter@601
   461
    }; //class CandidateListPivotRule
kpeter@601
   462
kpeter@601
   463
kpeter@601
   464
    /// \brief Implementation of the "Altering Candidate List" pivot rule
kpeter@601
   465
    /// for the \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   466
    ///
kpeter@601
   467
    /// This class implements the "Altering Candidate List" pivot rule
kpeter@601
   468
    /// for the \ref NetworkSimplex "network simplex" algorithm.
kpeter@601
   469
    ///
kpeter@601
   470
    /// For more information see \ref NetworkSimplex::run().
kpeter@601
   471
    class AlteringListPivotRule
kpeter@601
   472
    {
kpeter@601
   473
    private:
kpeter@601
   474
kpeter@601
   475
      // References to the NetworkSimplex class
kpeter@601
   476
      const IntVector  &_source;
kpeter@601
   477
      const IntVector  &_target;
kpeter@601
   478
      const CostVector &_cost;
kpeter@601
   479
      const IntVector  &_state;
kpeter@601
   480
      const CostVector &_pi;
kpeter@601
   481
      int &_in_arc;
kpeter@601
   482
      int _arc_num;
kpeter@601
   483
kpeter@601
   484
      // Pivot rule data
kpeter@601
   485
      int _block_size, _head_length, _curr_length;
kpeter@601
   486
      int _next_arc;
kpeter@601
   487
      IntVector _candidates;
kpeter@601
   488
      CostVector _cand_cost;
kpeter@601
   489
kpeter@601
   490
      // Functor class to compare arcs during sort of the candidate list
kpeter@601
   491
      class SortFunc
kpeter@601
   492
      {
kpeter@601
   493
      private:
kpeter@601
   494
        const CostVector &_map;
kpeter@601
   495
      public:
kpeter@601
   496
        SortFunc(const CostVector &map) : _map(map) {}
kpeter@601
   497
        bool operator()(int left, int right) {
kpeter@601
   498
          return _map[left] > _map[right];
kpeter@601
   499
        }
kpeter@601
   500
      };
kpeter@601
   501
kpeter@601
   502
      SortFunc _sort_func;
kpeter@601
   503
kpeter@601
   504
    public:
kpeter@601
   505
kpeter@601
   506
      /// Constructor
kpeter@601
   507
      AlteringListPivotRule(NetworkSimplex &ns) :
kpeter@603
   508
        _source(ns._source), _target(ns._target),
kpeter@601
   509
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603
   510
        _in_arc(ns.in_arc), _arc_num(ns._arc_num),
kpeter@601
   511
        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
kpeter@601
   512
      {
kpeter@601
   513
        // The main parameters of the pivot rule
kpeter@601
   514
        const double BLOCK_SIZE_FACTOR = 1.5;
kpeter@601
   515
        const int MIN_BLOCK_SIZE = 10;
kpeter@601
   516
        const double HEAD_LENGTH_FACTOR = 0.1;
kpeter@601
   517
        const int MIN_HEAD_LENGTH = 3;
kpeter@601
   518
kpeter@601
   519
        _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
kpeter@601
   520
                                MIN_BLOCK_SIZE );
kpeter@601
   521
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
kpeter@601
   522
                                 MIN_HEAD_LENGTH );
kpeter@601
   523
        _candidates.resize(_head_length + _block_size);
kpeter@601
   524
        _curr_length = 0;
kpeter@601
   525
      }
kpeter@601
   526
kpeter@601
   527
      /// Find next entering arc
kpeter@601
   528
      bool findEnteringArc() {
kpeter@601
   529
        // Check the current candidate list
kpeter@601
   530
        int e;
kpeter@601
   531
        for (int i = 0; i < _curr_length; ++i) {
kpeter@601
   532
          e = _candidates[i];
kpeter@601
   533
          _cand_cost[e] = _state[e] *
kpeter@601
   534
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   535
          if (_cand_cost[e] >= 0) {
kpeter@601
   536
            _candidates[i--] = _candidates[--_curr_length];
kpeter@601
   537
          }
kpeter@601
   538
        }
kpeter@601
   539
kpeter@601
   540
        // Extend the list
kpeter@601
   541
        int cnt = _block_size;
kpeter@603
   542
        int last_arc = 0;
kpeter@601
   543
        int limit = _head_length;
kpeter@601
   544
kpeter@601
   545
        for (int e = _next_arc; e < _arc_num; ++e) {
kpeter@601
   546
          _cand_cost[e] = _state[e] *
kpeter@601
   547
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   548
          if (_cand_cost[e] < 0) {
kpeter@601
   549
            _candidates[_curr_length++] = e;
kpeter@603
   550
            last_arc = e;
kpeter@601
   551
          }
kpeter@601
   552
          if (--cnt == 0) {
kpeter@601
   553
            if (_curr_length > limit) break;
kpeter@601
   554
            limit = 0;
kpeter@601
   555
            cnt = _block_size;
kpeter@601
   556
          }
kpeter@601
   557
        }
kpeter@601
   558
        if (_curr_length <= limit) {
kpeter@601
   559
          for (int e = 0; e < _next_arc; ++e) {
kpeter@601
   560
            _cand_cost[e] = _state[e] *
kpeter@601
   561
              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601
   562
            if (_cand_cost[e] < 0) {
kpeter@601
   563
              _candidates[_curr_length++] = e;
kpeter@603
   564
              last_arc = e;
kpeter@601
   565
            }
kpeter@601
   566
            if (--cnt == 0) {
kpeter@601
   567
              if (_curr_length > limit) break;
kpeter@601
   568
              limit = 0;
kpeter@601
   569
              cnt = _block_size;
kpeter@601
   570
            }
kpeter@601
   571
          }
kpeter@601
   572
        }
kpeter@601
   573
        if (_curr_length == 0) return false;
kpeter@603
   574
        _next_arc = last_arc + 1;
kpeter@601
   575
kpeter@601
   576
        // Make heap of the candidate list (approximating a partial sort)
kpeter@601
   577
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
kpeter@601
   578
                   _sort_func );
kpeter@601
   579
kpeter@601
   580
        // Pop the first element of the heap
kpeter@601
   581
        _in_arc = _candidates[0];
kpeter@601
   582
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
kpeter@601
   583
                  _sort_func );
kpeter@601
   584
        _curr_length = std::min(_head_length, _curr_length - 1);
kpeter@601
   585
        return true;
kpeter@601
   586
      }
kpeter@601
   587
kpeter@601
   588
    }; //class AlteringListPivotRule
kpeter@601
   589
kpeter@601
   590
  public:
kpeter@601
   591
kpeter@601
   592
    /// \brief General constructor (with lower bounds).
kpeter@601
   593
    ///
kpeter@601
   594
    /// General constructor (with lower bounds).
kpeter@601
   595
    ///
kpeter@603
   596
    /// \param graph The digraph the algorithm runs on.
kpeter@601
   597
    /// \param lower The lower bounds of the arcs.
kpeter@601
   598
    /// \param capacity The capacities (upper bounds) of the arcs.
kpeter@601
   599
    /// \param cost The cost (length) values of the arcs.
kpeter@601
   600
    /// \param supply The supply values of the nodes (signed).
kpeter@603
   601
    NetworkSimplex( const Digraph &graph,
kpeter@601
   602
                    const LowerMap &lower,
kpeter@601
   603
                    const CapacityMap &capacity,
kpeter@601
   604
                    const CostMap &cost,
kpeter@601
   605
                    const SupplyMap &supply ) :
kpeter@603
   606
      _graph(graph), _orig_lower(&lower), _orig_cap(capacity),
kpeter@601
   607
      _orig_cost(cost), _orig_supply(&supply),
kpeter@603
   608
      _flow_map(NULL), _potential_map(NULL),
kpeter@601
   609
      _local_flow(false), _local_potential(false),
kpeter@603
   610
      _node_id(graph)
kpeter@601
   611
    {}
kpeter@601
   612
kpeter@601
   613
    /// \brief General constructor (without lower bounds).
kpeter@601
   614
    ///
kpeter@601
   615
    /// General constructor (without lower bounds).
kpeter@601
   616
    ///
kpeter@603
   617
    /// \param graph The digraph the algorithm runs on.
kpeter@601
   618
    /// \param capacity The capacities (upper bounds) of the arcs.
kpeter@601
   619
    /// \param cost The cost (length) values of the arcs.
kpeter@601
   620
    /// \param supply The supply values of the nodes (signed).
kpeter@603
   621
    NetworkSimplex( const Digraph &graph,
kpeter@601
   622
                    const CapacityMap &capacity,
kpeter@601
   623
                    const CostMap &cost,
kpeter@601
   624
                    const SupplyMap &supply ) :
kpeter@603
   625
      _graph(graph), _orig_lower(NULL), _orig_cap(capacity),
kpeter@601
   626
      _orig_cost(cost), _orig_supply(&supply),
kpeter@603
   627
      _flow_map(NULL), _potential_map(NULL),
kpeter@601
   628
      _local_flow(false), _local_potential(false),
kpeter@603
   629
      _node_id(graph)
kpeter@601
   630
    {}
kpeter@601
   631
kpeter@601
   632
    /// \brief Simple constructor (with lower bounds).
kpeter@601
   633
    ///
kpeter@601
   634
    /// Simple constructor (with lower bounds).
kpeter@601
   635
    ///
kpeter@603
   636
    /// \param graph The digraph the algorithm runs on.
kpeter@601
   637
    /// \param lower The lower bounds of the arcs.
kpeter@601
   638
    /// \param capacity The capacities (upper bounds) of the arcs.
kpeter@601
   639
    /// \param cost The cost (length) values of the arcs.
kpeter@601
   640
    /// \param s The source node.
kpeter@601
   641
    /// \param t The target node.
kpeter@601
   642
    /// \param flow_value The required amount of flow from node \c s
kpeter@601
   643
    /// to node \c t (i.e. the supply of \c s and the demand of \c t).
kpeter@603
   644
    NetworkSimplex( const Digraph &graph,
kpeter@601
   645
                    const LowerMap &lower,
kpeter@601
   646
                    const CapacityMap &capacity,
kpeter@601
   647
                    const CostMap &cost,
kpeter@601
   648
                    Node s, Node t,
kpeter@601
   649
                    Capacity flow_value ) :
kpeter@603
   650
      _graph(graph), _orig_lower(&lower), _orig_cap(capacity),
kpeter@601
   651
      _orig_cost(cost), _orig_supply(NULL),
kpeter@601
   652
      _orig_source(s), _orig_target(t), _orig_flow_value(flow_value),
kpeter@603
   653
      _flow_map(NULL), _potential_map(NULL),
kpeter@601
   654
      _local_flow(false), _local_potential(false),
kpeter@603
   655
      _node_id(graph)
kpeter@601
   656
    {}
kpeter@601
   657
kpeter@601
   658
    /// \brief Simple constructor (without lower bounds).
kpeter@601
   659
    ///
kpeter@601
   660
    /// Simple constructor (without lower bounds).
kpeter@601
   661
    ///
kpeter@603
   662
    /// \param graph The digraph the algorithm runs on.
kpeter@601
   663
    /// \param capacity The capacities (upper bounds) of the arcs.
kpeter@601
   664
    /// \param cost The cost (length) values of the arcs.
kpeter@601
   665
    /// \param s The source node.
kpeter@601
   666
    /// \param t The target node.
kpeter@601
   667
    /// \param flow_value The required amount of flow from node \c s
kpeter@601
   668
    /// to node \c t (i.e. the supply of \c s and the demand of \c t).
kpeter@603
   669
    NetworkSimplex( const Digraph &graph,
kpeter@601
   670
                    const CapacityMap &capacity,
kpeter@601
   671
                    const CostMap &cost,
kpeter@601
   672
                    Node s, Node t,
kpeter@601
   673
                    Capacity flow_value ) :
kpeter@603
   674
      _graph(graph), _orig_lower(NULL), _orig_cap(capacity),
kpeter@601
   675
      _orig_cost(cost), _orig_supply(NULL),
kpeter@601
   676
      _orig_source(s), _orig_target(t), _orig_flow_value(flow_value),
kpeter@603
   677
      _flow_map(NULL), _potential_map(NULL),
kpeter@601
   678
      _local_flow(false), _local_potential(false),
kpeter@603
   679
      _node_id(graph)
kpeter@601
   680
    {}
kpeter@601
   681
kpeter@601
   682
    /// Destructor.
kpeter@601
   683
    ~NetworkSimplex() {
kpeter@603
   684
      if (_local_flow) delete _flow_map;
kpeter@603
   685
      if (_local_potential) delete _potential_map;
kpeter@601
   686
    }
kpeter@601
   687
kpeter@601
   688
    /// \brief Set the flow map.
kpeter@601
   689
    ///
kpeter@601
   690
    /// This function sets the flow map.
kpeter@601
   691
    ///
kpeter@601
   692
    /// \return <tt>(*this)</tt>
kpeter@601
   693
    NetworkSimplex& flowMap(FlowMap &map) {
kpeter@601
   694
      if (_local_flow) {
kpeter@603
   695
        delete _flow_map;
kpeter@601
   696
        _local_flow = false;
kpeter@601
   697
      }
kpeter@603
   698
      _flow_map = &map;
kpeter@601
   699
      return *this;
kpeter@601
   700
    }
kpeter@601
   701
kpeter@601
   702
    /// \brief Set the potential map.
kpeter@601
   703
    ///
kpeter@601
   704
    /// This function sets the potential map.
kpeter@601
   705
    ///
kpeter@601
   706
    /// \return <tt>(*this)</tt>
kpeter@601
   707
    NetworkSimplex& potentialMap(PotentialMap &map) {
kpeter@601
   708
      if (_local_potential) {
kpeter@603
   709
        delete _potential_map;
kpeter@601
   710
        _local_potential = false;
kpeter@601
   711
      }
kpeter@603
   712
      _potential_map = &map;
kpeter@601
   713
      return *this;
kpeter@601
   714
    }
kpeter@601
   715
kpeter@601
   716
    /// \name Execution control
kpeter@601
   717
    /// The algorithm can be executed using the
kpeter@601
   718
    /// \ref lemon::NetworkSimplex::run() "run()" function.
kpeter@601
   719
    /// @{
kpeter@601
   720
kpeter@601
   721
    /// \brief Run the algorithm.
kpeter@601
   722
    ///
kpeter@601
   723
    /// This function runs the algorithm.
kpeter@601
   724
    ///
kpeter@601
   725
    /// \param pivot_rule The pivot rule that is used during the
kpeter@601
   726
    /// algorithm.
kpeter@601
   727
    ///
kpeter@601
   728
    /// The available pivot rules:
kpeter@601
   729
    ///
kpeter@601
   730
    /// - FIRST_ELIGIBLE_PIVOT The next eligible arc is selected in
kpeter@601
   731
    /// a wraparound fashion in every iteration
kpeter@601
   732
    /// (\ref FirstEligiblePivotRule).
kpeter@601
   733
    ///
kpeter@601
   734
    /// - BEST_ELIGIBLE_PIVOT The best eligible arc is selected in
kpeter@601
   735
    /// every iteration (\ref BestEligiblePivotRule).
kpeter@601
   736
    ///
kpeter@601
   737
    /// - BLOCK_SEARCH_PIVOT A specified number of arcs are examined in
kpeter@601
   738
    /// every iteration in a wraparound fashion and the best eligible
kpeter@601
   739
    /// arc is selected from this block (\ref BlockSearchPivotRule).
kpeter@601
   740
    ///
kpeter@601
   741
    /// - CANDIDATE_LIST_PIVOT In a major iteration a candidate list is
kpeter@601
   742
    /// built from eligible arcs in a wraparound fashion and in the
kpeter@601
   743
    /// following minor iterations the best eligible arc is selected
kpeter@601
   744
    /// from this list (\ref CandidateListPivotRule).
kpeter@601
   745
    ///
kpeter@601
   746
    /// - ALTERING_LIST_PIVOT It is a modified version of the
kpeter@601
   747
    /// "Candidate List" pivot rule. It keeps only the several best
kpeter@601
   748
    /// eligible arcs from the former candidate list and extends this
kpeter@601
   749
    /// list in every iteration (\ref AlteringListPivotRule).
kpeter@601
   750
    ///
kpeter@601
   751
    /// According to our comprehensive benchmark tests the "Block Search"
kpeter@601
   752
    /// pivot rule proved to be the fastest and the most robust on
kpeter@601
   753
    /// various test inputs. Thus it is the default option.
kpeter@601
   754
    ///
kpeter@601
   755
    /// \return \c true if a feasible flow can be found.
kpeter@601
   756
    bool run(PivotRuleEnum pivot_rule = BLOCK_SEARCH_PIVOT) {
kpeter@601
   757
      return init() && start(pivot_rule);
kpeter@601
   758
    }
kpeter@601
   759
kpeter@601
   760
    /// @}
kpeter@601
   761
kpeter@601
   762
    /// \name Query Functions
kpeter@601
   763
    /// The results of the algorithm can be obtained using these
kpeter@601
   764
    /// functions.\n
kpeter@601
   765
    /// \ref lemon::NetworkSimplex::run() "run()" must be called before
kpeter@601
   766
    /// using them.
kpeter@601
   767
    /// @{
kpeter@601
   768
kpeter@601
   769
    /// \brief Return a const reference to the flow map.
kpeter@601
   770
    ///
kpeter@601
   771
    /// This function returns a const reference to an arc map storing
kpeter@601
   772
    /// the found flow.
kpeter@601
   773
    ///
kpeter@601
   774
    /// \pre \ref run() must be called before using this function.
kpeter@601
   775
    const FlowMap& flowMap() const {
kpeter@603
   776
      return *_flow_map;
kpeter@601
   777
    }
kpeter@601
   778
kpeter@601
   779
    /// \brief Return a const reference to the potential map
kpeter@601
   780
    /// (the dual solution).
kpeter@601
   781
    ///
kpeter@601
   782
    /// This function returns a const reference to a node map storing
kpeter@601
   783
    /// the found potentials (the dual solution).
kpeter@601
   784
    ///
kpeter@601
   785
    /// \pre \ref run() must be called before using this function.
kpeter@601
   786
    const PotentialMap& potentialMap() const {
kpeter@603
   787
      return *_potential_map;
kpeter@601
   788
    }
kpeter@601
   789
kpeter@601
   790
    /// \brief Return the flow on the given arc.
kpeter@601
   791
    ///
kpeter@601
   792
    /// This function returns the flow on the given arc.
kpeter@601
   793
    ///
kpeter@601
   794
    /// \pre \ref run() must be called before using this function.
kpeter@601
   795
    Capacity flow(const Arc& arc) const {
kpeter@603
   796
      return (*_flow_map)[arc];
kpeter@601
   797
    }
kpeter@601
   798
kpeter@601
   799
    /// \brief Return the potential of the given node.
kpeter@601
   800
    ///
kpeter@601
   801
    /// This function returns the potential of the given node.
kpeter@601
   802
    ///
kpeter@601
   803
    /// \pre \ref run() must be called before using this function.
kpeter@601
   804
    Cost potential(const Node& node) const {
kpeter@603
   805
      return (*_potential_map)[node];
kpeter@601
   806
    }
kpeter@601
   807
kpeter@601
   808
    /// \brief Return the total cost of the found flow.
kpeter@601
   809
    ///
kpeter@601
   810
    /// This function returns the total cost of the found flow.
kpeter@601
   811
    /// The complexity of the function is \f$ O(e) \f$.
kpeter@601
   812
    ///
kpeter@601
   813
    /// \pre \ref run() must be called before using this function.
kpeter@601
   814
    Cost totalCost() const {
kpeter@601
   815
      Cost c = 0;
kpeter@603
   816
      for (ArcIt e(_graph); e != INVALID; ++e)
kpeter@603
   817
        c += (*_flow_map)[e] * _orig_cost[e];
kpeter@601
   818
      return c;
kpeter@601
   819
    }
kpeter@601
   820
kpeter@601
   821
    /// @}
kpeter@601
   822
kpeter@601
   823
  private:
kpeter@601
   824
kpeter@601
   825
    // Initialize internal data structures
kpeter@601
   826
    bool init() {
kpeter@601
   827
      // Initialize result maps
kpeter@603
   828
      if (!_flow_map) {
kpeter@603
   829
        _flow_map = new FlowMap(_graph);
kpeter@601
   830
        _local_flow = true;
kpeter@601
   831
      }
kpeter@603
   832
      if (!_potential_map) {
kpeter@603
   833
        _potential_map = new PotentialMap(_graph);
kpeter@601
   834
        _local_potential = true;
kpeter@601
   835
      }
kpeter@601
   836
kpeter@601
   837
      // Initialize vectors
kpeter@603
   838
      _node_num = countNodes(_graph);
kpeter@603
   839
      _arc_num = countArcs(_graph);
kpeter@601
   840
      int all_node_num = _node_num + 1;
kpeter@603
   841
      int all_arc_num = _arc_num + _node_num;
kpeter@601
   842
kpeter@603
   843
      _arc_ref.resize(_arc_num);
kpeter@603
   844
      _source.resize(all_arc_num);
kpeter@603
   845
      _target.resize(all_arc_num);
kpeter@601
   846
kpeter@603
   847
      _cap.resize(all_arc_num);
kpeter@603
   848
      _cost.resize(all_arc_num);
kpeter@601
   849
      _supply.resize(all_node_num);
kpeter@603
   850
      _flow.resize(all_arc_num, 0);
kpeter@601
   851
      _pi.resize(all_node_num, 0);
kpeter@601
   852
kpeter@601
   853
      _depth.resize(all_node_num);
kpeter@601
   854
      _parent.resize(all_node_num);
kpeter@601
   855
      _pred.resize(all_node_num);
kpeter@603
   856
      _forward.resize(all_node_num);
kpeter@601
   857
      _thread.resize(all_node_num);
kpeter@603
   858
      _state.resize(all_arc_num, STATE_LOWER);
kpeter@601
   859
kpeter@601
   860
      // Initialize node related data
kpeter@601
   861
      bool valid_supply = true;
kpeter@601
   862
      if (_orig_supply) {
kpeter@601
   863
        Supply sum = 0;
kpeter@601
   864
        int i = 0;
kpeter@603
   865
        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@601
   866
          _node_id[n] = i;
kpeter@601
   867
          _supply[i] = (*_orig_supply)[n];
kpeter@601
   868
          sum += _supply[i];
kpeter@601
   869
        }
kpeter@601
   870
        valid_supply = (sum == 0);
kpeter@601
   871
      } else {
kpeter@601
   872
        int i = 0;
kpeter@603
   873
        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@601
   874
          _node_id[n] = i;
kpeter@601
   875
          _supply[i] = 0;
kpeter@601
   876
        }
kpeter@601
   877
        _supply[_node_id[_orig_source]] =  _orig_flow_value;
kpeter@601
   878
        _supply[_node_id[_orig_target]] = -_orig_flow_value;
kpeter@601
   879
      }
kpeter@601
   880
      if (!valid_supply) return false;
kpeter@601
   881
kpeter@601
   882
      // Set data for the artificial root node
kpeter@601
   883
      _root = _node_num;
kpeter@601
   884
      _depth[_root] = 0;
kpeter@601
   885
      _parent[_root] = -1;
kpeter@601
   886
      _pred[_root] = -1;
kpeter@601
   887
      _thread[_root] = 0;
kpeter@601
   888
      _supply[_root] = 0;
kpeter@601
   889
      _pi[_root] = 0;
kpeter@601
   890
kpeter@601
   891
      // Store the arcs in a mixed order
kpeter@601
   892
      int k = std::max(int(sqrt(_arc_num)), 10);
kpeter@601
   893
      int i = 0;
kpeter@603
   894
      for (ArcIt e(_graph); e != INVALID; ++e) {
kpeter@603
   895
        _arc_ref[i] = e;
kpeter@601
   896
        if ((i += k) >= _arc_num) i = (i % k) + 1;
kpeter@601
   897
      }
kpeter@601
   898
kpeter@601
   899
      // Initialize arc maps
kpeter@601
   900
      for (int i = 0; i != _arc_num; ++i) {
kpeter@603
   901
        Arc e = _arc_ref[i];
kpeter@603
   902
        _source[i] = _node_id[_graph.source(e)];
kpeter@603
   903
        _target[i] = _node_id[_graph.target(e)];
kpeter@601
   904
        _cost[i] = _orig_cost[e];
kpeter@601
   905
        _cap[i] = _orig_cap[e];
kpeter@601
   906
      }
kpeter@601
   907
kpeter@601
   908
      // Remove non-zero lower bounds
kpeter@601
   909
      if (_orig_lower) {
kpeter@601
   910
        for (int i = 0; i != _arc_num; ++i) {
kpeter@603
   911
          Capacity c = (*_orig_lower)[_arc_ref[i]];
kpeter@601
   912
          if (c != 0) {
kpeter@601
   913
            _cap[i] -= c;
kpeter@601
   914
            _supply[_source[i]] -= c;
kpeter@601
   915
            _supply[_target[i]] += c;
kpeter@601
   916
          }
kpeter@601
   917
        }
kpeter@601
   918
      }
kpeter@601
   919
kpeter@601
   920
      // Add artificial arcs and initialize the spanning tree data structure
kpeter@601
   921
      Cost max_cost = std::numeric_limits<Cost>::max() / 4;
kpeter@601
   922
      Capacity max_cap = std::numeric_limits<Capacity>::max();
kpeter@601
   923
      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
kpeter@601
   924
        _thread[u] = u + 1;
kpeter@601
   925
        _depth[u] = 1;
kpeter@601
   926
        _parent[u] = _root;
kpeter@601
   927
        _pred[u] = e;
kpeter@601
   928
        if (_supply[u] >= 0) {
kpeter@601
   929
          _flow[e] = _supply[u];
kpeter@601
   930
          _forward[u] = true;
kpeter@601
   931
          _pi[u] = -max_cost;
kpeter@601
   932
        } else {
kpeter@601
   933
          _flow[e] = -_supply[u];
kpeter@601
   934
          _forward[u] = false;
kpeter@601
   935
          _pi[u] = max_cost;
kpeter@601
   936
        }
kpeter@601
   937
        _cost[e] = max_cost;
kpeter@601
   938
        _cap[e] = max_cap;
kpeter@601
   939
        _state[e] = STATE_TREE;
kpeter@601
   940
      }
kpeter@601
   941
kpeter@601
   942
      return true;
kpeter@601
   943
    }
kpeter@601
   944
kpeter@601
   945
    // Find the join node
kpeter@601
   946
    void findJoinNode() {
kpeter@603
   947
      int u = _source[in_arc];
kpeter@603
   948
      int v = _target[in_arc];
kpeter@601
   949
      while (_depth[u] > _depth[v]) u = _parent[u];
kpeter@601
   950
      while (_depth[v] > _depth[u]) v = _parent[v];
kpeter@601
   951
      while (u != v) {
kpeter@601
   952
        u = _parent[u];
kpeter@601
   953
        v = _parent[v];
kpeter@601
   954
      }
kpeter@601
   955
      join = u;
kpeter@601
   956
    }
kpeter@601
   957
kpeter@601
   958
    // Find the leaving arc of the cycle and returns true if the
kpeter@601
   959
    // leaving arc is not the same as the entering arc
kpeter@601
   960
    bool findLeavingArc() {
kpeter@601
   961
      // Initialize first and second nodes according to the direction
kpeter@601
   962
      // of the cycle
kpeter@603
   963
      if (_state[in_arc] == STATE_LOWER) {
kpeter@603
   964
        first  = _source[in_arc];
kpeter@603
   965
        second = _target[in_arc];
kpeter@601
   966
      } else {
kpeter@603
   967
        first  = _target[in_arc];
kpeter@603
   968
        second = _source[in_arc];
kpeter@601
   969
      }
kpeter@603
   970
      delta = _cap[in_arc];
kpeter@601
   971
      int result = 0;
kpeter@601
   972
      Capacity d;
kpeter@601
   973
      int e;
kpeter@601
   974
kpeter@601
   975
      // Search the cycle along the path form the first node to the root
kpeter@601
   976
      for (int u = first; u != join; u = _parent[u]) {
kpeter@601
   977
        e = _pred[u];
kpeter@601
   978
        d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
kpeter@601
   979
        if (d < delta) {
kpeter@601
   980
          delta = d;
kpeter@601
   981
          u_out = u;
kpeter@601
   982
          result = 1;
kpeter@601
   983
        }
kpeter@601
   984
      }
kpeter@601
   985
      // Search the cycle along the path form the second node to the root
kpeter@601
   986
      for (int u = second; u != join; u = _parent[u]) {
kpeter@601
   987
        e = _pred[u];
kpeter@601
   988
        d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
kpeter@601
   989
        if (d <= delta) {
kpeter@601
   990
          delta = d;
kpeter@601
   991
          u_out = u;
kpeter@601
   992
          result = 2;
kpeter@601
   993
        }
kpeter@601
   994
      }
kpeter@601
   995
kpeter@601
   996
      if (result == 1) {
kpeter@601
   997
        u_in = first;
kpeter@601
   998
        v_in = second;
kpeter@601
   999
      } else {
kpeter@601
  1000
        u_in = second;
kpeter@601
  1001
        v_in = first;
kpeter@601
  1002
      }
kpeter@601
  1003
      return result != 0;
kpeter@601
  1004
    }
kpeter@601
  1005
kpeter@601
  1006
    // Change _flow and _state vectors
kpeter@601
  1007
    void changeFlow(bool change) {
kpeter@601
  1008
      // Augment along the cycle
kpeter@601
  1009
      if (delta > 0) {
kpeter@603
  1010
        Capacity val = _state[in_arc] * delta;
kpeter@603
  1011
        _flow[in_arc] += val;
kpeter@603
  1012
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
kpeter@601
  1013
          _flow[_pred[u]] += _forward[u] ? -val : val;
kpeter@601
  1014
        }
kpeter@603
  1015
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
kpeter@601
  1016
          _flow[_pred[u]] += _forward[u] ? val : -val;
kpeter@601
  1017
        }
kpeter@601
  1018
      }
kpeter@601
  1019
      // Update the state of the entering and leaving arcs
kpeter@601
  1020
      if (change) {
kpeter@603
  1021
        _state[in_arc] = STATE_TREE;
kpeter@601
  1022
        _state[_pred[u_out]] =
kpeter@601
  1023
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
kpeter@601
  1024
      } else {
kpeter@603
  1025
        _state[in_arc] = -_state[in_arc];
kpeter@601
  1026
      }
kpeter@601
  1027
    }
kpeter@601
  1028
kpeter@601
  1029
    // Update _thread and _parent vectors
kpeter@601
  1030
    void updateThreadParent() {
kpeter@601
  1031
      int u;
kpeter@601
  1032
      v_out = _parent[u_out];
kpeter@601
  1033
kpeter@601
  1034
      // Handle the case when join and v_out coincide
kpeter@601
  1035
      bool par_first = false;
kpeter@601
  1036
      if (join == v_out) {
kpeter@601
  1037
        for (u = join; u != u_in && u != v_in; u = _thread[u]) ;
kpeter@601
  1038
        if (u == v_in) {
kpeter@601
  1039
          par_first = true;
kpeter@601
  1040
          while (_thread[u] != u_out) u = _thread[u];
kpeter@601
  1041
          first = u;
kpeter@601
  1042
        }
kpeter@601
  1043
      }
kpeter@601
  1044
kpeter@601
  1045
      // Find the last successor of u_in (u) and the node after it (right)
kpeter@601
  1046
      // according to the thread index
kpeter@601
  1047
      for (u = u_in; _depth[_thread[u]] > _depth[u_in]; u = _thread[u]) ;
kpeter@601
  1048
      right = _thread[u];
kpeter@601
  1049
      if (_thread[v_in] == u_out) {
kpeter@601
  1050
        for (last = u; _depth[last] > _depth[u_out]; last = _thread[last]) ;
kpeter@601
  1051
        if (last == u_out) last = _thread[last];
kpeter@601
  1052
      }
kpeter@601
  1053
      else last = _thread[v_in];
kpeter@601
  1054
kpeter@601
  1055
      // Update stem nodes
kpeter@601
  1056
      _thread[v_in] = stem = u_in;
kpeter@601
  1057
      par_stem = v_in;
kpeter@601
  1058
      while (stem != u_out) {
kpeter@601
  1059
        _thread[u] = new_stem = _parent[stem];
kpeter@601
  1060
kpeter@601
  1061
        // Find the node just before the stem node (u) according to
kpeter@601
  1062
        // the original thread index
kpeter@601
  1063
        for (u = new_stem; _thread[u] != stem; u = _thread[u]) ;
kpeter@601
  1064
        _thread[u] = right;
kpeter@601
  1065
kpeter@601
  1066
        // Change the parent node of stem and shift stem and par_stem nodes
kpeter@601
  1067
        _parent[stem] = par_stem;
kpeter@601
  1068
        par_stem = stem;
kpeter@601
  1069
        stem = new_stem;
kpeter@601
  1070
kpeter@601
  1071
        // Find the last successor of stem (u) and the node after it (right)
kpeter@601
  1072
        // according to the thread index
kpeter@601
  1073
        for (u = stem; _depth[_thread[u]] > _depth[stem]; u = _thread[u]) ;
kpeter@601
  1074
        right = _thread[u];
kpeter@601
  1075
      }
kpeter@601
  1076
      _parent[u_out] = par_stem;
kpeter@601
  1077
      _thread[u] = last;
kpeter@601
  1078
kpeter@601
  1079
      if (join == v_out && par_first) {
kpeter@601
  1080
        if (first != v_in) _thread[first] = right;
kpeter@601
  1081
      } else {
kpeter@601
  1082
        for (u = v_out; _thread[u] != u_out; u = _thread[u]) ;
kpeter@601
  1083
        _thread[u] = right;
kpeter@601
  1084
      }
kpeter@601
  1085
    }
kpeter@601
  1086
kpeter@601
  1087
    // Update _pred and _forward vectors
kpeter@601
  1088
    void updatePredArc() {
kpeter@601
  1089
      int u = u_out, v;
kpeter@601
  1090
      while (u != u_in) {
kpeter@601
  1091
        v = _parent[u];
kpeter@601
  1092
        _pred[u] = _pred[v];
kpeter@601
  1093
        _forward[u] = !_forward[v];
kpeter@601
  1094
        u = v;
kpeter@601
  1095
      }
kpeter@603
  1096
      _pred[u_in] = in_arc;
kpeter@603
  1097
      _forward[u_in] = (u_in == _source[in_arc]);
kpeter@601
  1098
    }
kpeter@601
  1099
kpeter@601
  1100
    // Update _depth and _potential vectors
kpeter@601
  1101
    void updateDepthPotential() {
kpeter@601
  1102
      _depth[u_in] = _depth[v_in] + 1;
kpeter@601
  1103
      Cost sigma = _forward[u_in] ?
kpeter@601
  1104
        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
kpeter@601
  1105
        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
kpeter@601
  1106
      _pi[u_in] += sigma;
kpeter@601
  1107
      for(int u = _thread[u_in]; _parent[u] != -1; u = _thread[u]) {
kpeter@601
  1108
        _depth[u] = _depth[_parent[u]] + 1;
kpeter@601
  1109
        if (_depth[u] <= _depth[u_in]) break;
kpeter@601
  1110
        _pi[u] += sigma;
kpeter@601
  1111
      }
kpeter@601
  1112
    }
kpeter@601
  1113
kpeter@601
  1114
    // Execute the algorithm
kpeter@601
  1115
    bool start(PivotRuleEnum pivot_rule) {
kpeter@601
  1116
      // Select the pivot rule implementation
kpeter@601
  1117
      switch (pivot_rule) {
kpeter@601
  1118
        case FIRST_ELIGIBLE_PIVOT:
kpeter@601
  1119
          return start<FirstEligiblePivotRule>();
kpeter@601
  1120
        case BEST_ELIGIBLE_PIVOT:
kpeter@601
  1121
          return start<BestEligiblePivotRule>();
kpeter@601
  1122
        case BLOCK_SEARCH_PIVOT:
kpeter@601
  1123
          return start<BlockSearchPivotRule>();
kpeter@601
  1124
        case CANDIDATE_LIST_PIVOT:
kpeter@601
  1125
          return start<CandidateListPivotRule>();
kpeter@601
  1126
        case ALTERING_LIST_PIVOT:
kpeter@601
  1127
          return start<AlteringListPivotRule>();
kpeter@601
  1128
      }
kpeter@601
  1129
      return false;
kpeter@601
  1130
    }
kpeter@601
  1131
kpeter@601
  1132
    template<class PivotRuleImplementation>
kpeter@601
  1133
    bool start() {
kpeter@601
  1134
      PivotRuleImplementation pivot(*this);
kpeter@601
  1135
kpeter@601
  1136
      // Execute the network simplex algorithm
kpeter@601
  1137
      while (pivot.findEnteringArc()) {
kpeter@601
  1138
        findJoinNode();
kpeter@601
  1139
        bool change = findLeavingArc();
kpeter@601
  1140
        changeFlow(change);
kpeter@601
  1141
        if (change) {
kpeter@601
  1142
          updateThreadParent();
kpeter@601
  1143
          updatePredArc();
kpeter@601
  1144
          updateDepthPotential();
kpeter@601
  1145
        }
kpeter@601
  1146
      }
kpeter@601
  1147
kpeter@601
  1148
      // Check if the flow amount equals zero on all the artificial arcs
kpeter@601
  1149
      for (int e = _arc_num; e != _arc_num + _node_num; ++e) {
kpeter@601
  1150
        if (_flow[e] > 0) return false;
kpeter@601
  1151
      }
kpeter@601
  1152
kpeter@603
  1153
      // Copy flow values to _flow_map
kpeter@601
  1154
      if (_orig_lower) {
kpeter@601
  1155
        for (int i = 0; i != _arc_num; ++i) {
kpeter@603
  1156
          Arc e = _arc_ref[i];
kpeter@603
  1157
          _flow_map->set(e, (*_orig_lower)[e] + _flow[i]);
kpeter@601
  1158
        }
kpeter@601
  1159
      } else {
kpeter@601
  1160
        for (int i = 0; i != _arc_num; ++i) {
kpeter@603
  1161
          _flow_map->set(_arc_ref[i], _flow[i]);
kpeter@601
  1162
        }
kpeter@601
  1163
      }
kpeter@603
  1164
      // Copy potential values to _potential_map
kpeter@603
  1165
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@603
  1166
        _potential_map->set(n, _pi[_node_id[n]]);
kpeter@601
  1167
      }
kpeter@601
  1168
kpeter@601
  1169
      return true;
kpeter@601
  1170
    }
kpeter@601
  1171
kpeter@601
  1172
  }; //class NetworkSimplex
kpeter@601
  1173
kpeter@601
  1174
  ///@}
kpeter@601
  1175
kpeter@601
  1176
} //namespace lemon
kpeter@601
  1177
kpeter@601
  1178
#endif //LEMON_NETWORK_SIMPLEX_H