No children
gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 2 0
merge tip default
0 files changed with 25 insertions and 22 deletions:
↑ Collapse diff ↑
Ignore white space 4096 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_CAPACITY_SCALING_H
20 20
#define LEMON_CAPACITY_SCALING_H
21 21

	
22 22
/// \ingroup min_cost_flow_algs
23 23
///
24 24
/// \file
25 25
/// \brief Capacity Scaling algorithm for finding a minimum cost flow.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/bin_heap.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  /// \brief Default traits class of CapacityScaling algorithm.
35 35
  ///
36 36
  /// Default traits class of CapacityScaling algorithm.
37 37
  /// \tparam GR Digraph type.
38 38
  /// \tparam V The number type used for flow amounts, capacity bounds
39 39
  /// and supply values. By default it is \c int.
40 40
  /// \tparam C The number type used for costs and potentials.
41 41
  /// By default it is the same as \c V.
42 42
  template <typename GR, typename V = int, typename C = V>
43 43
  struct CapacityScalingDefaultTraits
44 44
  {
45 45
    /// The type of the digraph
46 46
    typedef GR Digraph;
47 47
    /// The type of the flow amounts, capacity bounds and supply values
48 48
    typedef V Value;
49 49
    /// The type of the arc costs
50 50
    typedef C Cost;
51 51

	
52 52
    /// \brief The type of the heap used for internal Dijkstra computations.
53 53
    ///
54 54
    /// The type of the heap used for internal Dijkstra computations.
55 55
    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
56 56
    /// its priority type must be \c Cost and its cross reference type
57 57
    /// must be \ref RangeMap "RangeMap<int>".
58 58
    typedef BinHeap<Cost, RangeMap<int> > Heap;
59 59
  };
60 60

	
61 61
  /// \addtogroup min_cost_flow_algs
62 62
  /// @{
63 63

	
64 64
  /// \brief Implementation of the Capacity Scaling algorithm for
65 65
  /// finding a \ref min_cost_flow "minimum cost flow".
66 66
  ///
67 67
  /// \ref CapacityScaling implements the capacity scaling version
68 68
  /// of the successive shortest path algorithm for finding a
69 69
  /// \ref min_cost_flow "minimum cost flow" \ref amo93networkflows,
70 70
  /// \ref edmondskarp72theoretical. It is an efficient dual
71 71
  /// solution method.
72 72
  ///
73 73
  /// Most of the parameters of the problem (except for the digraph)
74 74
  /// can be given using separate functions, and the algorithm can be
75 75
  /// executed using the \ref run() function. If some parameters are not
76 76
  /// specified, then default values will be used.
77 77
  ///
78 78
  /// \tparam GR The digraph type the algorithm runs on.
79 79
  /// \tparam V The number type used for flow amounts, capacity bounds
80 80
  /// and supply values in the algorithm. By default, it is \c int.
81 81
  /// \tparam C The number type used for costs and potentials in the
82 82
  /// algorithm. By default, it is the same as \c V.
83 83
  /// \tparam TR The traits class that defines various types used by the
84 84
  /// algorithm. By default, it is \ref CapacityScalingDefaultTraits
85 85
  /// "CapacityScalingDefaultTraits<GR, V, C>".
86 86
  /// In most cases, this parameter should not be set directly,
87 87
  /// consider to use the named template parameters instead.
88 88
  ///
89 89
  /// \warning Both \c V and \c C must be signed number types.
90
  /// \warning All input data (capacities, supply values, and costs) must
91
  /// be integer.
90
  /// \warning Capacity bounds and supply values must be integer, but
91
  /// arc costs can be arbitrary real numbers.
92 92
  /// \warning This algorithm does not support negative costs for
93 93
  /// arcs having infinite upper bound.
94 94
#ifdef DOXYGEN
95 95
  template <typename GR, typename V, typename C, typename TR>
96 96
#else
97 97
  template < typename GR, typename V = int, typename C = V,
98 98
             typename TR = CapacityScalingDefaultTraits<GR, V, C> >
99 99
#endif
100 100
  class CapacityScaling
101 101
  {
102 102
  public:
103 103

	
104 104
    /// The type of the digraph
105 105
    typedef typename TR::Digraph Digraph;
106 106
    /// The type of the flow amounts, capacity bounds and supply values
107 107
    typedef typename TR::Value Value;
108 108
    /// The type of the arc costs
109 109
    typedef typename TR::Cost Cost;
110 110

	
111 111
    /// The type of the heap used for internal Dijkstra computations
112 112
    typedef typename TR::Heap Heap;
113 113

	
114 114
    /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
115 115
    typedef TR Traits;
116 116

	
117 117
  public:
118 118

	
119 119
    /// \brief Problem type constants for the \c run() function.
120 120
    ///
121 121
    /// Enum type containing the problem type constants that can be
122 122
    /// returned by the \ref run() function of the algorithm.
123 123
    enum ProblemType {
124 124
      /// The problem has no feasible solution (flow).
125 125
      INFEASIBLE,
126 126
      /// The problem has optimal solution (i.e. it is feasible and
127 127
      /// bounded), and the algorithm has found optimal flow and node
128 128
      /// potentials (primal and dual solutions).
129 129
      OPTIMAL,
130 130
      /// The digraph contains an arc of negative cost and infinite
131 131
      /// upper bound. It means that the objective function is unbounded
132 132
      /// on that arc, however, note that it could actually be bounded
133 133
      /// over the feasible flows, but this algroithm cannot handle
134 134
      /// these cases.
135 135
      UNBOUNDED
136 136
    };
137 137

	
138 138
  private:
139 139

	
140 140
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
141 141

	
142 142
    typedef std::vector<int> IntVector;
143 143
    typedef std::vector<Value> ValueVector;
144 144
    typedef std::vector<Cost> CostVector;
145 145
    typedef std::vector<char> BoolVector;
146 146
    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
147 147

	
148 148
  private:
149 149

	
150 150
    // Data related to the underlying digraph
151 151
    const GR &_graph;
152 152
    int _node_num;
153 153
    int _arc_num;
154 154
    int _res_arc_num;
155 155
    int _root;
156 156

	
157 157
    // Parameters of the problem
158 158
    bool _have_lower;
159 159
    Value _sum_supply;
160 160

	
161 161
    // Data structures for storing the digraph
162 162
    IntNodeMap _node_id;
163 163
    IntArcMap _arc_idf;
164 164
    IntArcMap _arc_idb;
165 165
    IntVector _first_out;
166 166
    BoolVector _forward;
167 167
    IntVector _source;
168 168
    IntVector _target;
169 169
    IntVector _reverse;
170 170

	
171 171
    // Node and arc data
172 172
    ValueVector _lower;
173 173
    ValueVector _upper;
174 174
    CostVector _cost;
175 175
    ValueVector _supply;
176 176

	
177 177
    ValueVector _res_cap;
178 178
    CostVector _pi;
179 179
    ValueVector _excess;
180 180
    IntVector _excess_nodes;
181 181
    IntVector _deficit_nodes;
182 182

	
183 183
    Value _delta;
184 184
    int _factor;
185 185
    IntVector _pred;
186 186

	
187 187
  public:
188 188

	
189 189
    /// \brief Constant for infinite upper bounds (capacities).
190 190
    ///
191 191
    /// Constant for infinite upper bounds (capacities).
192 192
    /// It is \c std::numeric_limits<Value>::infinity() if available,
193 193
    /// \c std::numeric_limits<Value>::max() otherwise.
194 194
    const Value INF;
195 195

	
196 196
  private:
197 197

	
198 198
    // Special implementation of the Dijkstra algorithm for finding
199 199
    // shortest paths in the residual network of the digraph with
200 200
    // respect to the reduced arc costs and modifying the node
201 201
    // potentials according to the found distance labels.
202 202
    class ResidualDijkstra
203 203
    {
204 204
    private:
205 205

	
206 206
      int _node_num;
207 207
      bool _geq;
208 208
      const IntVector &_first_out;
209 209
      const IntVector &_target;
210 210
      const CostVector &_cost;
211 211
      const ValueVector &_res_cap;
212 212
      const ValueVector &_excess;
213 213
      CostVector &_pi;
214 214
      IntVector &_pred;
215 215

	
216 216
      IntVector _proc_nodes;
217 217
      CostVector _dist;
218 218

	
219 219
    public:
220 220

	
221 221
      ResidualDijkstra(CapacityScaling& cs) :
222 222
        _node_num(cs._node_num), _geq(cs._sum_supply < 0),
223 223
        _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
224 224
        _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
225 225
        _pred(cs._pred), _dist(cs._node_num)
226 226
      {}
227 227

	
228 228
      int run(int s, Value delta = 1) {
229 229
        RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
230 230
        Heap heap(heap_cross_ref);
231 231
        heap.push(s, 0);
232 232
        _pred[s] = -1;
233 233
        _proc_nodes.clear();
234 234

	
235 235
        // Process nodes
236 236
        while (!heap.empty() && _excess[heap.top()] > -delta) {
237 237
          int u = heap.top(), v;
238 238
          Cost d = heap.prio() + _pi[u], dn;
239 239
          _dist[u] = heap.prio();
240 240
          _proc_nodes.push_back(u);
241 241
          heap.pop();
242 242

	
243 243
          // Traverse outgoing residual arcs
244 244
          int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1;
245 245
          for (int a = _first_out[u]; a != last_out; ++a) {
246 246
            if (_res_cap[a] < delta) continue;
247 247
            v = _target[a];
248 248
            switch (heap.state(v)) {
249 249
              case Heap::PRE_HEAP:
250 250
                heap.push(v, d + _cost[a] - _pi[v]);
251 251
                _pred[v] = a;
252 252
                break;
253 253
              case Heap::IN_HEAP:
254 254
                dn = d + _cost[a] - _pi[v];
255 255
                if (dn < heap[v]) {
256 256
                  heap.decrease(v, dn);
257 257
                  _pred[v] = a;
258 258
                }
259 259
                break;
260 260
              case Heap::POST_HEAP:
261 261
                break;
262 262
            }
263 263
          }
264 264
        }
265 265
        if (heap.empty()) return -1;
266 266

	
267 267
        // Update potentials of processed nodes
268 268
        int t = heap.top();
269 269
        Cost dt = heap.prio();
270 270
        for (int i = 0; i < int(_proc_nodes.size()); ++i) {
271 271
          _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
272 272
        }
273 273

	
274 274
        return t;
275 275
      }
276 276

	
277 277
    }; //class ResidualDijkstra
278 278

	
279 279
  public:
280 280

	
281 281
    /// \name Named Template Parameters
282 282
    /// @{
283 283

	
284 284
    template <typename T>
285 285
    struct SetHeapTraits : public Traits {
286 286
      typedef T Heap;
287 287
    };
288 288

	
289 289
    /// \brief \ref named-templ-param "Named parameter" for setting
290 290
    /// \c Heap type.
291 291
    ///
292 292
    /// \ref named-templ-param "Named parameter" for setting \c Heap
293 293
    /// type, which is used for internal Dijkstra computations.
294 294
    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
295 295
    /// its priority type must be \c Cost and its cross reference type
296 296
    /// must be \ref RangeMap "RangeMap<int>".
297 297
    template <typename T>
298 298
    struct SetHeap
299 299
      : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
300 300
      typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
301 301
    };
302 302

	
303 303
    /// @}
304 304

	
305 305
  protected:
306 306

	
307 307
    CapacityScaling() {}
308 308

	
309 309
  public:
310 310

	
311 311
    /// \brief Constructor.
312 312
    ///
313 313
    /// The constructor of the class.
314 314
    ///
315 315
    /// \param graph The digraph the algorithm runs on.
316 316
    CapacityScaling(const GR& graph) :
317 317
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
318 318
      INF(std::numeric_limits<Value>::has_infinity ?
319 319
          std::numeric_limits<Value>::infinity() :
320 320
          std::numeric_limits<Value>::max())
321 321
    {
322 322
      // Check the number types
323 323
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
324 324
        "The flow type of CapacityScaling must be signed");
325 325
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
326 326
        "The cost type of CapacityScaling must be signed");
327 327

	
328 328
      // Reset data structures
329 329
      reset();
330 330
    }
331 331

	
332 332
    /// \name Parameters
333 333
    /// The parameters of the algorithm can be specified using these
334 334
    /// functions.
335 335

	
336 336
    /// @{
337 337

	
338 338
    /// \brief Set the lower bounds on the arcs.
339 339
    ///
340 340
    /// This function sets the lower bounds on the arcs.
341 341
    /// If it is not used before calling \ref run(), the lower bounds
342 342
    /// will be set to zero on all arcs.
343 343
    ///
344 344
    /// \param map An arc map storing the lower bounds.
345 345
    /// Its \c Value type must be convertible to the \c Value type
346 346
    /// of the algorithm.
347 347
    ///
348 348
    /// \return <tt>(*this)</tt>
349 349
    template <typename LowerMap>
350 350
    CapacityScaling& lowerMap(const LowerMap& map) {
351 351
      _have_lower = true;
352 352
      for (ArcIt a(_graph); a != INVALID; ++a) {
353 353
        _lower[_arc_idf[a]] = map[a];
354 354
        _lower[_arc_idb[a]] = map[a];
355 355
      }
356 356
      return *this;
357 357
    }
