gravatar
deba@inf.elte.hu
deba@inf.elte.hu
Fix critical bug in preflow (#372) The wrong transition between the bound decrease and highest active heuristics caused the bug. The last node chosen in bound decrease mode is used in the first iteration in highest active mode.
0 1 0
default
1 file changed with 24 insertions and 20 deletions:
↑ Collapse diff ↑
Ignore white space 16384 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-2009
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_PREFLOW_H
20 20
#define LEMON_PREFLOW_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24

	
25 25
/// \file
26 26
/// \ingroup max_flow
27 27
/// \brief Implementation of the preflow algorithm.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  /// \brief Default traits class of Preflow class.
32 32
  ///
33 33
  /// Default traits class of Preflow class.
34 34
  /// \tparam GR Digraph type.
35 35
  /// \tparam CAP Capacity map type.
36 36
  template <typename GR, typename CAP>
37 37
  struct PreflowDefaultTraits {
38 38

	
39 39
    /// \brief The type of the digraph the algorithm runs on.
40 40
    typedef GR Digraph;
41 41

	
42 42
    /// \brief The type of the map that stores the arc capacities.
43 43
    ///
44 44
    /// The type of the map that stores the arc capacities.
45 45
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
46 46
    typedef CAP CapacityMap;
47 47

	
48 48
    /// \brief The type of the flow values.
49 49
    typedef typename CapacityMap::Value Value;
50 50

	
51 51
    /// \brief The type of the map that stores the flow values.
52 52
    ///
53 53
    /// The type of the map that stores the flow values.
54 54
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
55 55
    typedef typename Digraph::template ArcMap<Value> FlowMap;
56 56

	
57 57
    /// \brief Instantiates a FlowMap.
58 58
    ///
59 59
    /// This function instantiates a \ref FlowMap.
60 60
    /// \param digraph The digraph for which we would like to define
61 61
    /// the flow map.
62 62
    static FlowMap* createFlowMap(const Digraph& digraph) {
63 63
      return new FlowMap(digraph);
64 64
    }
65 65

	
66 66
    /// \brief The elevator type used by Preflow algorithm.
67 67
    ///
68 68
    /// The elevator type used by Preflow algorithm.
69 69
    ///
70 70
    /// \sa Elevator
71 71
    /// \sa LinkedElevator
72 72
    typedef LinkedElevator<Digraph, typename Digraph::Node> Elevator;
73 73

	
74 74
    /// \brief Instantiates an Elevator.
75 75
    ///
76 76
    /// This function instantiates an \ref Elevator.
77 77
    /// \param digraph The digraph for which we would like to define
78 78
    /// the elevator.
79 79
    /// \param max_level The maximum level of the elevator.
80 80
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
81 81
      return new Elevator(digraph, max_level);
82 82
    }
83 83

	
84 84
    /// \brief The tolerance used by the algorithm
85 85
    ///
86 86
    /// The tolerance used by the algorithm to handle inexact computation.
87 87
    typedef lemon::Tolerance<Value> Tolerance;
88 88

	
89 89
  };
90 90

	
91 91

	
92 92
  /// \ingroup max_flow
93 93
  ///
94 94
  /// \brief %Preflow algorithm class.
95 95
  ///
96 96
  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
97 97
  /// \e push-relabel algorithm producing a \ref max_flow
98 98
  /// "flow of maximum value" in a digraph.
99 99
  /// The preflow algorithms are the fastest known maximum
100 100
  /// flow algorithms. The current implementation use a mixture of the
101 101
  /// \e "highest label" and the \e "bound decrease" heuristics.
102 102
  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
103 103
  ///
104 104
  /// The algorithm consists of two phases. After the first phase
105 105
  /// the maximum flow value and the minimum cut is obtained. The
106 106
  /// second phase constructs a feasible maximum flow on each arc.
107 107
  ///
108 108
  /// \tparam GR The type of the digraph the algorithm runs on.
109 109
  /// \tparam CAP The type of the capacity map. The default map
110 110
  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
111 111
#ifdef DOXYGEN
112 112
  template <typename GR, typename CAP, typename TR>
113 113
#else
114 114
  template <typename GR,
115 115
            typename CAP = typename GR::template ArcMap<int>,
116 116
            typename TR = PreflowDefaultTraits<GR, CAP> >
