COIN-OR::LEMON - Graph Library

source: lemon/lemon/network_simplex.h @ 1023:e0cef67fe565

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

Various doc improvements (#406)

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