COIN-OR::LEMON - Graph Library

source: lemon/lemon/network_simplex.h @ 687:6c408d864fa1

Last change on this file since 687:6c408d864fa1 was 687:6c408d864fa1, checked in by Peter Kovacs <kpeter@…>, 11 years ago

Support negative costs and bounds in NetworkSimplex? (#270)

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