117 117
#endif
118 118
  class Preflow {
119 119
  public:
120 120

	
121 121
    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
122 122
    typedef TR Traits;
123 123
    ///The type of the digraph the algorithm runs on.
124 124
    typedef typename Traits::Digraph Digraph;
125 125
    ///The type of the capacity map.
126 126
    typedef typename Traits::CapacityMap CapacityMap;
127 127
    ///The type of the flow values.
128 128
    typedef typename Traits::Value Value;
129 129

	
130 130
    ///The type of the flow map.
131 131
    typedef typename Traits::FlowMap FlowMap;
132 132
    ///The type of the elevator.
133 133
    typedef typename Traits::Elevator Elevator;
134 134
    ///The type of the tolerance.
135 135
    typedef typename Traits::Tolerance Tolerance;
136 136

	
137 137
  private:
138 138

	
139 139
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
140 140

	
141 141
    const Digraph& _graph;
142 142
    const CapacityMap* _capacity;
143 143

	
144 144
    int _node_num;
145 145

	
146 146
    Node _source, _target;
147 147

	
148 148
    FlowMap* _flow;
149 149
    bool _local_flow;
150 150

	
151 151
    Elevator* _level;
152 152
    bool _local_level;
153 153

	
154 154
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
155 155
    ExcessMap* _excess;
156 156

	
157 157
    Tolerance _tolerance;
158 158

	
159 159
    bool _phase;
160 160

	
161 161

	
162 162
    void createStructures() {
163 163
      _node_num = countNodes(_graph);
164 164

	
165 165
      if (!_flow) {
166 166
        _flow = Traits::createFlowMap(_graph);
167 167
        _local_flow = true;
168 168
      }
169 169
      if (!_level) {
170 170
        _level = Traits::createElevator(_graph, _node_num);
171 171
        _local_level = true;
172 172
      }
173 173
      if (!_excess) {
174 174
        _excess = new ExcessMap(_graph);
175 175
      }
176 176
    }
177 177

	
178 178
    void destroyStructures() {
179 179
      if (_local_flow) {
180 180
        delete _flow;
181 181
      }
182 182
      if (_local_level) {
183 183
        delete _level;
184 184
      }
185 185
      if (_excess) {
186 186
        delete _excess;
187 187
      }
188 188
    }
189 189

	
190 190
  public:
191 191

	
192 192
    typedef Preflow Create;
193 193

	
194 194
    ///\name Named Template Parameters
195 195

	
196 196
    ///@{
197 197

	
198 198
    template <typename T>
199 199
    struct SetFlowMapTraits : public Traits {
200 200
      typedef T FlowMap;
201 201
      static FlowMap *createFlowMap(const Digraph&) {
202 202
        LEMON_ASSERT(false, "FlowMap is not initialized");
203 203
        return 0; // ignore warnings
204 204
      }
205 205
    };
206 206

	
207 207
    /// \brief \ref named-templ-param "Named parameter" for setting
208 208
    /// FlowMap type
209 209
    ///
210 210
    /// \ref named-templ-param "Named parameter" for setting FlowMap
211 211
    /// type.
212 212
    template <typename T>
213 213
    struct SetFlowMap
214 214
      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
215 215
      typedef Preflow<Digraph, CapacityMap,
216 216
                      SetFlowMapTraits<T> > Create;
217 217
    };
218 218

	
219 219
    template <typename T>
220 220
    struct SetElevatorTraits : public Traits {
221 221
      typedef T Elevator;
222 222
      static Elevator *createElevator(const Digraph&, int) {
223 223
        LEMON_ASSERT(false, "Elevator is not initialized");
224 224
        return 0; // ignore warnings
225 225
      }
226 226
    };
227 227

	
228 228
    /// \brief \ref named-templ-param "Named parameter" for setting
229 229
    /// Elevator type
230 230
    ///
231 231
    /// \ref named-templ-param "Named parameter" for setting Elevator
232 232
    /// type. If this named parameter is used, then an external
233 233
    /// elevator object must be passed to the algorithm using the
234 234
    /// \ref elevator(Elevator&) "elevator()" function before calling
235 235
    /// \ref run() or \ref init().
236 236
    /// \sa SetStandardElevator
237 237
    template <typename T>
238 238
    struct SetElevator
239 239
      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
240 240
      typedef Preflow<Digraph, CapacityMap,
241 241
                      SetElevatorTraits<T> > Create;
242 242
    };
243 243

	
244 244
    template <typename T>
245 245
    struct SetStandardElevatorTraits : public Traits {
246 246
      typedef T Elevator;
247 247
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
248 248
        return new Elevator(digraph, max_level);
249 249
      }
250 250
    };
251 251

	
252 252
    /// \brief \ref named-templ-param "Named parameter" for setting
253 253
    /// Elevator type with automatic allocation
254 254
    ///
255 255
    /// \ref named-templ-param "Named parameter" for setting Elevator
256 256
    /// type with automatic allocation.