358 358

	
359 359
    /// \brief Set the upper bounds (capacities) on the arcs.
360 360
    ///
361 361
    /// This function sets the upper bounds (capacities) on the arcs.
362 362
    /// If it is not used before calling \ref run(), the upper bounds
363 363
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
364 364
    /// unbounded from above).
365 365
    ///
366 366
    /// \param map An arc map storing the upper bounds.
367 367
    /// Its \c Value type must be convertible to the \c Value type
368 368
    /// of the algorithm.
369 369
    ///
370 370
    /// \return <tt>(*this)</tt>
371 371
    template<typename UpperMap>
372 372
    CapacityScaling& upperMap(const UpperMap& map) {
373 373
      for (ArcIt a(_graph); a != INVALID; ++a) {
374 374
        _upper[_arc_idf[a]] = map[a];
375 375
      }
376 376
      return *this;
377 377
    }
378 378

	
379 379
    /// \brief Set the costs of the arcs.
380 380
    ///
381 381
    /// This function sets the costs of the arcs.
382 382
    /// If it is not used before calling \ref run(), the costs
383 383
    /// will be set to \c 1 on all arcs.
384 384
    ///
385 385
    /// \param map An arc map storing the costs.
386 386
    /// Its \c Value type must be convertible to the \c Cost type
387 387
    /// of the algorithm.
388 388
    ///
389 389
    /// \return <tt>(*this)</tt>
390 390
    template<typename CostMap>
391 391
    CapacityScaling& costMap(const CostMap& map) {
392 392
      for (ArcIt a(_graph); a != INVALID; ++a) {
393 393
        _cost[_arc_idf[a]] =  map[a];
394 394
        _cost[_arc_idb[a]] = -map[a];
395 395
      }
396 396
      return *this;
397 397
    }
398 398

	
399 399
    /// \brief Set the supply values of the nodes.
400 400
    ///
401 401
    /// This function sets the supply values of the nodes.
402 402
    /// If neither this function nor \ref stSupply() is used before
403 403
    /// calling \ref run(), the supply of each node will be set to zero.
404 404
    ///
405 405
    /// \param map A node map storing the supply values.
406 406
    /// Its \c Value type must be convertible to the \c Value type
407 407
    /// of the algorithm.
408 408
    ///
409 409
    /// \return <tt>(*this)</tt>
410 410
    template<typename SupplyMap>
411 411
    CapacityScaling& supplyMap(const SupplyMap& map) {
412 412
      for (NodeIt n(_graph); n != INVALID; ++n) {
413 413
        _supply[_node_id[n]] = map[n];
414 414
      }
415 415
      return *this;
416 416
    }
417 417

	
418 418
    /// \brief Set single source and target nodes and a supply value.
419 419
    ///
420 420
    /// This function sets a single source node and a single target node
421 421
    /// and the required flow value.
422 422
    /// If neither this function nor \ref supplyMap() is used before
423 423
    /// calling \ref run(), the supply of each node will be set to zero.
424 424
    ///
425 425
    /// Using this function has the same effect as using \ref supplyMap()
426 426
    /// with a map in which \c k is assigned to \c s, \c -k is
427 427
    /// assigned to \c t and all other nodes have zero supply value.
428 428
    ///
429 429
    /// \param s The source node.
430 430
    /// \param t The target node.
431 431
    /// \param k The required amount of flow from node \c s to node \c t
432 432
    /// (i.e. the supply of \c s and the demand of \c t).
433 433
    ///
434 434
    /// \return <tt>(*this)</tt>
435 435
    CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
436 436
      for (int i = 0; i != _node_num; ++i) {
437 437
        _supply[i] = 0;
438 438
      }
439 439
      _supply[_node_id[s]] =  k;
440 440
      _supply[_node_id[t]] = -k;
441 441
      return *this;
442 442
    }
443 443

	
444 444
    /// @}
445 445

	
446 446
    /// \name Execution control
447 447
    /// The algorithm can be executed using \ref run().
448 448

	
449 449
    /// @{
450 450

	
451 451
    /// \brief Run the algorithm.
452 452
    ///
453 453
    /// This function runs the algorithm.
454 454
    /// The paramters can be specified using functions \ref lowerMap(),
455 455
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
456 456
    /// For example,
457 457
    /// \code
458 458
    ///   CapacityScaling<ListDigraph> cs(graph);
459 459
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
460 460
    ///     .supplyMap(sup).run();
461 461
    /// \endcode
462 462
    ///
463 463
    /// This function can be called more than once. All the given parameters
464 464
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
465 465
    /// is used, thus only the modified parameters have to be set again.
466 466
    /// If the underlying digraph was also modified after the construction
467 467
    /// of the class (or the last \ref reset() call), then the \ref reset()
468 468
    /// function must be called.
469 469
    ///
470 470
    /// \param factor The capacity scaling factor. It must be larger than
471 471
    /// one to use scaling. If it is less or equal to one, then scaling
472 472
    /// will be disabled.
473 473
    ///
474 474
    /// \return \c INFEASIBLE if no feasible flow exists,
475 475
    /// \n \c OPTIMAL if the problem has optimal solution
476 476
    /// (i.e. it is feasible and bounded), and the algorithm has found
477 477
    /// optimal flow and node potentials (primal and dual solutions),
478 478
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
479 479
    /// and infinite upper bound. It means that the objective function
480 480
    /// is unbounded on that arc, however, note that it could actually be
481 481
    /// bounded over the feasible flows, but this algroithm cannot handle
482 482
    /// these cases.
483 483
    ///
484 484
    /// \see ProblemType
485 485
    /// \see resetParams(), reset()
486 486
    ProblemType run(int factor = 4) {
487 487
      _factor = factor;
488 488
      ProblemType pt = init();
489 489
      if (pt != OPTIMAL) return pt;
490 490
      return start();
491 491
    }
492 492

	
493 493
    /// \brief Reset all the parameters that have been given before.
494 494
    ///
495 495
    /// This function resets all the paramaters that have been given
496 496
    /// before using functions \ref lowerMap(), \ref upperMap(),
497 497
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
498 498
    ///
499 499
    /// It is useful for multiple \ref run() calls. Basically, all the given
500 500
    /// parameters are kept for the next \ref run() call, unless
501 501
    /// \ref resetParams() or \ref reset() is used.
502 502
    /// If the underlying digraph was also modified after the construction
503 503
    /// of the class or the last \ref reset() call, then the \ref reset()
504 504
    /// function must be used, otherwise \ref resetParams() is sufficient.
505 505
    ///
506 506
    /// For example,
507 507
    /// \code
508 508
    ///   CapacityScaling<ListDigraph> cs(graph);
509 509
    ///
510 510
    ///   // First run
511 511
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
512 512
    ///     .supplyMap(sup).run();
513 513
    ///
514 514
    ///   // Run again with modified cost map (resetParams() is not called,
515 515
    ///   // so only the cost map have to be set again)
516 516
    ///   cost[e] += 100;
517 517
    ///   cs.costMap(cost).run();
518 518
    ///
519 519
    ///   // Run again from scratch using resetParams()
520 520
    ///   // (the lower bounds will be set to zero on all arcs)
521 521
    ///   cs.resetParams();
522 522
    ///   cs.upperMap(capacity).costMap(cost)
523 523
    ///     .supplyMap(sup).run();
524 524
    /// \endcode
525 525
    ///
526 526
    /// \return <tt>(*this)</tt>
527 527
    ///
528 528
    /// \see reset(), run()
529 529
    CapacityScaling& resetParams() {
530 530
      for (int i = 0; i != _node_num; ++i) {
531 531
        _supply[i] = 0;
532 532
      }
533 533
      for (int j = 0; j != _res_arc_num; ++j) {
534 534
        _lower[j] = 0;
535 535
        _upper[j] = INF;
536 536
        _cost[j] = _forward[j] ? 1 : -1;
537 537
      }
538 538
      _have_lower = false;
539 539
      return *this;
540 540
    }
541 541

	
542 542
    /// \brief Reset the internal data structures and all the parameters
543 543
    /// that have been given before.
544 544
    ///
545 545
    /// This function resets the internal data structures and all the
546 546
    /// paramaters that have been given before using functions \ref lowerMap(),
547 547
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
548 548
    ///
549 549
    /// It is useful for multiple \ref run() calls. Basically, all the given
550 550
    /// parameters are kept for the next \ref run() call, unless
551 551
    /// \ref resetParams() or \ref reset() is used.
552 552
    /// If the underlying digraph was also modified after the construction
553 553
    /// of the class or the last \ref reset() call, then the \ref reset()
554 554
    /// function must be used, otherwise \ref resetParams() is sufficient.
555 555
    ///
556 556
    /// See \ref resetParams() for examples.
557 557
    ///
558 558
    /// \return <tt>(*this)</tt>
559 559
    ///
560 560
    /// \see resetParams(), run()
561 561
    CapacityScaling& reset() {
562 562
      // Resize vectors
563 563
      _node_num = countNodes(_graph);
564 564
      _arc_num = countArcs(_graph);
565 565
      _res_arc_num = 2 * (_arc_num + _node_num);
566 566
      _root = _node_num;
567 567
      ++_node_num;
568 568

	
569 569
      _first_out.resize(_node_num + 1);
570 570
      _forward.resize(_res_arc_num);
571 571
      _source.resize(_res_arc_num);
572 572
      _target.resize(_res_arc_num);
573 573
      _reverse.resize(_res_arc_num);
574 574

	
575 575
      _lower.resize(_res_arc_num);
576 576
      _upper.resize(_res_arc_num);
577 577
      _cost.resize(_res_arc_num);
578 578
      _supply.resize(_node_num);
579 579

	
580 580
      _res_cap.resize(_res_arc_num);
581 581
      _pi.resize(_node_num);
582 582
      _excess.resize(_node_num);
583 583
      _pred.resize(_node_num);
584 584

	
585 585
      // Copy the graph
586 586
      int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
587 587
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
588 588
        _node_id[n] = i;
589 589
      }
590 590
      i = 0;
591 591
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
592 592
        _first_out[i] = j;
593 593
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
594 594
          _arc_idf[a] = j;
595 595
          _forward[j] = true;
596 596
          _source[j] = i;
597 597
          _target[j] = _node_id[_graph.runningNode(a)];
598 598
        }
599 599
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
600 600
          _arc_idb[a] = j;
601 601
          _forward[j] = false;
602 602
          _source[j] = i;
603 603
          _target[j] = _node_id[_graph.runningNode(a)];
604 604
        }
605 605
        _forward[j] = false;
606 606
        _source[j] = i;
607 607
        _target[j] = _root;
608 608
        _reverse[j] = k;
609 609
        _forward[k] = true;
610 610
        _source[k] = _root;
611 611
        _target[k] = i;
612 612
        _reverse[k] = j;
613 613
        ++j; ++k;
614 614
      }
615 615
      _first_out[i] = j;
616 616
      _first_out[_node_num] = k;
617 617
      for (ArcIt a(_graph); a != INVALID; ++a) {
618 618
        int fi = _arc_idf[a];
619 619
        int bi = _arc_idb[a];
620 620
        _reverse[fi] = bi;
621 621
        _reverse[bi] = fi;
622 622
      }
623 623

	
624 624
      // Reset parameters
625 625
      resetParams();
626 626
      return *this;
627 627
    }
628 628

	
629 629
    /// @}
630 630

	
631 631
    /// \name Query Functions
632 632
    /// The results of the algorithm can be obtained using these
633 633
    /// functions.\n
634 634
    /// The \ref run() function must be called before using them.
635 635

	
636 636
    /// @{
637 637

	
638 638
    /// \brief Return the total cost of the found flow.
639 639
    ///
640 640
    /// This function returns the total cost of the found flow.
641 641
    /// Its complexity is O(e).
642 642
    ///
643 643
    /// \note The return type of the function can be specified as a
644 644
    /// template parameter. For example,
645 645
    /// \code
646 646
    ///   cs.totalCost<double>();
647 647
    /// \endcode
648 648
    /// It is useful if the total cost cannot be stored in the \c Cost
649 649
    /// type of the algorithm, which is the default return type of the
650 650
    /// function.
651 651
    ///
652 652
    /// \pre \ref run() must be called before using this function.
653 653
    template <typename Number>
654 654
    Number totalCost() const {
655 655
      Number c = 0;
656 656
      for (ArcIt a(_graph); a != INVALID; ++a) {
657 657
        int i = _arc_idb[a];
658 658
        c += static_cast<Number>(_res_cap[i]) *
659 659
             (-static_cast<Number>(_cost[i]));
660 660
      }
661 661
      return c;
662 662
    }
663 663

	
664 664
#ifndef DOXYGEN
665 665
    Cost totalCost() const {
666 666
      return totalCost<Cost>();
667 667
    }
668 668
#endif
669 669

	
670 670
    /// \brief Return the flow on the given arc.
671 671
    ///
672 672
    /// This function returns the flow on the given arc.
673 673
    ///
674 674
    /// \pre \ref run() must be called before using this function.
675 675
    Value flow(const Arc& a) const {
676 676
      return _res_cap[_arc_idb[a]];
677 677
    }
678 678

	
679 679
    /// \brief Return the flow map (the primal solution).
