COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/network_simplex.h @ 607:9ad8d2122b50

Last change on this file since 607:9ad8d2122b50 was 607:9ad8d2122b50, checked in by Peter Kovacs <kpeter@…>, 15 years ago

Separate types for flow and cost values in NetworkSimplex? (#234)

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