257 257
    /// The Elevator should have standard constructor interface to be
258 258
    /// able to automatically created by the algorithm (i.e. the
259 259
    /// digraph and the maximum level should be passed to it).
260 260
    /// However an external elevator object could also be passed to the
261 261
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
262 262
    /// before calling \ref run() or \ref init().
263 263
    /// \sa SetElevator
264 264
    template <typename T>
265 265
    struct SetStandardElevator
266 266
      : public Preflow<Digraph, CapacityMap,
267 267
                       SetStandardElevatorTraits<T> > {
268 268
      typedef Preflow<Digraph, CapacityMap,
269 269
                      SetStandardElevatorTraits<T> > Create;
270 270
    };
271 271

	
272 272
    /// @}
273 273

	
274 274
  protected:
275 275

	
276 276
    Preflow() {}
277 277

	
278 278
  public:
279 279

	
280 280

	
281 281
    /// \brief The constructor of the class.
282 282
    ///
283 283
    /// The constructor of the class.
284 284
    /// \param digraph The digraph the algorithm runs on.
285 285
    /// \param capacity The capacity of the arcs.
286 286
    /// \param source The source node.
287 287
    /// \param target The target node.
288 288
    Preflow(const Digraph& digraph, const CapacityMap& capacity,
289 289
            Node source, Node target)
290 290
      : _graph(digraph), _capacity(&capacity),
291 291
        _node_num(0), _source(source), _target(target),
292 292
        _flow(0), _local_flow(false),
293 293
        _level(0), _local_level(false),
294 294
        _excess(0), _tolerance(), _phase() {}
295 295

	
296 296
    /// \brief Destructor.
297 297
    ///
298 298
    /// Destructor.
299 299
    ~Preflow() {
300 300
      destroyStructures();
301 301
    }
302 302

	
303 303
    /// \brief Sets the capacity map.
304 304
    ///
305 305
    /// Sets the capacity map.
306 306
    /// \return <tt>(*this)</tt>
307 307
    Preflow& capacityMap(const CapacityMap& map) {
308 308
      _capacity = &map;
309 309
      return *this;
310 310
    }
311 311

	
312 312
    /// \brief Sets the flow map.
313 313
    ///
314 314
    /// Sets the flow map.
315 315
    /// If you don't use this function before calling \ref run() or
316 316
    /// \ref init(), an instance will be allocated automatically.
317 317
    /// The destructor deallocates this automatically allocated map,
318 318
    /// of course.
319 319
    /// \return <tt>(*this)</tt>
320 320
    Preflow& flowMap(FlowMap& map) {
321 321
      if (_local_flow) {
322 322
        delete _flow;
323 323
        _local_flow = false;
324 324
      }
325 325
      _flow = &map;
326 326
      return *this;
327 327
    }
328 328

	
329 329
    /// \brief Sets the source node.
330 330
    ///
331 331
    /// Sets the source node.
332 332
    /// \return <tt>(*this)</tt>
333 333
    Preflow& source(const Node& node) {
334 334
      _source = node;
335 335
      return *this;
336 336
    }
337 337

	
338 338
    /// \brief Sets the target node.
339 339
    ///
340 340
    /// Sets the target node.
341 341
    /// \return <tt>(*this)</tt>
342 342
    Preflow& target(const Node& node) {
343 343
      _target = node;
344 344
      return *this;
345 345
    }
346 346

	
347 347
    /// \brief Sets the elevator used by algorithm.
348 348
    ///
349 349
    /// Sets the elevator used by algorithm.
350 350
    /// If you don't use this function before calling \ref run() or
351 351
    /// \ref init(), an instance will be allocated automatically.
352 352
    /// The destructor deallocates this automatically allocated elevator,
353 353
    /// of course.
354 354
    /// \return <tt>(*this)</tt>
355 355
    Preflow& elevator(Elevator& elevator) {
356 356
      if (_local_level) {
357 357
        delete _level;
358 358
        _local_level = false;
359 359
      }
360 360
      _level = &elevator;
361 361
      return *this;
362 362
    }
363 363

	
364 364
    /// \brief Returns a const reference to the elevator.
365 365
    ///
366 366
    /// Returns a const reference to the elevator.
367 367
    ///
368 368
    /// \pre Either \ref run() or \ref init() must be called before
369 369
    /// using this function.
370 370
    const Elevator& elevator() const {
371 371
      return *_level;
372 372
    }
373 373

	
374 374
    /// \brief Sets the tolerance used by algorithm.
375 375
    ///
376 376
    /// Sets the tolerance used by algorithm.
377 377
    Preflow& tolerance(const Tolerance& tolerance) {
378 378
      _tolerance = tolerance;
379 379
      return *this;
380 380
    }