680 680
    ///
681 681
    /// This function copies the flow value on each arc into the given
682 682
    /// map. The \c Value type of the algorithm must be convertible to
683 683
    /// the \c Value type of the map.
684 684
    ///
685 685
    /// \pre \ref run() must be called before using this function.
686 686
    template <typename FlowMap>
687 687
    void flowMap(FlowMap &map) const {
688 688
      for (ArcIt a(_graph); a != INVALID; ++a) {
689 689
        map.set(a, _res_cap[_arc_idb[a]]);
690 690
      }
691 691
    }
692 692

	
693 693
    /// \brief Return the potential (dual value) of the given node.
694 694
    ///
695 695
    /// This function returns the potential (dual value) of the
696 696
    /// given node.
697 697
    ///
698 698
    /// \pre \ref run() must be called before using this function.
699 699
    Cost potential(const Node& n) const {
700 700
      return _pi[_node_id[n]];
701 701
    }
702 702

	
703 703
    /// \brief Return the potential map (the dual solution).
704 704
    ///
705 705
    /// This function copies the potential (dual value) of each node
706 706
    /// into the given map.
707 707
    /// The \c Cost type of the algorithm must be convertible to the
708 708
    /// \c Value type of the map.
709 709
    ///
710 710
    /// \pre \ref run() must be called before using this function.
711 711
    template <typename PotentialMap>
712 712
    void potentialMap(PotentialMap &map) const {
713 713
      for (NodeIt n(_graph); n != INVALID; ++n) {
714 714
        map.set(n, _pi[_node_id[n]]);
715 715
      }
716 716
    }
717 717

	
718 718
    /// @}
719 719

	
720 720
  private:
721 721

	
722 722
    // Initialize the algorithm
723 723
    ProblemType init() {
724 724
      if (_node_num <= 1) return INFEASIBLE;
725 725

	
726 726
      // Check the sum of supply values
727 727
      _sum_supply = 0;
728 728
      for (int i = 0; i != _root; ++i) {
729 729
        _sum_supply += _supply[i];
730 730
      }
731 731
      if (_sum_supply > 0) return INFEASIBLE;
732 732

	
733 733
      // Initialize vectors
734 734
      for (int i = 0; i != _root; ++i) {
735 735
        _pi[i] = 0;
736 736
        _excess[i] = _supply[i];
737 737
      }
738 738

	
739 739
      // Remove non-zero lower bounds
740 740
      const Value MAX = std::numeric_limits<Value>::max();
741 741
      int last_out;
742 742
      if (_have_lower) {
743 743
        for (int i = 0; i != _root; ++i) {
744 744
          last_out = _first_out[i+1];
745 745
          for (int j = _first_out[i]; j != last_out; ++j) {
746 746
            if (_forward[j]) {
747 747
              Value c = _lower[j];
748 748
              if (c >= 0) {
749 749
                _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
750 750
              } else {
751 751
                _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
752 752
              }
753 753
              _excess[i] -= c;
754 754
              _excess[_target[j]] += c;
755 755
            } else {
756 756
              _res_cap[j] = 0;
757 757
            }
758 758
          }
759 759
        }
760 760
      } else {
761 761
        for (int j = 0; j != _res_arc_num; ++j) {
762 762
          _res_cap[j] = _forward[j] ? _upper[j] : 0;
763 763
        }
764 764
      }
765 765

	
766 766
      // Handle negative costs
767 767
      for (int i = 0; i != _root; ++i) {
768 768
        last_out = _first_out[i+1] - 1;
769 769
        for (int j = _first_out[i]; j != last_out; ++j) {
770 770
          Value rc = _res_cap[j];
771 771
          if (_cost[j] < 0 && rc > 0) {
772 772
            if (rc >= MAX) return UNBOUNDED;
773 773
            _excess[i] -= rc;
774 774
            _excess[_target[j]] += rc;
775 775
            _res_cap[j] = 0;
776 776
            _res_cap[_reverse[j]] += rc;
777 777
          }
778 778
        }
779 779
      }
780 780

	
781 781
      // Handle GEQ supply type
782 782
      if (_sum_supply < 0) {
783 783
        _pi[_root] = 0;
784 784
        _excess[_root] = -_sum_supply;
785 785
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
786 786
          int ra = _reverse[a];
787 787
          _res_cap[a] = -_sum_supply + 1;
788 788
          _res_cap[ra] = 0;
789 789
          _cost[a] = 0;
790 790
          _cost[ra] = 0;
791 791
        }
792 792
      } else {
793 793
        _pi[_root] = 0;
794 794
        _excess[_root] = 0;
795 795
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
796 796
          int ra = _reverse[a];
797 797
          _res_cap[a] = 1;
798 798
          _res_cap[ra] = 0;
799 799
          _cost[a] = 0;
800 800
          _cost[ra] = 0;
801 801
        }
802 802
      }
803 803

	
804 804
      // Initialize delta value
805 805
      if (_factor > 1) {
806 806
        // With scaling
807 807
        Value max_sup = 0, max_dem = 0, max_cap = 0;
808 808
        for (int i = 0; i != _root; ++i) {
809 809
          Value ex = _excess[i];
810 810
          if ( ex > max_sup) max_sup =  ex;
811 811
          if (-ex > max_dem) max_dem = -ex;
812 812
          int last_out = _first_out[i+1] - 1;
813 813
          for (int j = _first_out[i]; j != last_out; ++j) {
814 814
            if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
815 815
          }
816 816
        }
817 817
        max_sup = std::min(std::min(max_sup, max_dem), max_cap);
818 818
        for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
819 819
      } else {
820 820
        // Without scaling
821 821
        _delta = 1;
822 822
      }
823 823

	
824 824
      return OPTIMAL;
825 825
    }
826 826

	
827 827
    ProblemType start() {
828 828
      // Execute the algorithm
829 829
      ProblemType pt;
830 830
      if (_delta > 1)
831 831
        pt = startWithScaling();
832 832
      else
833 833
        pt = startWithoutScaling();
834 834

	
835 835
      // Handle non-zero lower bounds
836 836
      if (_have_lower) {
837 837
        int limit = _first_out[_root];
838 838
        for (int j = 0; j != limit; ++j) {
839 839
          if (!_forward[j]) _res_cap[j] += _lower[j];
840 840
        }
841 841
      }
842 842

	
843 843
      // Shift potentials if necessary
844 844
      Cost pr = _pi[_root];
845 845
      if (_sum_supply < 0 || pr > 0) {
846 846
        for (int i = 0; i != _node_num; ++i) {
847 847
          _pi[i] -= pr;
848 848
        }
849 849
      }
850 850

	
851 851
      return pt;
852 852
    }
853 853

	
854 854
    // Execute the capacity scaling algorithm
855 855
    ProblemType startWithScaling() {
856 856
      // Perform capacity scaling phases
857 857
      int s, t;
858 858
      ResidualDijkstra _dijkstra(*this);
859 859
      while (true) {
860 860
        // Saturate all arcs not satisfying the optimality condition
861 861
        int last_out;
862 862
        for (int u = 0; u != _node_num; ++u) {
863 863
          last_out = _sum_supply < 0 ?
864 864
            _first_out[u+1] : _first_out[u+1] - 1;
865 865
          for (int a = _first_out[u]; a != last_out; ++a) {
866 866
            int v = _target[a];
867 867
            Cost c = _cost[a] + _pi[u] - _pi[v];
868 868
            Value rc = _res_cap[a];
869 869
            if (c < 0 && rc >= _delta) {
870 870
              _excess[u] -= rc;
871 871
              _excess[v] += rc;
872 872
              _res_cap[a] = 0;
873 873
              _res_cap[_reverse[a]] += rc;
874 874
            }
875 875
          }
876 876
        }
877 877

	
878 878
        // Find excess nodes and deficit nodes
879 879
        _excess_nodes.clear();
880 880
        _deficit_nodes.clear();
881 881
        for (int u = 0; u != _node_num; ++u) {
882 882
          Value ex = _excess[u];
883 883
          if (ex >=  _delta) _excess_nodes.push_back(u);
884 884
          if (ex <= -_delta) _deficit_nodes.push_back(u);
885 885
        }
886 886
        int next_node = 0, next_def_node = 0;
887 887

	
888 888
        // Find augmenting shortest paths
889 889
        while (next_node < int(_excess_nodes.size())) {
890 890
          // Check deficit nodes
891 891
          if (_delta > 1) {
892 892
            bool delta_deficit = false;
893 893
            for ( ; next_def_node < int(_deficit_nodes.size());
894 894
                    ++next_def_node ) {
895 895
              if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
896 896
                delta_deficit = true;
897 897
                break;
898 898
              }
899 899
            }
900 900
            if (!delta_deficit) break;
901 901
          }
902 902

	
903 903
          // Run Dijkstra in the residual network
904 904
          s = _excess_nodes[next_node];
905 905
          if ((t = _dijkstra.run(s, _delta)) == -1) {
906 906
            if (_delta > 1) {
907 907
              ++next_node;
908 908
              continue;
909 909
            }
910 910
            return INFEASIBLE;
911 911
          }
912 912

	
913 913
          // Augment along a shortest path from s to t
914 914
          Value d = std::min(_excess[s], -_excess[t]);
915 915
          int u = t;
916 916
          int a;
917 917
          if (d > _delta) {
918 918
            while ((a = _pred[u]) != -1) {
919 919
              if (_res_cap[a] < d) d = _res_cap[a];
920 920
              u = _source[a];
921 921
            }
922 922
          }
923 923
          u = t;
924 924
          while ((a = _pred[u]) != -1) {
925 925
            _res_cap[a] -= d;
926 926
            _res_cap[_reverse[a]] += d;
927 927
            u = _source[a];
928 928
          }
929 929
          _excess[s] -= d;
930 930
          _excess[t] += d;
931 931

	
932 932
          if (_excess[s] < _delta) ++next_node;
933 933
        }
934 934

	
935 935
        if (_delta == 1) break;
936 936
        _delta = _delta <= _factor ? 1 : _delta / _factor;
937 937
      }
938 938

	
939 939
      return OPTIMAL;
940 940
    }
941 941

	
942 942
    // Execute the successive shortest path algorithm
943 943
    ProblemType startWithoutScaling() {
944 944
      // Find excess nodes
945 945
      _excess_nodes.clear();
946 946
      for (int i = 0; i != _node_num; ++i) {
947 947
        if (_excess[i] > 0) _excess_nodes.push_back(i);
948 948
      }
949 949
      if (_excess_nodes.size() == 0) return OPTIMAL;
950 950
      int next_node = 0;
951 951

	
952 952
      // Find shortest paths
953 953
      int s, t;
954 954
      ResidualDijkstra _dijkstra(*this);
955 955
      while ( _excess[_excess_nodes[next_node]] > 0 ||
956 956
              ++next_node < int(_excess_nodes.size()) )
957 957
      {
958 958
        // Run Dijkstra in the residual network
959 959
        s = _excess_nodes[next_node];
960 960
        if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
961 961

	
962 962
        // Augment along a shortest path from s to t
963 963
        Value d = std::min(_excess[s], -_excess[t]);
964 964
        int u = t;
965 965
        int a;
966 966
        if (d > 1) {
967 967
          while ((a = _pred[u]) != -1) {
968 968
            if (_res_cap[a] < d) d = _res_cap[a];
969 969
            u = _source[a];
970 970
          }
971 971
        }
972 972
        u = t;
973 973
        while ((a = _pred[u]) != -1) {
974 974
          _res_cap[a] -= d;
975 975
          _res_cap[_reverse[a]] += d;
976 976
          u = _source[a];
977 977
        }
978 978
        _excess[s] -= d;
979 979
        _excess[t] += d;
980 980
      }
981 981

	
982 982
      return OPTIMAL;
983 983
    }
984 984

	
985 985
  }; //class CapacityScaling
986 986

	
987 987
  ///@}
988 988

	
989 989
} //namespace lemon
990 990

	
991 991
#endif //LEMON_CAPACITY_SCALING_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_NETWORK_SIMPLEX_H
20 20
#define LEMON_NETWORK_SIMPLEX_H
21 21

	
22 22
/// \ingroup min_cost_flow_algs
23 23
///
24 24
/// \file
25 25
/// \brief Network Simplex algorithm for finding a minimum cost flow.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <algorithm>
30 30

	
31 31
#include <lemon/core.h>
32 32
#include <lemon/math.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \addtogroup min_cost_flow_algs
37 37
  /// @{
38 38

	
39 39
  /// \brief Implementation of the primal Network Simplex algorithm
40 40
  /// for finding a \ref min_cost_flow "minimum cost flow".
41 41
  ///
42 42
  /// \ref NetworkSimplex implements the primal Network Simplex algorithm
43 43
  /// for finding a \ref min_cost_flow "minimum cost flow"
44 44
  /// \ref amo93networkflows, \ref dantzig63linearprog,
45 45
  /// \ref kellyoneill91netsimplex.
46 46
  /// This algorithm is a highly efficient specialized version of the
47 47
  /// linear programming simplex method directly for the minimum cost
48 48
  /// flow problem.
49 49
  ///
50 50
  /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
51 51
  /// implementations available in LEMON for this problem.
52 52
  /// Furthermore, this class supports both directions of the supply/demand
