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