381 381

	
382 382
    /// \brief Returns a const reference to the tolerance.
383 383
    ///
384 384
    /// Returns a const reference to the tolerance.
385 385
    const Tolerance& tolerance() const {
386 386
      return _tolerance;
387 387
    }
388 388

	
389 389
    /// \name Execution Control
390 390
    /// The simplest way to execute the preflow algorithm is to use
391 391
    /// \ref run() or \ref runMinCut().\n
392 392
    /// If you need more control on the initial solution or the execution,
393 393
    /// first you have to call one of the \ref init() functions, then
394 394
    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
395 395

	
396 396
    ///@{
397 397

	
398 398
    /// \brief Initializes the internal data structures.
399 399
    ///
400 400
    /// Initializes the internal data structures and sets the initial
401 401
    /// flow to zero on each arc.
402 402
    void init() {
403 403
      createStructures();
404 404

	
405 405
      _phase = true;
406 406
      for (NodeIt n(_graph); n != INVALID; ++n) {
407 407
        (*_excess)[n] = 0;
408 408
      }
409 409

	
410 410
      for (ArcIt e(_graph); e != INVALID; ++e) {
411 411
        _flow->set(e, 0);
412 412
      }
413 413

	
414 414
      typename Digraph::template NodeMap<bool> reached(_graph, false);
415 415

	
416 416
      _level->initStart();
417 417
      _level->initAddItem(_target);
418 418

	
419 419
      std::vector<Node> queue;
420 420
      reached[_source] = true;
421 421

	
422 422
      queue.push_back(_target);
423 423
      reached[_target] = true;
424 424
      while (!queue.empty()) {
425 425
        _level->initNewLevel();
426 426
        std::vector<Node> nqueue;
427 427
        for (int i = 0; i < int(queue.size()); ++i) {
428 428
          Node n = queue[i];
429 429
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
430 430
            Node u = _graph.source(e);
431 431
            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
432 432
              reached[u] = true;
433 433
              _level->initAddItem(u);
434 434
              nqueue.push_back(u);
435 435
            }
436 436
          }
437 437
        }
438 438
        queue.swap(nqueue);
439 439
      }
440 440
      _level->initFinish();
441 441

	
442 442
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
443 443
        if (_tolerance.positive((*_capacity)[e])) {
444 444
          Node u = _graph.target(e);
445 445
          if ((*_level)[u] == _level->maxLevel()) continue;
446 446
          _flow->set(e, (*_capacity)[e]);
447 447
          (*_excess)[u] += (*_capacity)[e];
448 448
          if (u != _target && !_level->active(u)) {
449 449
            _level->activate(u);
450 450
          }
451 451
        }
452 452
      }
453 453
    }
454 454

	
455 455
    /// \brief Initializes the internal data structures using the
456 456
    /// given flow map.
457 457
    ///
458 458
    /// Initializes the internal data structures and sets the initial
459 459
    /// flow to the given \c flowMap. The \c flowMap should contain a
460 460
    /// flow or at least a preflow, i.e. at each node excluding the
461 461
    /// source node the incoming flow should greater or equal to the
462 462
    /// outgoing flow.
463 463
    /// \return \c false if the given \c flowMap is not a preflow.
464 464
    template <typename FlowMap>
465 465
    bool init(const FlowMap& flowMap) {
466 466
      createStructures();
467 467

	
468 468
      for (ArcIt e(_graph); e != INVALID; ++e) {
469 469
        _flow->set(e, flowMap[e]);
470 470
      }
471 471

	
472 472
      for (NodeIt n(_graph); n != INVALID; ++n) {
473 473
        Value excess = 0;
474 474
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
475 475
          excess += (*_flow)[e];
476 476
        }
477 477
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
478 478
          excess -= (*_flow)[e];
479 479
        }
480 480
        if (excess < 0 && n != _source) return false;
481 481
        (*_excess)[n] = excess;
482 482
      }
483 483

	
484 484
      typename Digraph::template NodeMap<bool> reached(_graph, false);
485 485

	
486 486
      _level->initStart();
487 487
      _level->initAddItem(_target);
488 488

	
489 489
      std::vector<Node> queue;
490 490
      reached[_source] = true;
491 491

	
492 492
      queue.push_back(_target);
493 493
      reached[_target] = true;