53 53
  /// inequality constraints. For more information, see \ref SupplyType.
54 54
  ///
55 55
  /// Most of the parameters of the problem (except for the digraph)
56 56
  /// can be given using separate functions, and the algorithm can be
57 57
  /// executed using the \ref run() function. If some parameters are not
58 58
  /// specified, then default values will be used.
59 59
  ///
60 60
  /// \tparam GR The digraph type the algorithm runs on.
61 61
  /// \tparam V The number type used for flow amounts, capacity bounds
62 62
  /// and supply values in the algorithm. By default, it is \c int.
63 63
  /// \tparam C The number type used for costs and potentials in the
64 64
  /// algorithm. By default, it is the same as \c V.
65 65
  ///
66 66
  /// \warning Both \c V and \c C must be signed number types.
67 67
  /// \warning All input data (capacities, supply values, and costs) must
68 68
  /// be integer.
69 69
  ///
70 70
  /// \note %NetworkSimplex provides five different pivot rule
71 71
  /// implementations, from which the most efficient one is used
72 72
  /// by default. For more information, see \ref PivotRule.
73 73
  template <typename GR, typename V = int, typename C = V>
74 74
  class NetworkSimplex
75 75
  {
76 76
  public:
77 77

	
78 78
    /// The type of the flow amounts, capacity bounds and supply values
79 79
    typedef V Value;
80 80
    /// The type of the arc costs
81 81
    typedef C Cost;
82 82

	
83 83
  public:
84 84

	
85 85
    /// \brief Problem type constants for the \c run() function.
86 86
    ///
87 87
    /// Enum type containing the problem type constants that can be
88 88
    /// returned by the \ref run() function of the algorithm.
89 89
    enum ProblemType {
90 90
      /// The problem has no feasible solution (flow).
91 91
      INFEASIBLE,
92 92
      /// The problem has optimal solution (i.e. it is feasible and
93 93
      /// bounded), and the algorithm has found optimal flow and node
94 94
      /// potentials (primal and dual solutions).
95 95
      OPTIMAL,
96 96
      /// The objective function of the problem is unbounded, i.e.
97 97
      /// there is a directed cycle having negative total cost and
98 98
      /// infinite upper bound.
99 99
      UNBOUNDED
100 100
    };
101 101

	
102 102
    /// \brief Constants for selecting the type of the supply constraints.
103 103
    ///
104 104
    /// Enum type containing constants for selecting the supply type,
105 105
    /// i.e. the direction of the inequalities in the supply/demand
106 106
    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
107 107
    ///
108 108
    /// The default supply type is \c GEQ, the \c LEQ type can be
109 109
    /// selected using \ref supplyType().
110 110
    /// The equality form is a special case of both supply types.
111 111
    enum SupplyType {
112 112
      /// This option means that there are <em>"greater or equal"</em>
113 113
      /// supply/demand constraints in the definition of the problem.
114 114
      GEQ,
115 115
      /// This option means that there are <em>"less or equal"</em>
116 116
      /// supply/demand constraints in the definition of the problem.
117 117
      LEQ
118 118
    };
119 119

	
120 120
    /// \brief Constants for selecting the pivot rule.
121 121
    ///
122 122
    /// Enum type containing constants for selecting the pivot rule for
123 123
    /// the \ref run() function.
124 124
    ///
125
    /// \ref NetworkSimplex provides five different pivot rule
126
    /// implementations that significantly affect the running time
125
    /// \ref NetworkSimplex provides five different implementations for
126
    /// the pivot strategy that significantly affects the running time
127 127
    /// of the algorithm.
128
    /// By default, \ref BLOCK_SEARCH "Block Search" is used, which
129
    /// turend out to be the most efficient and the most robust on various
130
    /// test inputs.
131
    /// However, another pivot rule can be selected using the \ref run()
132
    /// function with the proper parameter.
128
    /// According to experimental tests conducted on various problem
129
    /// instances, \ref BLOCK_SEARCH "Block Search" and
130
    /// \ref ALTERING_LIST "Altering Candidate List" rules turned out
131
    /// to be the most efficient.
132
    /// Since \ref BLOCK_SEARCH "Block Search" is a simpler strategy that
133
    /// seemed to be slightly more robust, it is used by default.
134
    /// However, another pivot rule can easily be selected using the
135
    /// \ref run() function with the proper parameter.
133 136
    enum PivotRule {
134 137

	
135 138
      /// The \e First \e Eligible pivot rule.
136 139
      /// The next eligible arc is selected in a wraparound fashion
137 140
      /// in every iteration.
138 141
      FIRST_ELIGIBLE,
139 142

	
140 143
      /// The \e Best \e Eligible pivot rule.
141 144
      /// The best eligible arc is selected in every iteration.
142 145
      BEST_ELIGIBLE,
143 146

	
144 147
      /// The \e Block \e Search pivot rule.
145 148
      /// A specified number of arcs are examined in every iteration
146 149
      /// in a wraparound fashion and the best eligible arc is selected
147 150
      /// from this block.
148 151
      BLOCK_SEARCH,
149 152

	
150 153
      /// The \e Candidate \e List pivot rule.
151 154
      /// In a major iteration a candidate list is built from eligible arcs
152 155
      /// in a wraparound fashion and in the following minor iterations
153 156
      /// the best eligible arc is selected from this list.
154 157
      CANDIDATE_LIST,
155 158

	
156 159
      /// The \e Altering \e Candidate \e List pivot rule.
157 160
      /// It is a modified version of the Candidate List method.
158
      /// It keeps only the several best eligible arcs from the former
161
      /// It keeps only a few of the best eligible arcs from the former
159 162
      /// candidate list and extends this list in every iteration.
160 163
      ALTERING_LIST
161 164
    };
162 165

	
163 166
  private:
164 167

	
165 168
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
166 169

	
167 170
    typedef std::vector<int> IntVector;
168 171
    typedef std::vector<Value> ValueVector;
169 172
    typedef std::vector<Cost> CostVector;
170 173
    typedef std::vector<signed char> CharVector;
171 174
    // Note: vector<signed char> is used instead of vector<ArcState> and
172 175
    // vector<ArcDirection> for efficiency reasons
173 176

	
174 177
    // State constants for arcs
175 178
    enum ArcState {
176 179
      STATE_UPPER = -1,
177 180
      STATE_TREE  =  0,
178 181
      STATE_LOWER =  1
179 182
    };
180 183

	
181 184
    // Direction constants for tree arcs
182 185
    enum ArcDirection {
183 186
      DIR_DOWN = -1,
184 187
      DIR_UP   =  1
185 188
    };
186 189

	
187 190
  private:
188 191

	
189 192
    // Data related to the underlying digraph
190 193
    const GR &_graph;
191 194
    int _node_num;
192 195
    int _arc_num;
193 196
    int _all_arc_num;
194 197
    int _search_arc_num;
195 198

	
196 199
    // Parameters of the problem
197 200
    bool _have_lower;
198 201
    SupplyType _stype;
199 202
    Value _sum_supply;
200 203

	
201 204
    // Data structures for storing the digraph
202 205
    IntNodeMap _node_id;
203 206
    IntArcMap _arc_id;
204 207
    IntVector _source;
205 208
    IntVector _target;
206 209
    bool _arc_mixing;
207 210

	
208 211
    // Node and arc data
209 212
    ValueVector _lower;
210 213
    ValueVector _upper;
211 214
    ValueVector _cap;
212 215
    CostVector _cost;
213 216
    ValueVector _supply;
214 217
    ValueVector _flow;
215 218
    CostVector _pi;
216 219

	
217 220
    // Data for storing the spanning tree structure
218 221
    IntVector _parent;
219 222
    IntVector _pred;
220 223
    IntVector _thread;
221 224
    IntVector _rev_thread;
222 225
    IntVector _succ_num;
223 226
    IntVector _last_succ;
224 227
    CharVector _pred_dir;
225 228
    CharVector _state;
226 229
    IntVector _dirty_revs;
227 230
    int _root;
228 231

	
229 232
    // Temporary data used in the current pivot iteration
230 233
    int in_arc, join, u_in, v_in, u_out, v_out;
231 234
    Value delta;
232 235

	
233 236
    const Value MAX;
234 237

	
235 238
  public:
236 239

	
237 240
    /// \brief Constant for infinite upper bounds (capacities).
238 241
    ///
239 242
    /// Constant for infinite upper bounds (capacities).
240 243
    /// It is \c std::numeric_limits<Value>::infinity() if available,
241 244
    /// \c std::numeric_limits<Value>::max() otherwise.
242 245
    const Value INF;
243 246

	
244 247
  private:
245 248

	
246 249
    // Implementation of the First Eligible pivot rule
247 250
    class FirstEligiblePivotRule
248 251
    {
249 252
    private:
250 253

	
251 254
      // References to the NetworkSimplex class
252 255
      const IntVector  &_source;
253 256
      const IntVector  &_target;
254 257
      const CostVector &_cost;
255 258
      const CharVector &_state;
256 259
      const CostVector &_pi;
257 260
      int &_in_arc;
258 261
      int _search_arc_num;
259 262

	
260 263
      // Pivot rule data
261 264
      int _next_arc;
262 265

	
263 266
    public:
264 267

	
265 268
      // Constructor
266 269
      FirstEligiblePivotRule(NetworkSimplex &ns) :
267 270
        _source(ns._source), _target(ns._target),
268 271
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
269 272
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
270 273
        _next_arc(0)
271 274
      {}
272 275

	
273 276
      // Find next entering arc
274 277
      bool findEnteringArc() {
275 278
        Cost c;
276 279
        for (int e = _next_arc; e != _search_arc_num; ++e) {
277 280
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
278 281
          if (c < 0) {
279 282
            _in_arc = e;
280 283
            _next_arc = e + 1;
281 284
            return true;
282 285
          }
283 286
        }
284 287
        for (int e = 0; e != _next_arc; ++e) {
285 288
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
286 289
          if (c < 0) {
287 290
            _in_arc = e;
288 291
            _next_arc = e + 1;
289 292
            return true;
290 293
          }
291 294
        }
292 295
        return false;
293 296
      }
294 297

	
295 298
    }; //class FirstEligiblePivotRule
296 299

	
297 300

	
298 301
    // Implementation of the Best Eligible pivot rule
299 302
    class BestEligiblePivotRule
300 303
    {
301 304
    private:
302 305

	
303 306
      // References to the NetworkSimplex class
304 307
      const IntVector  &_source;
305 308
      const IntVector  &_target;
306 309
      const CostVector &_cost;
307 310
      const CharVector &_state;
308 311
      const CostVector &_pi;
309 312
      int &_in_arc;
310 313
      int _search_arc_num;
311 314

	
312 315
    public:
313 316

	
314 317
      // Constructor
315 318
      BestEligiblePivotRule(NetworkSimplex &ns) :
316 319
        _source(ns._source), _target(ns._target),
317 320
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
318 321
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
319 322
      {}
320 323

	
321 324
      // Find next entering arc
322 325
      bool findEnteringArc() {
323 326
        Cost c, min = 0;
324 327
        for (int e = 0; e != _search_arc_num; ++e) {
325 328
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
326 329
          if (c < min) {
327 330
            min = c;
328 331
            _in_arc = e;
329 332
          }
330 333
        }
331 334
        return min < 0;
332 335
      }
333 336

	
334 337
    }; //class BestEligiblePivotRule
335 338

	
336 339

	
337 340
    // Implementation of the Block Search pivot rule
338 341
    class BlockSearchPivotRule
339 342
    {
340 343
    private:
341 344

	
342 345
      // References to the NetworkSimplex class
343 346
      const IntVector  &_source;
344 347
      const IntVector  &_target;
345 348
      const CostVector &_cost;
346 349
      const CharVector &_state;
347 350
      const CostVector &_pi;
348 351
      int &_in_arc;
349 352
      int _search_arc_num;
350 353

	
351 354
      // Pivot rule data
352 355
      int _block_size;
353 356
      int _next_arc;
354 357

	
355 358
    public:
356 359

	
357 360
      // Constructor
358 361
      BlockSearchPivotRule(NetworkSimplex &ns) :
359 362
        _source(ns._source), _target(ns._target),
360 363
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
361 364
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
362 365
        _next_arc(0)
363 366
      {
364 367
        // The main parameters of the pivot rule
365 368
        const double BLOCK_SIZE_FACTOR = 1.0;
366 369
        const int MIN_BLOCK_SIZE = 10;
367 370

	
368 371
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
369 372
                                    std::sqrt(double(_search_arc_num))),
370 373
                                MIN_BLOCK_SIZE );
371 374
      }
372 375

	
373 376
      // Find next entering arc
374 377
      bool findEnteringArc() {
375 378
        Cost c, min = 0;
376 379
        int cnt = _block_size;
377 380
        int e;
378 381
        for (e = _next_arc; e != _search_arc_num; ++e) {
379 382
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
380 383
          if (c < min) {
381 384
            min = c;
382 385
            _in_arc = e;
383 386
          }
384 387
          if (--cnt == 0) {
385 388
            if (min < 0) goto search_end;
386 389
            cnt = _block_size;
387 390
          }
388 391
        }
389 392
        for (e = 0; e != _next_arc; ++e) {
390 393
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
391 394
          if (c < min) {
392 395
            min = c;
393 396
            _in_arc = e;
394 397
          }
395 398
          if (--cnt == 0) {
396 399
            if (min < 0) goto search_end;
397 400
            cnt = _block_size;
398 401
          }
399 402
        }
400 403
        if (min >= 0) return false;
401 404

	
402 405
      search_end:
403 406
        _next_arc = e;
404 407
        return true;
405 408
      }