494 494
      while (!queue.empty()) {
495 495
        _level->initNewLevel();
496 496
        std::vector<Node> nqueue;
497 497
        for (int i = 0; i < int(queue.size()); ++i) {
498 498
          Node n = queue[i];
499 499
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
500 500
            Node u = _graph.source(e);
501 501
            if (!reached[u] &&
502 502
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
503 503
              reached[u] = true;
504 504
              _level->initAddItem(u);
505 505
              nqueue.push_back(u);
506 506
            }
507 507
          }
508 508
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
509 509
            Node v = _graph.target(e);
510 510
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
511 511
              reached[v] = true;
512 512
              _level->initAddItem(v);
513 513
              nqueue.push_back(v);
514 514
            }
515 515
          }
516 516
        }
517 517
        queue.swap(nqueue);
518 518
      }
519 519
      _level->initFinish();
520 520

	
521 521
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
522 522
        Value rem = (*_capacity)[e] - (*_flow)[e];
523 523
        if (_tolerance.positive(rem)) {
524 524
          Node u = _graph.target(e);
525 525
          if ((*_level)[u] == _level->maxLevel()) continue;
526 526
          _flow->set(e, (*_capacity)[e]);
527 527
          (*_excess)[u] += rem;
528 528
          if (u != _target && !_level->active(u)) {
529 529
            _level->activate(u);
530 530
          }
531 531
        }
532 532
      }
533 533
      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
534 534
        Value rem = (*_flow)[e];
535 535
        if (_tolerance.positive(rem)) {
536 536
          Node v = _graph.source(e);
537 537
          if ((*_level)[v] == _level->maxLevel()) continue;
538 538
          _flow->set(e, 0);
539 539
          (*_excess)[v] += rem;
540 540
          if (v != _target && !_level->active(v)) {
541 541
            _level->activate(v);
542 542
          }
543 543
        }
544 544
      }
545 545
      return true;
546 546
    }
547 547

	
548 548
    /// \brief Starts the first phase of the preflow algorithm.
549 549
    ///
550 550
    /// The preflow algorithm consists of two phases, this method runs
551 551
    /// the first phase. After the first phase the maximum flow value
552 552
    /// and a minimum value cut can already be computed, although a
553 553
    /// maximum flow is not yet obtained. So after calling this method
554 554
    /// \ref flowValue() returns the value of a maximum flow and \ref
555 555
    /// minCut() returns a minimum cut.
556 556
    /// \pre One of the \ref init() functions must be called before
557 557
    /// using this function.
558 558
    void startFirstPhase() {
559 559
      _phase = true;
560 560

	
561
      Node n = _level->highestActive();
562
      int level = _level->highestActiveLevel();
563
      while (n != INVALID) {
561
      while (true) {
564 562
        int num = _node_num;
565 563

	
566
        while (num > 0 && n != INVALID) {
564
        Node n = INVALID;
565
        int level = -1;
566

	
567
        while (num > 0) {
568
          n = _level->highestActive();
569
          if (n == INVALID) goto first_phase_done;
570
          level = _level->highestActiveLevel();
571
          --num;
572
          
567 573
          Value excess = (*_excess)[n];
568 574
          int new_level = _level->maxLevel();
569 575

	
570 576
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
571 577
            Value rem = (*_capacity)[e] - (*_flow)[e];
572 578
            if (!_tolerance.positive(rem)) continue;
573 579
            Node v = _graph.target(e);
574 580
            if ((*_level)[v] < level) {
575 581
              if (!_level->active(v) && v != _target) {
576 582
                _level->activate(v);
577 583
              }
578 584
              if (!_tolerance.less(rem, excess)) {
579 585
                _flow->set(e, (*_flow)[e] + excess);
580 586
                (*_excess)[v] += excess;
581 587
                excess = 0;
582 588
                goto no_more_push_1;
583 589
              } else {
584 590
                excess -= rem;
585 591
                (*_excess)[v] += rem;
586 592
                _flow->set(e, (*_capacity)[e]);
587 593
              }
588 594
            } else if (new_level > (*_level)[v]) {
589 595
              new_level = (*_level)[v];
590 596
            }
591 597
          }
592 598

	
593 599
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
594 600
            Value rem = (*_flow)[e];
595 601
            if (!_tolerance.positive(rem)) continue;
596 602
            Node v = _graph.source(e);
597 603
            if ((*_level)[v] < level) {
598 604
              if (!_level->active(v) && v != _target) {
599 605
                _level->activate(v);
600 606
              }
601 607
              if (!_tolerance.less(rem, excess)) {
602 608
                _flow->set(e, (*_flow)[e] - excess);
603 609
                (*_excess)[v] += excess;
604 610
                excess = 0;
605 611
                goto no_more_push_1;
606 612
              } else {
607 613
                excess -= rem;
608 614
                (*_excess)[v] += rem;
609 615
                _flow->set(e, 0);
610 616
              }
611 617
            } else if (new_level > (*_level)[v]) {
612 618
              new_level = (*_level)[v];
613 619
            }
614 620
          }
615 621

	
616 622
        no_more_push_1:
617 623

	
618 624
          (*_excess)[n] = excess;
619 625

	
620 626
          if (excess != 0) {
621 627
            if (new_level + 1 < _level->maxLevel()) {
622 628
              _level->liftHighestActive(new_level + 1);
623 629
            } else {
624 630
              _level->liftHighestActiveToTop();
625 631
            }
626 632
            if (_level->emptyLevel(level)) {
627 633
              _level->liftToTop(level);
628 634
            }
629 635
          } else {
630 636
            _level->deactivate(n);
631 637
          }
632

	
633
          n = _level->highestActive();
634
          level = _level->highestActiveLevel();
635
          --num;
636 638
        }
637 639

	
638 640
        num = _node_num * 20;
639
        while (num > 0 && n != INVALID) {
641
        while (num > 0) {
642
          while (level >= 0 && _level->activeFree(level)) {
643
            --level;
644
          }
645
          if (level == -1) {
646
            n = _level->highestActive();
647
            level = _level->highestActiveLevel();
648
            if (n == INVALID) goto first_phase_done;
649
          } else {
650
            n = _level->activeOn(level);
651
          }
652
          --num;
653

	
640 654
          Value excess = (*_excess)[n];
641 655
          int new_level = _level->maxLevel();
642 656

	
643 657
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
644 658
            Value rem = (*_capacity)[e] - (*_flow)[e];
645 659
            if (!_tolerance.positive(rem)) continue;
646 660
            Node v = _graph.target(e);
647 661
            if ((*_level)[v] < level) {
648 662
              if (!_level->active(v) && v != _target) {
649 663
                _level->activate(v);
650 664
              }
651 665
              if (!_tolerance.less(rem, excess)) {
652 666
                _flow->set(e, (*_flow)[e] + excess);
653 667
                (*_excess)[v] += excess;
654 668
                excess = 0;
655 669
                goto no_more_push_2;
656 670
              } else {
657 671
                excess -= rem;
658 672
                (*_excess)[v] += rem;
659 673
                _flow->set(e, (*_capacity)[e]);
660 674
              }
661 675
            } else if (new_level > (*_level)[v]) {
662 676
              new_level = (*_level)[v];
663 677
            }
664 678
          }
665 679

	
666 680
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
667 681
            Value rem = (*_flow)[e];
668 682
            if (!_tolerance.positive(rem)) continue;
669 683
            Node v = _graph.source(e);
670 684
            if ((*_level)[v] < level) {
671 685
              if (!_level->active(v) && v != _target) {
672 686
                _level->activate(v);
673 687
              }
674 688
              if (!_tolerance.less(rem, excess)) {
675 689
                _flow->set(e, (*_flow)[e] - excess);
676 690
                (*_excess)[v] += excess;
677 691
                excess = 0;
678 692
                goto no_more_push_2;
679 693
              } else {
680 694
                excess -= rem;
681 695
                (*_excess)[v] += rem;
682 696
                _flow->set(e, 0);
683 697
              }
684 698
            } else if (new_level > (*_level)[v]) {
685 699
              new_level = (*_level)[v];
686 700
            }
687 701
          }
688 702

	
689 703
        no_more_push_2:
690 704

	
691 705
          (*_excess)[n] = excess;
692 706

	
693 707
          if (excess != 0) {
694 708
            if (new_level + 1 < _level->maxLevel()) {
695 709
              _level->liftActiveOn(level, new_level + 1);
696 710
            } else {
697 711
              _level->liftActiveToTop(level);
698 712
            }
699 713
            if (_level->emptyLevel(level)) {
700 714
              _level->liftToTop(level);
701 715
            }
702 716
          } else {
703 717
            _level->deactivate(n);
704 718
          }
705

	
706
          while (level >= 0 && _level->activeFree(level)) {
707
            --level;
708
          }
709
          if (level == -1) {
710
            n = _level->highestActive();
711
            level = _level->highestActiveLevel();
712
          } else {
713
            n = _level->activeOn(level);
714
          }
715
          --num;
716 719
        }
717 720
      }
721
    first_phase_done:;
718 722
    }
719 723

	
720 724
    /// \brief Starts the second phase of the preflow algorithm.
721 725
    ///
722 726
    /// The preflow algorithm consists of two phases, this method runs
723 727
    /// the second phase. After calling one of the \ref init() functions
724 728
    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
725 729
    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
726 730
    /// value of a maximum flow, \ref minCut() returns a minimum cut