406 409

	
407 410
    }; //class BlockSearchPivotRule
408 411

	
409 412

	
410 413
    // Implementation of the Candidate List pivot rule
411 414
    class CandidateListPivotRule
412 415
    {
413 416
    private:
414 417

	
415 418
      // References to the NetworkSimplex class
416 419
      const IntVector  &_source;
417 420
      const IntVector  &_target;
418 421
      const CostVector &_cost;
419 422
      const CharVector &_state;
420 423
      const CostVector &_pi;
421 424
      int &_in_arc;
422 425
      int _search_arc_num;
423 426

	
424 427
      // Pivot rule data
425 428
      IntVector _candidates;
426 429
      int _list_length, _minor_limit;
427 430
      int _curr_length, _minor_count;
428 431
      int _next_arc;
429 432

	
430 433
    public:
431 434

	
432 435
      /// Constructor
433 436
      CandidateListPivotRule(NetworkSimplex &ns) :
434 437
        _source(ns._source), _target(ns._target),
435 438
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
436 439
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
437 440
        _next_arc(0)
438 441
      {
439 442
        // The main parameters of the pivot rule
440 443
        const double LIST_LENGTH_FACTOR = 0.25;
441 444
        const int MIN_LIST_LENGTH = 10;
442 445
        const double MINOR_LIMIT_FACTOR = 0.1;
443 446
        const int MIN_MINOR_LIMIT = 3;
444 447

	
445 448
        _list_length = std::max( int(LIST_LENGTH_FACTOR *
446 449
                                     std::sqrt(double(_search_arc_num))),
447 450
                                 MIN_LIST_LENGTH );
448 451
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
449 452
                                 MIN_MINOR_LIMIT );
450 453
        _curr_length = _minor_count = 0;
451 454
        _candidates.resize(_list_length);
452 455
      }
453 456

	
454 457
      /// Find next entering arc
455 458
      bool findEnteringArc() {
456 459
        Cost min, c;
457 460
        int e;
458 461
        if (_curr_length > 0 && _minor_count < _minor_limit) {
459 462
          // Minor iteration: select the best eligible arc from the
460 463
          // current candidate list
461 464
          ++_minor_count;
462 465
          min = 0;
463 466
          for (int i = 0; i < _curr_length; ++i) {
464 467
            e = _candidates[i];
465 468
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
466 469
            if (c < min) {
467 470
              min = c;
468 471
              _in_arc = e;
469 472
            }
470 473
            else if (c >= 0) {
471 474
              _candidates[i--] = _candidates[--_curr_length];
472 475
            }
473 476
          }
474 477
          if (min < 0) return true;
475 478
        }
476 479

	
477 480
        // Major iteration: build a new candidate list
478 481
        min = 0;
479 482
        _curr_length = 0;
480 483
        for (e = _next_arc; e != _search_arc_num; ++e) {
481 484
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
482 485
          if (c < 0) {
483 486
            _candidates[_curr_length++] = e;
484 487
            if (c < min) {
485 488
              min = c;
486 489
              _in_arc = e;
487 490
            }
488 491
            if (_curr_length == _list_length) goto search_end;
489 492
          }
490 493
        }
491 494
        for (e = 0; e != _next_arc; ++e) {
492 495
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
493 496
          if (c < 0) {
494 497
            _candidates[_curr_length++] = e;
495 498
            if (c < min) {
496 499
              min = c;
497 500
              _in_arc = e;
498 501
            }
499 502
            if (_curr_length == _list_length) goto search_end;
500 503
          }
501 504
        }
502 505
        if (_curr_length == 0) return false;
503 506

	
504 507
      search_end:
505 508
        _minor_count = 1;
506 509
        _next_arc = e;
507 510
        return true;
508 511
      }
509 512

	
510 513
    }; //class CandidateListPivotRule
511 514

	
512 515

	
513 516
    // Implementation of the Altering Candidate List pivot rule
514 517
    class AlteringListPivotRule
515 518
    {
516 519
    private:
517 520

	
518 521
      // References to the NetworkSimplex class
519 522
      const IntVector  &_source;
520 523
      const IntVector  &_target;
521 524
      const CostVector &_cost;
522 525
      const CharVector &_state;
523 526
      const CostVector &_pi;
524 527
      int &_in_arc;
525 528
      int _search_arc_num;
526 529

	
527 530
      // Pivot rule data
528 531
      int _block_size, _head_length, _curr_length;
529 532
      int _next_arc;
530 533
      IntVector _candidates;
531 534
      CostVector _cand_cost;
532 535

	
533 536
      // Functor class to compare arcs during sort of the candidate list
534 537
      class SortFunc
535 538
      {
536 539
      private:
537 540
        const CostVector &_map;
538 541
      public:
539 542
        SortFunc(const CostVector &map) : _map(map) {}
540 543
        bool operator()(int left, int right) {
541
          return _map[left] > _map[right];
544
          return _map[left] < _map[right];
542 545
        }
543 546
      };
544 547

	
545 548
      SortFunc _sort_func;
546 549

	
547 550
    public:
548 551

	
549 552
      // Constructor
550 553
      AlteringListPivotRule(NetworkSimplex &ns) :
551 554
        _source(ns._source), _target(ns._target),
552 555
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
553 556
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
554 557
        _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
555 558
      {
556 559
        // The main parameters of the pivot rule
557 560
        const double BLOCK_SIZE_FACTOR = 1.0;
558 561
        const int MIN_BLOCK_SIZE = 10;
559
        const double HEAD_LENGTH_FACTOR = 0.1;
562
        const double HEAD_LENGTH_FACTOR = 0.01;
560 563
        const int MIN_HEAD_LENGTH = 3;
561 564

	
562 565
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
563 566
                                    std::sqrt(double(_search_arc_num))),
564 567
                                MIN_BLOCK_SIZE );
565 568
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
566 569
                                 MIN_HEAD_LENGTH );
567 570
        _candidates.resize(_head_length + _block_size);
568 571
        _curr_length = 0;
569 572
      }
570 573

	
571 574
      // Find next entering arc
572 575
      bool findEnteringArc() {
573 576
        // Check the current candidate list
574 577
        int e;
575 578
        Cost c;
576 579
        for (int i = 0; i != _curr_length; ++i) {
577 580
          e = _candidates[i];
578 581
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
579 582
          if (c < 0) {
580 583
            _cand_cost[e] = c;
581 584
          } else {
582 585
            _candidates[i--] = _candidates[--_curr_length];
583 586
          }
584 587
        }
585 588

	
586 589
        // Extend the list
587 590
        int cnt = _block_size;
588 591
        int limit = _head_length;
589 592

	
590 593
        for (e = _next_arc; e != _search_arc_num; ++e) {
591 594
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
592 595
          if (c < 0) {
593 596
            _cand_cost[e] = c;
594 597
            _candidates[_curr_length++] = e;
595 598
          }
596 599
          if (--cnt == 0) {
597 600
            if (_curr_length > limit) goto search_end;
598 601
            limit = 0;
599 602
            cnt = _block_size;
600 603
          }
601 604
        }
602 605
        for (e = 0; e != _next_arc; ++e) {
603
          _cand_cost[e] = _state[e] *
604
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
605
          if (_cand_cost[e] < 0) {
606
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
607
          if (c < 0) {
608
            _cand_cost[e] = c;
606 609
            _candidates[_curr_length++] = e;
607 610
          }
608 611
          if (--cnt == 0) {
609 612
            if (_curr_length > limit) goto search_end;
610 613
            limit = 0;
611 614
            cnt = _block_size;
612 615
          }
613 616
        }
614 617
        if (_curr_length == 0) return false;
615 618

	
616 619
      search_end:
617 620

	
618
        // Make heap of the candidate list (approximating a partial sort)
619
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
620
                   _sort_func );
621
        // Perform partial sort operation on the candidate list
622
        int new_length = std::min(_head_length + 1, _curr_length);
623
        std::partial_sort(_candidates.begin(), _candidates.begin() + new_length,
624
                          _candidates.begin() + _curr_length, _sort_func);
621 625

	
622
        // Pop the first element of the heap
626
        // Select the entering arc and remove it from the list
623 627
        _in_arc = _candidates[0];
624 628
        _next_arc = e;
625
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
626
                  _sort_func );
627
        _curr_length = std::min(_head_length, _curr_length - 1);
629
        _candidates[0] = _candidates[new_length - 1];
630
        _curr_length = new_length - 1;
628 631
        return true;
629 632
      }
630 633

	
631 634
    }; //class AlteringListPivotRule
632 635

	
633 636
  public:
634 637

	
635 638
    /// \brief Constructor.
636 639
    ///
637 640
    /// The constructor of the class.
638 641
    ///
639 642
    /// \param graph The digraph the algorithm runs on.
640 643
    /// \param arc_mixing Indicate if the arcs will be stored in a
641 644
    /// mixed order in the internal data structure.
642 645
    /// In general, it leads to similar performance as using the original
643 646
    /// arc order, but it makes the algorithm more robust and in special
644 647
    /// cases, even significantly faster. Therefore, it is enabled by default.
645 648
    NetworkSimplex(const GR& graph, bool arc_mixing = true) :
646 649
      _graph(graph), _node_id(graph), _arc_id(graph),
647 650
      _arc_mixing(arc_mixing),
648 651
      MAX(std::numeric_limits<Value>::max()),
649 652
      INF(std::numeric_limits<Value>::has_infinity ?
650 653
          std::numeric_limits<Value>::infinity() : MAX)
651 654
    {
652 655
      // Check the number types
653 656
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
654 657
        "The flow type of NetworkSimplex must be signed");
655 658
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
656 659
        "The cost type of NetworkSimplex must be signed");
657 660

	
658 661
      // Reset data structures
659 662
      reset();
660 663
    }
661 664

	
662 665
    /// \name Parameters
663 666
    /// The parameters of the algorithm can be specified using these
664 667
    /// functions.
665 668

	
666 669
    /// @{
667 670

	
668 671
    /// \brief Set the lower bounds on the arcs.
669 672
    ///
670 673
    /// This function sets the lower bounds on the arcs.
671 674
    /// If it is not used before calling \ref run(), the lower bounds
672 675
    /// will be set to zero on all arcs.
673 676
    ///
674 677
    /// \param map An arc map storing the lower bounds.
675 678
    /// Its \c Value type must be convertible to the \c Value type
676 679
    /// of the algorithm.
677 680
    ///
678 681
    /// \return <tt>(*this)</tt>
679 682
    template <typename LowerMap>
680 683
    NetworkSimplex& lowerMap(const LowerMap& map) {
681 684
      _have_lower = true;
682 685
      for (ArcIt a(_graph); a != INVALID; ++a) {
683 686
        _lower[_arc_id[a]] = map[a];
684 687
      }
685 688
      return *this;
686 689
    }
687 690

	
688 691
    /// \brief Set the upper bounds (capacities) on the arcs.
689 692
    ///
690 693
    /// This function sets the upper bounds (capacities) on the arcs.
691 694
    /// If it is not used before calling \ref run(), the upper bounds
692 695
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
693 696
    /// unbounded from above).
694 697
    ///
695 698
    /// \param map An arc map storing the upper bounds.
696 699
    /// Its \c Value type must be convertible to the \c Value type
697 700
    /// of the algorithm.
698 701
    ///
699 702
    /// \return <tt>(*this)</tt>
700 703
    template<typename UpperMap>
701 704
    NetworkSimplex& upperMap(const UpperMap& map) {
702 705
      for (ArcIt a(_graph); a != INVALID; ++a) {
703 706
        _upper[_arc_id[a]] = map[a];
704 707
      }
705 708
      return *this;
706 709
    }
707 710

	
708 711
    /// \brief Set the costs of the arcs.
709 712
    ///
710 713
    /// This function sets the costs of the arcs.
711 714
    /// If it is not used before calling \ref run(), the costs
712 715
    /// will be set to \c 1 on all arcs.
713 716
    ///
714 717
    /// \param map An arc map storing the costs.
715 718
    /// Its \c Value type must be convertible to the \c Cost type
716 719
    /// of the algorithm.
717 720
    ///
718 721
    /// \return <tt>(*this)</tt>
719 722
    template<typename CostMap>
720 723
    NetworkSimplex& costMap(const CostMap& map) {
721 724
      for (ArcIt a(_graph); a != INVALID; ++a) {
722 725
        _cost[_arc_id[a]] = map[a];
723 726
      }
724 727
      return *this;
725 728
    }
726 729

	
727 730
    /// \brief Set the supply values of the nodes.
728 731
    ///
729 732
    /// This function sets the supply values of the nodes.
730 733
    /// If neither this function nor \ref stSupply() is used before
731 734
    /// calling \ref run(), the supply of each node will be set to zero.
732 735
    ///
733 736
    /// \param map A node map storing the supply values.
734 737
    /// Its \c Value type must be convertible to the \c Value type