727 731
    /// \pre One of the \ref init() functions and \ref startFirstPhase()
728 732
    /// must be called before using this function.
729 733
    void startSecondPhase() {
730 734
      _phase = false;
731 735

	
732 736
      typename Digraph::template NodeMap<bool> reached(_graph);
733 737
      for (NodeIt n(_graph); n != INVALID; ++n) {
734 738
        reached[n] = (*_level)[n] < _level->maxLevel();
735 739
      }
736 740

	
737 741
      _level->initStart();
738 742
      _level->initAddItem(_source);
739 743

	
740 744
      std::vector<Node> queue;
741 745
      queue.push_back(_source);
742 746
      reached[_source] = true;
743 747

	
744 748
      while (!queue.empty()) {
745 749
        _level->initNewLevel();
746 750
        std::vector<Node> nqueue;
747 751
        for (int i = 0; i < int(queue.size()); ++i) {
748 752
          Node n = queue[i];
749 753
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
750 754
            Node v = _graph.target(e);
751 755
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
752 756
              reached[v] = true;
753 757
              _level->initAddItem(v);
754 758
              nqueue.push_back(v);
755 759
            }
756 760
          }
757 761
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
758 762
            Node u = _graph.source(e);
759 763
            if (!reached[u] &&
760 764
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
761 765
              reached[u] = true;
762 766
              _level->initAddItem(u);
763 767
              nqueue.push_back(u);
764 768
            }
765 769
          }
766 770
        }
767 771
        queue.swap(nqueue);
768 772
      }
769 773
      _level->initFinish();
770 774

	
771 775
      for (NodeIt n(_graph); n != INVALID; ++n) {
772 776
        if (!reached[n]) {
773 777
          _level->dirtyTopButOne(n);
774 778
        } else if ((*_excess)[n] > 0 && _target != n) {
775 779
          _level->activate(n);
776 780
        }
777 781
      }
778 782

	
779 783
      Node n;
780 784
      while ((n = _level->highestActive()) != INVALID) {
781 785
        Value excess = (*_excess)[n];
782 786
        int level = _level->highestActiveLevel();
783 787
        int new_level = _level->maxLevel();
784 788

	
785 789
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
786 790
          Value rem = (*_capacity)[e] - (*_flow)[e];
787 791
          if (!_tolerance.positive(rem)) continue;
788 792
          Node v = _graph.target(e);
789 793
          if ((*_level)[v] < level) {
790 794
            if (!_level->active(v) && v != _source) {
791 795
              _level->activate(v);
792 796
            }
793 797
            if (!_tolerance.less(rem, excess)) {
794 798
              _flow->set(e, (*_flow)[e] + excess);
795 799
              (*_excess)[v] += excess;
796 800
              excess = 0;
797 801
              goto no_more_push;
798 802
            } else {
799 803
              excess -= rem;
800 804
              (*_excess)[v] += rem;
801 805
              _flow->set(e, (*_capacity)[e]);
802 806
            }
803 807
          } else if (new_level > (*_level)[v]) {
804 808
            new_level = (*_level)[v];
805 809
          }
806 810
        }
807 811

	
808 812
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
809 813
          Value rem = (*_flow)[e];
810 814
          if (!_tolerance.positive(rem)) continue;
811 815
          Node v = _graph.source(e);
812 816
          if ((*_level)[v] < level) {
813 817
            if (!_level->active(v) && v != _source) {
814 818
              _level->activate(v);
815 819
            }
816 820
            if (!_tolerance.less(rem, excess)) {
817 821
              _flow->set(e, (*_flow)[e] - excess);
818 822
              (*_excess)[v] += excess;
819 823
              excess = 0;
820 824
              goto no_more_push;
821 825
            } else {
822 826
              excess -= rem;
823 827
              (*_excess)[v] += rem;
824 828
              _flow->set(e, 0);
825 829
            }
826 830
          } else if (new_level > (*_level)[v]) {
827 831
            new_level = (*_level)[v];
828 832
          }
829 833
        }
830 834

	
831 835
      no_more_push:
832 836

	
833 837
        (*_excess)[n] = excess;
834 838

	
835 839
        if (excess != 0) {
836 840
          if (new_level + 1 < _level->maxLevel()) {
837 841
            _level->liftHighestActive(new_level + 1);
838 842
          } else {
839 843
            // Calculation error
840 844
            _level->liftHighestActiveToTop();
841 845
          }
842 846
          if (_level->emptyLevel(level)) {
843 847
            // Calculation error
844 848
            _level->liftToTop(level);
845 849
          }
846 850
        } else {
847 851
          _level->deactivate(n);
848 852
        }
849 853

	
850 854
      }
851 855
    }
852 856

	
853 857
    /// \brief Runs the preflow algorithm.
854 858
    ///
855 859
    /// Runs the preflow algorithm.
856 860
    /// \note pf.run() is just a shortcut of the following code.
857 861
    /// \code
858 862
    ///   pf.init();
859 863
    ///   pf.startFirstPhase();
860 864
    ///   pf.startSecondPhase();
861 865
    /// \endcode
862 866
    void run() {
863 867
      init();
864 868
      startFirstPhase();
865 869
      startSecondPhase();
866 870
    }
867 871

	
868 872
    /// \brief Runs the preflow algorithm to compute the minimum cut.
869 873
    ///
870 874
    /// Runs the preflow algorithm to compute the minimum cut.
871 875
    /// \note pf.runMinCut() is just a shortcut of the following code.
872 876
    /// \code
873 877
    ///   pf.init();
874 878
    ///   pf.startFirstPhase();
875 879
    /// \endcode
876 880
    void runMinCut() {
877 881
      init();
878 882
      startFirstPhase();
879 883
    }
880 884

	
881 885
    /// @}
882 886

	
883 887
    /// \name Query Functions
884 888
    /// The results of the preflow algorithm can be obtained using these
885 889
    /// functions.\n
886 890
    /// Either one of the \ref run() "run*()" functions or one of the
887 891
    /// \ref startFirstPhase() "start*()" functions should be called
888 892
    /// before using them.
889 893

	
890 894
    ///@{
891 895

	
892 896
    /// \brief Returns the value of the maximum flow.
893 897
    ///
894 898
    /// Returns the value of the maximum flow by returning the excess
895 899
    /// of the target node. This value equals to the value of
896 900
    /// the maximum flow already after the first phase of the algorithm.
897 901
    ///
898 902
    /// \pre Either \ref run() or \ref init() must be called before
899 903
    /// using this function.
900 904
    Value flowValue() const {
901 905
      return (*_excess)[_target];
902 906
    }
903 907

	
904 908
    /// \brief Returns the flow value on the given arc.
905 909
    ///
906 910
    /// Returns the flow value on the given arc. This method can
907 911
    /// be called after the second phase of the algorithm.
908 912
    ///
909 913
    /// \pre Either \ref run() or \ref init() must be called before
910 914
    /// using this function.
911 915
    Value flow(const Arc& arc) const {
912 916
      return (*_flow)[arc];
913 917
    }
914 918

	
915 919
    /// \brief Returns a const reference to the flow map.
916 920
    ///
917 921
    /// Returns a const reference to the arc map storing the found flow.
918 922
    /// This method can be called after the second phase of the algorithm.
919 923
    ///
920 924
    /// \pre Either \ref run() or \ref init() must be called before
921 925
    /// using this function.
922 926
    const FlowMap& flowMap() const {
923 927
      return *_flow;
924 928
    }
925 929

	
926 930
    /// \brief Returns \c true when the node is on the source side of the
927 931
    /// minimum cut.
928 932
    ///
929 933
    /// Returns true when the node is on the source side of the found
930 934
    /// minimum cut. This method can be called both after running \ref
931 935
    /// startFirstPhase() and \ref startSecondPhase().
932 936
    ///
933 937
    /// \pre Either \ref run() or \ref init() must be called before
934 938
    /// using this function.
935 939
    bool minCut(const Node& node) const {
936 940
      return ((*_level)[node] == _level->maxLevel()) == _phase;
937 941
    }
938 942

	
939 943
    /// \brief Gives back a minimum value cut.
940 944
    ///
941 945
    /// Sets \c cutMap to the characteristic vector of a minimum value
942 946
    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
943 947
    /// node map with \c bool (or convertible) value type.
944 948
    ///
945 949
    /// This method can be called both after running \ref startFirstPhase()
946 950
    /// and \ref startSecondPhase(). The result after the second phase
947 951
    /// could be slightly different if inexact computation is used.
948 952
    ///
949 953
    /// \note This function calls \ref minCut() for each node, so it runs in
950 954
    /// O(n) time.
951 955
    ///
952 956
    /// \pre Either \ref run() or \ref init() must be called before
953 957
    /// using this function.
954 958
    template <typename CutMap>
955 959
    void minCutMap(CutMap& cutMap) const {
956 960
      for (NodeIt n(_graph); n != INVALID; ++n) {
957 961
        cutMap.set(n, minCut(n));
958 962
      }
959 963
    }
960 964

	
961 965
    /// @}
962 966
  };
963 967
}
964 968

	
965 969
#endif
0 comments (0 inline)