735 738
    /// of the algorithm.
736 739
    ///
737 740
    /// \return <tt>(*this)</tt>
738 741
    ///
739 742
    /// \sa supplyType()
740 743
    template<typename SupplyMap>
741 744
    NetworkSimplex& supplyMap(const SupplyMap& map) {
742 745
      for (NodeIt n(_graph); n != INVALID; ++n) {
743 746
        _supply[_node_id[n]] = map[n];
744 747
      }
745 748
      return *this;
746 749
    }
747 750

	
748 751
    /// \brief Set single source and target nodes and a supply value.
749 752
    ///
750 753
    /// This function sets a single source node and a single target node
751 754
    /// and the required flow value.
752 755
    /// If neither this function nor \ref supplyMap() is used before
753 756
    /// calling \ref run(), the supply of each node will be set to zero.
754 757
    ///
755 758
    /// Using this function has the same effect as using \ref supplyMap()
756 759
    /// with a map in which \c k is assigned to \c s, \c -k is
757 760
    /// assigned to \c t and all other nodes have zero supply value.
758 761
    ///
759 762
    /// \param s The source node.
760 763
    /// \param t The target node.
761 764
    /// \param k The required amount of flow from node \c s to node \c t
762 765
    /// (i.e. the supply of \c s and the demand of \c t).
763 766
    ///
764 767
    /// \return <tt>(*this)</tt>
765 768
    NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
766 769
      for (int i = 0; i != _node_num; ++i) {
767 770
        _supply[i] = 0;
768 771
      }
769 772
      _supply[_node_id[s]] =  k;
770 773
      _supply[_node_id[t]] = -k;
771 774
      return *this;
772 775
    }
773 776

	
774 777
    /// \brief Set the type of the supply constraints.
775 778
    ///
776 779
    /// This function sets the type of the supply/demand constraints.
777 780
    /// If it is not used before calling \ref run(), the \ref GEQ supply
778 781
    /// type will be used.
779 782
    ///
780 783
    /// For more information, see \ref SupplyType.
781 784
    ///
782 785
    /// \return <tt>(*this)</tt>
783 786
    NetworkSimplex& supplyType(SupplyType supply_type) {
784 787
      _stype = supply_type;
785 788
      return *this;
786 789
    }
787 790

	
788 791
    /// @}
789 792

	
790 793
    /// \name Execution Control
791 794
    /// The algorithm can be executed using \ref run().
792 795

	
793 796
    /// @{
794 797

	
795 798
    /// \brief Run the algorithm.
796 799
    ///
797 800
    /// This function runs the algorithm.
798 801
    /// The paramters can be specified using functions \ref lowerMap(),
799 802
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
800 803
    /// \ref supplyType().
801 804
    /// For example,
802 805
    /// \code
803 806
    ///   NetworkSimplex<ListDigraph> ns(graph);
804 807
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
805 808
    ///     .supplyMap(sup).run();
806 809
    /// \endcode
807 810
    ///
808 811
    /// This function can be called more than once. All the given parameters
809 812
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
810 813
    /// is used, thus only the modified parameters have to be set again.
811 814
    /// If the underlying digraph was also modified after the construction
812 815
    /// of the class (or the last \ref reset() call), then the \ref reset()
813 816
    /// function must be called.
814 817
    ///
815 818
    /// \param pivot_rule The pivot rule that will be used during the
816 819
    /// algorithm. For more information, see \ref PivotRule.
817 820
    ///
818 821
    /// \return \c INFEASIBLE if no feasible flow exists,
819 822
    /// \n \c OPTIMAL if the problem has optimal solution
820 823
    /// (i.e. it is feasible and bounded), and the algorithm has found
821 824
    /// optimal flow and node potentials (primal and dual solutions),
822 825
    /// \n \c UNBOUNDED if the objective function of the problem is
823 826
    /// unbounded, i.e. there is a directed cycle having negative total
824 827
    /// cost and infinite upper bound.
825 828
    ///
826 829
    /// \see ProblemType, PivotRule
827 830
    /// \see resetParams(), reset()
828 831
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
829 832
      if (!init()) return INFEASIBLE;
830 833
      return start(pivot_rule);
831 834
    }
832 835

	
833 836
    /// \brief Reset all the parameters that have been given before.
834 837
    ///
835 838
    /// This function resets all the paramaters that have been given
836 839
    /// before using functions \ref lowerMap(), \ref upperMap(),
837 840
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
838 841
    ///
839 842
    /// It is useful for multiple \ref run() calls. Basically, all the given
840 843
    /// parameters are kept for the next \ref run() call, unless
841 844
    /// \ref resetParams() or \ref reset() is used.
842 845
    /// If the underlying digraph was also modified after the construction
843 846
    /// of the class or the last \ref reset() call, then the \ref reset()
844 847
    /// function must be used, otherwise \ref resetParams() is sufficient.
845 848
    ///
846 849
    /// For example,
847 850
    /// \code
848 851
    ///   NetworkSimplex<ListDigraph> ns(graph);
849 852
    ///
850 853
    ///   // First run
851 854
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
852 855
    ///     .supplyMap(sup).run();
853 856
    ///
854 857
    ///   // Run again with modified cost map (resetParams() is not called,
855 858
    ///   // so only the cost map have to be set again)
856 859
    ///   cost[e] += 100;
857 860
    ///   ns.costMap(cost).run();
858 861
    ///
859 862
    ///   // Run again from scratch using resetParams()
860 863
    ///   // (the lower bounds will be set to zero on all arcs)
861 864
    ///   ns.resetParams();
862 865
    ///   ns.upperMap(capacity).costMap(cost)
863 866
    ///     .supplyMap(sup).run();
864 867
    /// \endcode
865 868
    ///
866 869
    /// \return <tt>(*this)</tt>
867 870
    ///
868 871
    /// \see reset(), run()
869 872
    NetworkSimplex& resetParams() {
870 873
      for (int i = 0; i != _node_num; ++i) {
871 874
        _supply[i] = 0;
872 875
      }
873 876
      for (int i = 0; i != _arc_num; ++i) {
874 877
        _lower[i] = 0;
875 878
        _upper[i] = INF;
876 879
        _cost[i] = 1;
877 880
      }
878 881
      _have_lower = false;
879 882
      _stype = GEQ;
880 883
      return *this;
881 884
    }
882 885

	
883 886
    /// \brief Reset the internal data structures and all the parameters
884 887
    /// that have been given before.
885 888
    ///
886 889
    /// This function resets the internal data structures and all the
887 890
    /// paramaters that have been given before using functions \ref lowerMap(),
888 891
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
889 892
    /// \ref supplyType().
890 893
    ///
891 894
    /// It is useful for multiple \ref run() calls. Basically, all the given
892 895
    /// parameters are kept for the next \ref run() call, unless
893 896
    /// \ref resetParams() or \ref reset() is used.
894 897
    /// If the underlying digraph was also modified after the construction
895 898
    /// of the class or the last \ref reset() call, then the \ref reset()
896 899
    /// function must be used, otherwise \ref resetParams() is sufficient.
897 900
    ///
898 901
    /// See \ref resetParams() for examples.
899 902
    ///
900 903
    /// \return <tt>(*this)</tt>
901 904
    ///
902 905
    /// \see resetParams(), run()
903 906
    NetworkSimplex& reset() {
904 907
      // Resize vectors
905 908
      _node_num = countNodes(_graph);
906 909
      _arc_num = countArcs(_graph);
907 910
      int all_node_num = _node_num + 1;
908 911
      int max_arc_num = _arc_num + 2 * _node_num;
909 912

	
910 913
      _source.resize(max_arc_num);
911 914
      _target.resize(max_arc_num);
912 915

	
913 916
      _lower.resize(_arc_num);
914 917
      _upper.resize(_arc_num);
915 918
      _cap.resize(max_arc_num);
916 919
      _cost.resize(max_arc_num);
917 920
      _supply.resize(all_node_num);
918 921
      _flow.resize(max_arc_num);
919 922
      _pi.resize(all_node_num);
920 923

	
921 924
      _parent.resize(all_node_num);
922 925
      _pred.resize(all_node_num);
923 926
      _pred_dir.resize(all_node_num);
924 927
      _thread.resize(all_node_num);
925 928
      _rev_thread.resize(all_node_num);
926 929
      _succ_num.resize(all_node_num);
927 930
      _last_succ.resize(all_node_num);
928 931
      _state.resize(max_arc_num);
929 932

	
930 933
      // Copy the graph
931 934
      int i = 0;
932 935
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
933 936
        _node_id[n] = i;
934 937
      }
935 938
      if (_arc_mixing) {
936 939
        // Store the arcs in a mixed order
937 940
        const int skip = std::max(_arc_num / _node_num, 3);
938 941
        int i = 0, j = 0;
939 942
        for (ArcIt a(_graph); a != INVALID; ++a) {
940 943
          _arc_id[a] = i;
941 944
          _source[i] = _node_id[_graph.source(a)];
942 945
          _target[i] = _node_id[_graph.target(a)];
943 946
          if ((i += skip) >= _arc_num) i = ++j;
944 947
        }
945 948
      } else {
946 949
        // Store the arcs in the original order
947 950
        int i = 0;
948 951
        for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
949 952
          _arc_id[a] = i;
950 953
          _source[i] = _node_id[_graph.source(a)];
951 954
          _target[i] = _node_id[_graph.target(a)];
952 955
        }
953 956
      }
954 957

	
955 958
      // Reset parameters
956 959
      resetParams();
957 960
      return *this;
958 961
    }
959 962

	
960 963
    /// @}
961 964

	
962 965
    /// \name Query Functions
963 966
    /// The results of the algorithm can be obtained using these
964 967
    /// functions.\n
965 968
    /// The \ref run() function must be called before using them.
966 969

	
967 970
    /// @{
968 971

	
969 972
    /// \brief Return the total cost of the found flow.
970 973
    ///
971 974
    /// This function returns the total cost of the found flow.
972 975
    /// Its complexity is O(e).
973 976
    ///
974 977
    /// \note The return type of the function can be specified as a
975 978
    /// template parameter. For example,
976 979
    /// \code
977 980
    ///   ns.totalCost<double>();
978 981
    /// \endcode
979 982
    /// It is useful if the total cost cannot be stored in the \c Cost
980 983
    /// type of the algorithm, which is the default return type of the
981 984
    /// function.
982 985
    ///
983 986
    /// \pre \ref run() must be called before using this function.
984 987
    template <typename Number>
985 988
    Number totalCost() const {
986 989
      Number c = 0;
987 990
      for (ArcIt a(_graph); a != INVALID; ++a) {
988 991
        int i = _arc_id[a];
989 992
        c += Number(_flow[i]) * Number(_cost[i]);
990 993
      }
991 994
      return c;
992 995
    }
993 996

	
994 997
#ifndef DOXYGEN
995 998
    Cost totalCost() const {
996 999
      return totalCost<Cost>();
997 1000
    }
998 1001
#endif
999 1002

	
1000 1003
    /// \brief Return the flow on the given arc.
1001 1004
    ///
1002 1005
    /// This function returns the flow on the given arc.
1003 1006
    ///
1004 1007
    /// \pre \ref run() must be called before using this function.
1005 1008
    Value flow(const Arc& a) const {
1006 1009
      return _flow[_arc_id[a]];
1007 1010
    }
1008 1011

	
1009 1012
    /// \brief Return the flow map (the primal solution).
1010 1013
    ///
1011 1014
    /// This function copies the flow value on each arc into the given
1012 1015
    /// map. The \c Value type of the algorithm must be convertible to
1013 1016
    /// the \c Value type of the map.
1014 1017
    ///
1015 1018
    /// \pre \ref run() must be called before using this function.
1016 1019
    template <typename FlowMap>
1017 1020
    void flowMap(FlowMap &map) const {
1018 1021
      for (ArcIt a(_graph); a != INVALID; ++a) {
1019 1022
        map.set(a, _flow[_arc_id[a]]);
1020 1023
      }
1021 1024
    }
1022 1025

	
1023 1026
    /// \brief Return the potential (dual value) of the given node.
1024 1027
    ///
1025 1028
    /// This function returns the potential (dual value) of the
1026 1029
    /// given node.
1027 1030
    ///
1028 1031
    /// \pre \ref run() must be called before using this function.
1029 1032
    Cost potential(const Node& n) const {
1030 1033
      return _pi[_node_id[n]];
1031 1034
    }
1032 1035

	
1033 1036
    /// \brief Return the potential map (the dual solution).
1034 1037
    ///
1035 1038
    /// This function copies the potential (dual value) of each node
1036 1039
    /// into the given map.
1037 1040
    /// The \c Cost type of the algorithm must be convertible to the
1038 1041
    /// \c Value type of the map.
1039 1042
    ///
1040 1043
    /// \pre \ref run() must be called before using this function.
1041 1044
    template <typename PotentialMap>
1042 1045
    void potentialMap(PotentialMap &map) const {
1043 1046
      for (NodeIt n(_graph); n != INVALID; ++n) {
1044 1047
        map.set(n, _pi[_node_id[n]]);
1045 1048
      }
1046 1049
    }
1047 1050

	
1048 1051
    /// @}
1049 1052

	
1050 1053
  private:
1051 1054

	
1052 1055
    // Initialize internal data structures
1053 1056
    bool init() {
1054 1057
      if (_node_num == 0) return false;
1055 1058

	
1056 1059
      // Check the sum of supply values
1057 1060
      _sum_supply = 0;
1058 1061
      for (int i = 0; i != _node_num; ++i) {
1059 1062
        _sum_supply += _supply[i];
1060 1063
      }
1061 1064
      if ( !((_stype == GEQ && _sum_supply <= 0) ||
1062 1065
             (_stype == LEQ && _sum_supply >= 0)) ) return false;
1063 1066

	
1064 1067
      // Remove non-zero lower bounds
1065 1068
      if (_have_lower) {
1066 1069
        for (int i = 0; i != _arc_num; ++i) {
1067 1070
          Value c = _lower[i];
1068 1071
          if (c >= 0) {
1069 1072
            _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1070 1073
          } else {
1071 1074
            _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1072 1075
          }
1073 1076
          _supply[_source[i]] -= c;
1074 1077
          _supply[_target[i]] += c;
1075 1078
        }
1076 1079
      } else {
1077 1080
        for (int i = 0; i != _arc_num; ++i) {
1078 1081
          _cap[i] = _upper[i];
1079 1082
        }
1080 1083
      }
1081 1084

	
1082 1085
      // Initialize artifical cost
1083 1086
      Cost ART_COST;
1084 1087
      if (std::numeric_limits<Cost>::is_exact) {
1085 1088
        ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1086 1089
      } else {
1087 1090
        ART_COST = 0;
1088 1091
        for (int i = 0; i != _arc_num; ++i) {
1089 1092
          if (_cost[i] > ART_COST) ART_COST = _cost[i];
1090 1093
        }
1091 1094
        ART_COST = (ART_COST + 1) * _node_num;
1092 1095
      }
1093 1096

	
1094 1097
      // Initialize arc maps
1095 1098
      for (int i = 0; i != _arc_num; ++i) {
1096 1099
        _flow[i] = 0;
1097 1100
        _state[i] = STATE_LOWER;
1098 1101
      }
1099 1102

	
1100 1103
      // Set data for the artificial root node
1101 1104
      _root = _node_num;
1102 1105
      _parent[_root] = -1;
1103 1106
      _pred[_root] = -1;
1104 1107
      _thread[_root] = 0;
1105 1108
      _rev_thread[0] = _root;
1106 1109
      _succ_num[_root] = _node_num + 1;
1107 1110
      _last_succ[_root] = _root - 1;
1108 1111
      _supply[_root] = -_sum_supply;
1109 1112
      _pi[_root] = 0;
1110 1113

	
1111 1114
      // Add artificial arcs and initialize the spanning tree data structure
1112 1115
      if (_sum_supply == 0) {
1113 1116
        // EQ supply constraints
1114 1117
        _search_arc_num = _arc_num;
1115 1118
        _all_arc_num = _arc_num + _node_num;
1116 1119
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1117 1120
          _parent[u] = _root;
1118 1121
          _pred[u] = e;
1119 1122
          _thread[u] = u + 1;
1120 1123
          _rev_thread[u + 1] = u;
1121 1124
          _succ_num[u] = 1;
1122 1125
          _last_succ[u] = u;
1123 1126
          _cap[e] = INF;
1124 1127
          _state[e] = STATE_TREE;
1125 1128
          if (_supply[u] >= 0) {
1126 1129
            _pred_dir[u] = DIR_UP;
1127 1130
            _pi[u] = 0;
1128 1131
            _source[e] = u;
1129 1132
            _target[e] = _root;
1130 1133
            _flow[e] = _supply[u];
1131 1134
            _cost[e] = 0;
1132 1135
          } else {
1133 1136
            _pred_dir[u] = DIR_DOWN;
1134 1137
            _pi[u] = ART_COST;
1135 1138
            _source[e] = _root;
1136 1139
            _target[e] = u;
1137 1140
            _flow[e] = -_supply[u];
1138 1141
            _cost[e] = ART_COST;
1139 1142
          }
1140 1143
        }
1141 1144
      }
1142 1145
      else if (_sum_supply > 0) {
1143 1146
        // LEQ supply constraints
1144 1147
        _search_arc_num = _arc_num + _node_num;
1145 1148
        int f = _arc_num + _node_num;
1146 1149
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1147 1150
          _parent[u] = _root;
1148 1151
          _thread[u] = u + 1;
1149 1152
          _rev_thread[u + 1] = u;
1150 1153
          _succ_num[u] = 1;
1151 1154
          _last_succ[u] = u;
1152 1155
          if (_supply[u] >= 0) {
1153 1156
            _pred_dir[u] = DIR_UP;
1154 1157
            _pi[u] = 0;
1155 1158
            _pred[u] = e;
1156 1159
            _source[e] = u;
1157 1160
            _target[e] = _root;
1158 1161
            _cap[e] = INF;
1159 1162
            _flow[e] = _supply[u];
1160 1163
            _cost[e] = 0;
1161 1164
            _state[e] = STATE_TREE;
1162 1165
          } else {
1163 1166
            _pred_dir[u] = DIR_DOWN;
1164 1167
            _pi[u] = ART_COST;
1165 1168
            _pred[u] = f;
1166 1169
            _source[f] = _root;
1167 1170
            _target[f] = u;
1168 1171
            _cap[f] = INF;
1169 1172
            _flow[f] = -_supply[u];
1170 1173
            _cost[f] = ART_COST;
1171 1174
            _state[f] = STATE_TREE;
1172 1175
            _source[e] = u;
1173 1176
            _target[e] = _root;
1174 1177
            _cap[e] = INF;
1175 1178
            _flow[e] = 0;
1176 1179
            _cost[e] = 0;
1177 1180
            _state[e] = STATE_LOWER;
1178 1181
            ++f;
1179 1182
          }
1180 1183
        }
1181 1184
        _all_arc_num = f;
1182 1185
      }
1183 1186
      else {
1184 1187
        // GEQ supply constraints
1185 1188
        _search_arc_num = _arc_num + _node_num;
1186 1189
        int f = _arc_num + _node_num;
1187 1190
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1188 1191
          _parent[u] = _root;
1189 1192
          _thread[u] = u + 1;
1190 1193
          _rev_thread[u + 1] = u;
1191 1194
          _succ_num[u] = 1;
1192 1195
          _last_succ[u] = u;
1193 1196
          if (_supply[u] <= 0) {
1194 1197
            _pred_dir[u] = DIR_DOWN;
1195 1198
            _pi[u] = 0;
1196 1199
            _pred[u] = e;
1197 1200
            _source[e] = _root;
1198 1201
            _target[e] = u;
1199 1202
            _cap[e] = INF;
1200 1203
            _flow[e] = -_supply[u];
1201 1204
            _cost[e] = 0;
1202 1205
            _state[e] = STATE_TREE;
1203 1206
          } else {
1204 1207
            _pred_dir[u] = DIR_UP;
1205 1208
            _pi[u] = -ART_COST;
1206 1209
            _pred[u] = f;
1207 1210
            _source[f] = u;
1208 1211
            _target[f] = _root;
1209 1212
            _cap[f] = INF;
1210 1213
            _flow[f] = _supply[u];
1211 1214
            _state[f] = STATE_TREE;
1212 1215
            _cost[f] = ART_COST;
1213 1216
            _source[e] = _root;
1214 1217
            _target[e] = u;
1215 1218
            _cap[e] = INF;
1216 1219
            _flow[e] = 0;
1217 1220
            _cost[e] = 0;
1218 1221
            _state[e] = STATE_LOWER;
1219 1222
            ++f;
1220 1223
          }
1221 1224
        }
1222 1225
        _all_arc_num = f;
1223 1226
      }
1224 1227

	
1225 1228
      return true;
1226 1229
    }
1227 1230

	
1228 1231
    // Find the join node
1229 1232
    void findJoinNode() {
1230 1233
      int u = _source[in_arc];
1231 1234
      int v = _target[in_arc];
1232 1235
      while (u != v) {
1233 1236
        if (_succ_num[u] < _succ_num[v]) {
1234 1237
          u = _parent[u];
1235 1238
        } else {
1236 1239
          v = _parent[v];
1237 1240
        }
1238 1241
      }
1239 1242
      join = u;
1240 1243
    }
1241 1244

	
1242 1245
    // Find the leaving arc of the cycle and returns true if the
1243 1246
    // leaving arc is not the same as the entering arc
1244 1247
    bool findLeavingArc() {
1245 1248
      // Initialize first and second nodes according to the direction
1246 1249
      // of the cycle
1247 1250
      int first, second;
1248 1251
      if (_state[in_arc] == STATE_LOWER) {
1249 1252
        first  = _source[in_arc];
1250 1253
        second = _target[in_arc];
1251 1254
      } else {
1252 1255
        first  = _target[in_arc];
1253 1256
        second = _source[in_arc];
1254 1257
      }
1255 1258
      delta = _cap[in_arc];
1256 1259
      int result = 0;
1257 1260
      Value c, d;
1258 1261
      int e;
1259 1262

	
1260 1263
      // Search the cycle form the first node to the join node
1261 1264
      for (int u = first; u != join; u = _parent[u]) {
1262 1265
        e = _pred[u];
1263 1266
        d = _flow[e];
1264 1267
        if (_pred_dir[u] == DIR_DOWN) {
1265 1268
          c = _cap[e];
1266 1269
          d = c >= MAX ? INF : c - d;
1267 1270
        }
1268 1271
        if (d < delta) {
1269 1272
          delta = d;
1270 1273
          u_out = u;
1271 1274
          result = 1;
1272 1275
        }
1273 1276
      }
1274 1277

	
1275 1278
      // Search the cycle form the second node to the join node
1276 1279
      for (int u = second; u != join; u = _parent[u]) {
1277 1280
        e = _pred[u];
1278 1281
        d = _flow[e];
1279 1282
        if (_pred_dir[u] == DIR_UP) {
1280 1283
          c = _cap[e];
1281 1284
          d = c >= MAX ? INF : c - d;
1282 1285
        }
1283 1286
        if (d <= delta) {
1284 1287
          delta = d;
1285 1288
          u_out = u;
1286 1289
          result = 2;
1287 1290
        }
1288 1291
      }
1289 1292

	
1290 1293
      if (result == 1) {
1291 1294
        u_in = first;
1292 1295
        v_in = second;
1293 1296
      } else {
1294 1297
        u_in = second;
1295 1298
        v_in = first;
1296 1299
      }
1297 1300
      return result != 0;
1298 1301
    }
1299 1302

	
1300 1303
    // Change _flow and _state vectors
1301 1304
    void changeFlow(bool change) {
1302 1305
      // Augment along the cycle
1303 1306
      if (delta > 0) {
1304 1307
        Value val = _state[in_arc] * delta;
1305 1308
        _flow[in_arc] += val;
1306 1309
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1307 1310
          _flow[_pred[u]] -= _pred_dir[u] * val;
1308 1311
        }
1309 1312
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1310 1313
          _flow[_pred[u]] += _pred_dir[u] * val;
1311 1314
        }
1312 1315
      }
1313 1316
      // Update the state of the entering and leaving arcs
1314 1317
      if (change) {
1315 1318
        _state[in_arc] = STATE_TREE;
1316 1319
        _state[_pred[u_out]] =
1317 1320
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1318 1321
      } else {
1319 1322
        _state[in_arc] = -_state[in_arc];
1320 1323
      }
1321 1324
    }
1322 1325

	
1323 1326
    // Update the tree structure
1324 1327
    void updateTreeStructure() {
1325 1328
      int old_rev_thread = _rev_thread[u_out];
1326 1329
      int old_succ_num = _succ_num[u_out];
1327 1330
      int old_last_succ = _last_succ[u_out];
1328 1331
      v_out = _parent[u_out];
1329 1332

	
1330 1333
      // Check if u_in and u_out coincide
1331 1334
      if (u_in == u_out) {
1332 1335
        // Update _parent, _pred, _pred_dir
1333 1336
        _parent[u_in] = v_in;
1334 1337
        _pred[u_in] = in_arc;
1335 1338
        _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1336 1339

	
1337 1340
        // Update _thread and _rev_thread
1338 1341
        if (_thread[v_in] != u_out) {
1339 1342
          int after = _thread[old_last_succ];
1340 1343
          _thread[old_rev_thread] = after;
1341 1344
          _rev_thread[after] = old_rev_thread;
1342 1345
          after = _thread[v_in];
1343 1346
          _thread[v_in] = u_out;
1344 1347
          _rev_thread[u_out] = v_in;
1345 1348
          _thread[old_last_succ] = after;
1346 1349
          _rev_thread[after] = old_last_succ;
1347 1350
        }
1348 1351
      } else {
1349 1352
        // Handle the case when old_rev_thread equals to v_in
1350 1353
        // (it also means that join and v_out coincide)
1351 1354
        int thread_continue = old_rev_thread == v_in ?
1352 1355
          _thread[old_last_succ] : _thread[v_in];
1353 1356

	
1354 1357
        // Update _thread and _parent along the stem nodes (i.e. the nodes
1355 1358
        // between u_in and u_out, whose parent have to be changed)
1356 1359
        int stem = u_in;              // the current stem node
1357 1360
        int par_stem = v_in;          // the new parent of stem
1358 1361
        int next_stem;                // the next stem node
1359 1362
        int last = _last_succ[u_in];  // the last successor of stem
1360 1363
        int before, after = _thread[last];
1361 1364
        _thread[v_in] = u_in;
1362 1365
        _dirty_revs.clear();
1363 1366
        _dirty_revs.push_back(v_in);
1364 1367
        while (stem != u_out) {
1365 1368
          // Insert the next stem node into the thread list
1366 1369
          next_stem = _parent[stem];
1367 1370
          _thread[last] = next_stem;
1368 1371
          _dirty_revs.push_back(last);
1369 1372

	
1370 1373
          // Remove the subtree of stem from the thread list
1371 1374
          before = _rev_thread[stem];
1372 1375
          _thread[before] = after;
1373 1376
          _rev_thread[after] = before;
1374 1377

	
1375 1378
          // Change the parent node and shift stem nodes
1376 1379
          _parent[stem] = par_stem;
1377 1380
          par_stem = stem;
1378 1381
          stem = next_stem;
1379 1382

	
1380 1383
          // Update last and after
1381 1384
          last = _last_succ[stem] == _last_succ[par_stem] ?
1382 1385
            _rev_thread[par_stem] : _last_succ[stem];
1383 1386
          after = _thread[last];
1384 1387
        }
1385 1388
        _parent[u_out] = par_stem;
1386 1389
        _thread[last] = thread_continue;
1387 1390
        _rev_thread[thread_continue] = last;
1388 1391
        _last_succ[u_out] = last;
1389 1392

	
1390 1393
        // Remove the subtree of u_out from the thread list except for
1391 1394
        // the case when old_rev_thread equals to v_in
1392 1395
        if (old_rev_thread != v_in) {
1393 1396
          _thread[old_rev_thread] = after;
1394 1397
          _rev_thread[after] = old_rev_thread;
1395 1398
        }
1396 1399

	
1397 1400
        // Update _rev_thread using the new _thread values
1398 1401
        for (int i = 0; i != int(_dirty_revs.size()); ++i) {
1399 1402
          int u = _dirty_revs[i];
1400 1403
          _rev_thread[_thread[u]] = u;
1401 1404
        }
1402 1405

	
1403 1406
        // Update _pred, _pred_dir, _last_succ and _succ_num for the
1404 1407
        // stem nodes from u_out to u_in
1405 1408
        int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1406 1409
        for (int u = u_out, p = _parent[u]; u != u_in; u = p, p = _parent[u]) {
1407 1410
          _pred[u] = _pred[p];
1408 1411
          _pred_dir[u] = -_pred_dir[p];
1409 1412
          tmp_sc += _succ_num[u] - _succ_num[p];
1410 1413
          _succ_num[u] = tmp_sc;
1411 1414
          _last_succ[p] = tmp_ls;
1412 1415
        }
1413 1416
        _pred[u_in] = in_arc;
1414 1417
        _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1415 1418
        _succ_num[u_in] = old_succ_num;
1416 1419
      }
1417 1420

	
1418 1421
      // Update _last_succ from v_in towards the root
1419 1422
      int up_limit_out = _last_succ[join] == v_in ? join : -1;
1420 1423
      int last_succ_out = _last_succ[u_out];
1421 1424
      for (int u = v_in; u != -1 && _last_succ[u] == v_in; u = _parent[u]) {
1422 1425
        _last_succ[u] = last_succ_out;
1423 1426
      }
1424 1427

	
1425 1428
      // Update _last_succ from v_out towards the root
1426 1429
      if (join != old_rev_thread && v_in != old_rev_thread) {
1427 1430
        for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1428 1431
             u = _parent[u]) {
1429 1432
          _last_succ[u] = old_rev_thread;
1430 1433
        }
1431 1434
      }
1432 1435
      else if (last_succ_out != old_last_succ) {
1433 1436
        for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1434 1437
             u = _parent[u]) {
1435 1438
          _last_succ[u] = last_succ_out;
1436 1439
        }
1437 1440
      }
1438 1441

	
1439 1442
      // Update _succ_num from v_in to join
1440 1443
      for (int u = v_in; u != join; u = _parent[u]) {
1441 1444
        _succ_num[u] += old_succ_num;
1442 1445
      }
1443 1446
      // Update _succ_num from v_out to join
1444 1447
      for (int u = v_out; u != join; u = _parent[u]) {
1445 1448
        _succ_num[u] -= old_succ_num;
1446 1449
      }
1447 1450
    }
1448 1451

	
1449 1452
    // Update potentials in the subtree that has been moved
1450 1453
    void updatePotential() {
1451 1454
      Cost sigma = _pi[v_in] - _pi[u_in] -
1452 1455
                   _pred_dir[u_in] * _cost[in_arc];
1453 1456
      int end = _thread[_last_succ[u_in]];
1454 1457
      for (int u = u_in; u != end; u = _thread[u]) {
1455 1458
        _pi[u] += sigma;
1456 1459
      }
1457 1460
    }
1458 1461

	
1459 1462
    // Heuristic initial pivots
1460 1463
    bool initialPivots() {
1461 1464
      Value curr, total = 0;
1462 1465
      std::vector<Node> supply_nodes, demand_nodes;
1463 1466
      for (NodeIt u(_graph); u != INVALID; ++u) {
1464 1467
        curr = _supply[_node_id[u]];
1465 1468
        if (curr > 0) {
1466 1469
          total += curr;
1467 1470
          supply_nodes.push_back(u);
1468 1471
        }
1469 1472
        else if (curr < 0) {
1470 1473
          demand_nodes.push_back(u);
1471 1474
        }
1472 1475
      }
1473 1476
      if (_sum_supply > 0) total -= _sum_supply;
1474 1477
      if (total <= 0) return true;
1475 1478

	
1476 1479
      IntVector arc_vector;
1477 1480
      if (_sum_supply >= 0) {
1478 1481
        if (supply_nodes.size() == 1 && demand_nodes.size() == 1) {
1479 1482
          // Perform a reverse graph search from the sink to the source
1480 1483
          typename GR::template NodeMap<bool> reached(_graph, false);
1481 1484
          Node s = supply_nodes[0], t = demand_nodes[0];
1482 1485
          std::vector<Node> stack;
1483 1486
          reached[t] = true;
1484 1487
          stack.push_back(t);
1485 1488
          while (!stack.empty()) {
1486 1489
            Node u, v = stack.back();
1487 1490
            stack.pop_back();
1488 1491
            if (v == s) break;
1489 1492
            for (InArcIt a(_graph, v); a != INVALID; ++a) {
1490 1493
              if (reached[u = _graph.source(a)]) continue;
1491 1494
              int j = _arc_id[a];
1492 1495
              if (_cap[j] >= total) {
1493 1496
                arc_vector.push_back(j);
1494 1497
                reached[u] = true;
1495 1498
                stack.push_back(u);
1496 1499
              }
1497 1500
            }
1498 1501
          }
1499 1502
        } else {
1500 1503
          // Find the min. cost incomming arc for each demand node
1501 1504
          for (int i = 0; i != int(demand_nodes.size()); ++i) {
1502 1505
            Node v = demand_nodes[i];
1503 1506
            Cost c, min_cost = std::numeric_limits<Cost>::max();
1504 1507
            Arc min_arc = INVALID;
1505 1508
            for (InArcIt a(_graph, v); a != INVALID; ++a) {
1506 1509
              c = _cost[_arc_id[a]];
1507 1510
              if (c < min_cost) {
1508 1511
                min_cost = c;
1509 1512
                min_arc = a;
1510 1513
              }
1511 1514
            }
1512 1515
            if (min_arc != INVALID) {
1513 1516
              arc_vector.push_back(_arc_id[min_arc]);
1514 1517
            }
1515 1518
          }
1516 1519
        }
1517 1520
      } else {
1518 1521
        // Find the min. cost outgoing arc for each supply node
1519 1522
        for (int i = 0; i != int(supply_nodes.size()); ++i) {
1520 1523
          Node u = supply_nodes[i];
1521 1524
          Cost c, min_cost = std::numeric_limits<Cost>::max();
1522 1525
          Arc min_arc = INVALID;
1523 1526
          for (OutArcIt a(_graph, u); a != INVALID; ++a) {
1524 1527
            c = _cost[_arc_id[a]];
1525 1528
            if (c < min_cost) {
1526 1529
              min_cost = c;
1527 1530
              min_arc = a;
1528 1531
            }
1529 1532
          }
1530 1533
          if (min_arc != INVALID) {
1531 1534
            arc_vector.push_back(_arc_id[min_arc]);
1532 1535
          }
1533 1536
        }
1534 1537
      }
1535 1538

	
1536 1539
      // Perform heuristic initial pivots
1537 1540
      for (int i = 0; i != int(arc_vector.size()); ++i) {
1538 1541
        in_arc = arc_vector[i];
1539 1542
        if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -
1540 1543
            _pi[_target[in_arc]]) >= 0) continue;
1541 1544
        findJoinNode();
1542 1545
        bool change = findLeavingArc();
1543 1546
        if (delta >= MAX) return false;
1544 1547
        changeFlow(change);
1545 1548
        if (change) {
1546 1549
          updateTreeStructure();
1547 1550
          updatePotential();
1548 1551
        }
1549 1552
      }
1550 1553
      return true;
1551 1554
    }
1552 1555

	
1553 1556
    // Execute the algorithm
1554 1557
    ProblemType start(PivotRule pivot_rule) {
1555 1558
      // Select the pivot rule implementation
1556 1559
      switch (pivot_rule) {
1557 1560
        case FIRST_ELIGIBLE:
1558 1561
          return start<FirstEligiblePivotRule>();
1559 1562
        case BEST_ELIGIBLE:
1560 1563
          return start<BestEligiblePivotRule>();
1561 1564
        case BLOCK_SEARCH:
1562 1565
          return start<BlockSearchPivotRule>();
1563 1566
        case CANDIDATE_LIST:
1564 1567
          return start<CandidateListPivotRule>();
1565 1568
        case ALTERING_LIST:
1566 1569
          return start<AlteringListPivotRule>();
1567 1570
      }
1568 1571
      return INFEASIBLE; // avoid warning
1569 1572
    }
1570 1573

	
1571 1574
    template <typename PivotRuleImpl>
1572 1575
    ProblemType start() {
1573 1576
      PivotRuleImpl pivot(*this);
1574 1577

	
1575 1578
      // Perform heuristic initial pivots
1576 1579
      if (!initialPivots()) return UNBOUNDED;
1577 1580

	
1578 1581
      // Execute the Network Simplex algorithm
1579 1582
      while (pivot.findEnteringArc()) {
1580 1583
        findJoinNode();
1581 1584
        bool change = findLeavingArc();
1582 1585
        if (delta >= MAX) return UNBOUNDED;
1583 1586
        changeFlow(change);
1584 1587
        if (change) {
1585 1588
          updateTreeStructure();
1586 1589
          updatePotential();
1587 1590
        }
1588 1591
      }
1589 1592

	
1590 1593
      // Check feasibility
1591 1594
      for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1592 1595
        if (_flow[e] != 0) return INFEASIBLE;
1593 1596
      }
1594 1597

	
1595 1598
      // Transform the solution and the supply map to the original form
1596 1599
      if (_have_lower) {
1597 1600
        for (int i = 0; i != _arc_num; ++i) {
1598 1601
          Value c = _lower[i];
1599 1602
          if (c != 0) {
1600 1603
            _flow[i] += c;
1601 1604
            _supply[_source[i]] += c;
1602 1605
            _supply[_target[i]] -= c;
1603 1606
          }
1604 1607
        }
1605 1608
      }
1606 1609

	
1607 1610
      // Shift potentials to meet the requirements of the GEQ/LEQ type
1608 1611
      // optimality conditions
1609 1612
      if (_sum_supply == 0) {
1610 1613
        if (_stype == GEQ) {
1611 1614
          Cost max_pot = -std::numeric_limits<Cost>::max();
1612 1615
          for (int i = 0; i != _node_num; ++i) {
1613 1616
            if (_pi[i] > max_pot) max_pot = _pi[i];
1614 1617
          }
1615 1618
          if (max_pot > 0) {
1616 1619
            for (int i = 0; i != _node_num; ++i)
1617 1620
              _pi[i] -= max_pot;
1618 1621
          }
1619 1622
        } else {
1620 1623
          Cost min_pot = std::numeric_limits<Cost>::max();
1621 1624
          for (int i = 0; i != _node_num; ++i) {
1622 1625
            if (_pi[i] < min_pot) min_pot = _pi[i];
1623 1626
          }
1624 1627
          if (min_pot < 0) {
1625 1628
            for (int i = 0; i != _node_num; ++i)
1626 1629
              _pi[i] -= min_pot;
1627 1630
          }
1628 1631
        }
1629 1632
      }
1630 1633

	
1631 1634
      return OPTIMAL;
1632 1635
    }
1633 1636

	
1634 1637
  }; //class NetworkSimplex
1635 1638

	
1636 1639
  ///@}
1637 1640

	
1638 1641
} //namespace lemon
1639 1642

	
1640 1643
#endif //LEMON_NETWORK_SIMPLEX_H
0 comments (0 inline)