gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge bugfix #372 to branch 1.2
0 1 0
merge 1.2
1 file changed with 24 insertions and 20 deletions:
↑ Collapse diff ↑
Ignore white space 1536 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_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
#ifdef DOXYGEN
56 56
    typedef GR::ArcMap<Value> FlowMap;
57 57
#else
58 58
    typedef typename Digraph::template ArcMap<Value> FlowMap;
59 59
#endif
60 60

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

	
70 70
    /// \brief The elevator type used by Preflow algorithm.
71 71
    ///
72 72
    /// The elevator type used by Preflow algorithm.
73 73
    ///
74 74
    /// \sa Elevator, LinkedElevator
75 75
#ifdef DOXYGEN
76 76
    typedef lemon::Elevator<GR, GR::Node> Elevator;
77 77
#else
78 78
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
79 79
#endif
80 80

	
81 81
    /// \brief Instantiates an Elevator.
82 82
    ///
83 83
    /// This function instantiates an \ref Elevator.
84 84
    /// \param digraph The digraph for which we would like to define
85 85
    /// the elevator.
86 86
    /// \param max_level The maximum level of the elevator.
87 87
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
88 88
      return new Elevator(digraph, max_level);
89 89
    }
90 90

	
91 91
    /// \brief The tolerance used by the algorithm
92 92
    ///
93 93
    /// The tolerance used by the algorithm to handle inexact computation.
94 94
    typedef lemon::Tolerance<Value> Tolerance;
95 95

	
96 96
  };
97 97

	
98 98

	
99 99
  /// \ingroup max_flow
100 100
  ///
101 101
  /// \brief %Preflow algorithm class.
102 102
  ///
103 103
  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
104 104
  /// \e push-relabel algorithm producing a \ref max_flow
105 105
  /// "flow of maximum value" in a digraph \ref clrs01algorithms,
106 106
  /// \ref amo93networkflows, \ref goldberg88newapproach.
107 107
  /// The preflow algorithms are the fastest known maximum
108 108
  /// flow algorithms. The current implementation uses a mixture of the
109 109
  /// \e "highest label" and the \e "bound decrease" heuristics.
110 110
  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
111 111
  ///
112 112
  /// The algorithm consists of two phases. After the first phase
113 113
  /// the maximum flow value and the minimum cut is obtained. The
114 114
  /// second phase constructs a feasible maximum flow on each arc.
115 115
  ///
116 116
  /// \warning This implementation cannot handle infinite or very large
117 117
  /// capacities (e.g. the maximum value of \c CAP::Value).
118 118
  ///
119 119
  /// \tparam GR The type of the digraph the algorithm runs on.
120 120
  /// \tparam CAP The type of the capacity map. The default map
121 121
  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
122 122
  /// \tparam TR The traits class that defines various types used by the
123 123
  /// algorithm. By default, it is \ref PreflowDefaultTraits
124 124
  /// "PreflowDefaultTraits<GR, CAP>".
125 125
  /// In most cases, this parameter should not be set directly,
126 126
  /// consider to use the named template parameters instead.
127 127
#ifdef DOXYGEN
128 128
  template <typename GR, typename CAP, typename TR>
129 129
#else
130 130
  template <typename GR,
131 131
            typename CAP = typename GR::template ArcMap<int>,
132 132
            typename TR = PreflowDefaultTraits<GR, CAP> >
133 133
#endif
134 134
  class Preflow {
135 135
  public:
136 136

	
137 137
    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
138 138
    typedef TR Traits;
139 139
    ///The type of the digraph the algorithm runs on.
140 140
    typedef typename Traits::Digraph Digraph;
141 141
    ///The type of the capacity map.
142 142
    typedef typename Traits::CapacityMap CapacityMap;
143 143
    ///The type of the flow values.
144 144
    typedef typename Traits::Value Value;
145 145

	
146 146
    ///The type of the flow map.
147 147
    typedef typename Traits::FlowMap FlowMap;
148 148
    ///The type of the elevator.
149 149
    typedef typename Traits::Elevator Elevator;
150 150
    ///The type of the tolerance.
151 151
    typedef typename Traits::Tolerance Tolerance;
152 152

	
153 153
  private:
154 154

	
155 155
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
156 156

	
157 157
    const Digraph& _graph;
158 158
    const CapacityMap* _capacity;
159 159

	
160 160
    int _node_num;
161 161

	
162 162
    Node _source, _target;
163 163

	
164 164
    FlowMap* _flow;
165 165
    bool _local_flow;
166 166

	
167 167
    Elevator* _level;
168 168
    bool _local_level;
169 169

	
170 170
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
171 171
    ExcessMap* _excess;
172 172

	
173 173
    Tolerance _tolerance;
174 174

	
175 175
    bool _phase;
176 176

	
177 177

	
178 178
    void createStructures() {
179 179
      _node_num = countNodes(_graph);
180 180

	
181 181
      if (!_flow) {
182 182
        _flow = Traits::createFlowMap(_graph);
183 183
        _local_flow = true;
184 184
      }
185 185
      if (!_level) {
186 186
        _level = Traits::createElevator(_graph, _node_num);
187 187
        _local_level = true;
188 188
      }
189 189
      if (!_excess) {
190 190
        _excess = new ExcessMap(_graph);
191 191
      }
192 192
    }
193 193

	
194 194
    void destroyStructures() {
195 195
      if (_local_flow) {
196 196
        delete _flow;
197 197
      }
198 198
      if (_local_level) {
199 199
        delete _level;
200 200
      }
201 201
      if (_excess) {
202 202
        delete _excess;
203 203
      }
204 204
    }
205 205

	
206 206
  public:
207 207

	
208 208
    typedef Preflow Create;
209 209

	
210 210
    ///\name Named Template Parameters
211 211

	
212 212
    ///@{
213 213

	
214 214
    template <typename T>
215 215
    struct SetFlowMapTraits : public Traits {
216 216
      typedef T FlowMap;
217 217
      static FlowMap *createFlowMap(const Digraph&) {
218 218
        LEMON_ASSERT(false, "FlowMap is not initialized");
219 219
        return 0; // ignore warnings
220 220
      }
221 221
    };
222 222

	
223 223
    /// \brief \ref named-templ-param "Named parameter" for setting
224 224
    /// FlowMap type
225 225
    ///
226 226
    /// \ref named-templ-param "Named parameter" for setting FlowMap
227 227
    /// type.
228 228
    template <typename T>
229 229
    struct SetFlowMap
230 230
      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
231 231
      typedef Preflow<Digraph, CapacityMap,
232 232
                      SetFlowMapTraits<T> > Create;
233 233
    };
234 234

	
235 235
    template <typename T>
236 236
    struct SetElevatorTraits : public Traits {
237 237
      typedef T Elevator;
238 238
      static Elevator *createElevator(const Digraph&, int) {
239 239
        LEMON_ASSERT(false, "Elevator is not initialized");
240 240
        return 0; // ignore warnings
241 241
      }
242 242
    };
243 243

	
244 244
    /// \brief \ref named-templ-param "Named parameter" for setting
245 245
    /// Elevator type
246 246
    ///
247 247
    /// \ref named-templ-param "Named parameter" for setting Elevator
248 248
    /// type. If this named parameter is used, then an external
249 249
    /// elevator object must be passed to the algorithm using the
250 250
    /// \ref elevator(Elevator&) "elevator()" function before calling
251 251
    /// \ref run() or \ref init().
252 252
    /// \sa SetStandardElevator
253 253
    template <typename T>
254 254
    struct SetElevator
255 255
      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
256 256
      typedef Preflow<Digraph, CapacityMap,
257 257
                      SetElevatorTraits<T> > Create;
258 258
    };
259 259

	
260 260
    template <typename T>
261 261
    struct SetStandardElevatorTraits : public Traits {
262 262
      typedef T Elevator;
263 263
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
264 264
        return new Elevator(digraph, max_level);
265 265
      }
266 266
    };
267 267

	
268 268
    /// \brief \ref named-templ-param "Named parameter" for setting
269 269
    /// Elevator type with automatic allocation
270 270
    ///
271 271
    /// \ref named-templ-param "Named parameter" for setting Elevator
272 272
    /// type with automatic allocation.
273 273
    /// The Elevator should have standard constructor interface to be
274 274
    /// able to automatically created by the algorithm (i.e. the
275 275
    /// digraph and the maximum level should be passed to it).
276 276
    /// However, an external elevator object could also be passed to the
277 277
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
278 278
    /// before calling \ref run() or \ref init().
279 279
    /// \sa SetElevator
280 280
    template <typename T>
281 281
    struct SetStandardElevator
282 282
      : public Preflow<Digraph, CapacityMap,
283 283
                       SetStandardElevatorTraits<T> > {
284 284
      typedef Preflow<Digraph, CapacityMap,
285 285
                      SetStandardElevatorTraits<T> > Create;
286 286
    };
287 287

	
288 288
    /// @}
289 289

	
290 290
  protected:
291 291

	
292 292
    Preflow() {}
293 293

	
294 294
  public:
295 295

	
296 296

	
297 297
    /// \brief The constructor of the class.
298 298
    ///
299 299
    /// The constructor of the class.
300 300
    /// \param digraph The digraph the algorithm runs on.
301 301
    /// \param capacity The capacity of the arcs.
302 302
    /// \param source The source node.
303 303
    /// \param target The target node.
304 304
    Preflow(const Digraph& digraph, const CapacityMap& capacity,
305 305
            Node source, Node target)
306 306
      : _graph(digraph), _capacity(&capacity),
307 307
        _node_num(0), _source(source), _target(target),
308 308
        _flow(0), _local_flow(false),
309 309
        _level(0), _local_level(false),
310 310
        _excess(0), _tolerance(), _phase() {}
311 311

	
312 312
    /// \brief Destructor.
313 313
    ///
314 314
    /// Destructor.
315 315
    ~Preflow() {
316 316
      destroyStructures();
317 317
    }
318 318

	
319 319
    /// \brief Sets the capacity map.
320 320
    ///
321 321
    /// Sets the capacity map.
322 322
    /// \return <tt>(*this)</tt>
323 323
    Preflow& capacityMap(const CapacityMap& map) {
324 324
      _capacity = &map;
325 325
      return *this;
326 326
    }
327 327

	
328 328
    /// \brief Sets the flow map.
329 329
    ///
330 330
    /// Sets the flow map.
331 331
    /// If you don't use this function before calling \ref run() or
332 332
    /// \ref init(), an instance will be allocated automatically.
333 333
    /// The destructor deallocates this automatically allocated map,
334 334
    /// of course.
335 335
    /// \return <tt>(*this)</tt>
336 336
    Preflow& flowMap(FlowMap& map) {
337 337
      if (_local_flow) {
338 338
        delete _flow;
339 339
        _local_flow = false;
340 340
      }
341 341
      _flow = &map;
342 342
      return *this;
343 343
    }
344 344

	
345 345
    /// \brief Sets the source node.
346 346
    ///
347 347
    /// Sets the source node.
348 348
    /// \return <tt>(*this)</tt>
349 349
    Preflow& source(const Node& node) {
350 350
      _source = node;
351 351
      return *this;
352 352
    }
353 353

	
354 354
    /// \brief Sets the target node.
355 355
    ///
356 356
    /// Sets the target node.
357 357
    /// \return <tt>(*this)</tt>
358 358
    Preflow& target(const Node& node) {
359 359
      _target = node;
360 360
      return *this;
361 361
    }
362 362

	
363 363
    /// \brief Sets the elevator used by algorithm.
364 364
    ///
365 365
    /// Sets the elevator used by algorithm.
366 366
    /// If you don't use this function before calling \ref run() or
367 367
    /// \ref init(), an instance will be allocated automatically.
368 368
    /// The destructor deallocates this automatically allocated elevator,
369 369
    /// of course.
370 370
    /// \return <tt>(*this)</tt>
371 371
    Preflow& elevator(Elevator& elevator) {
372 372
      if (_local_level) {
373 373
        delete _level;
374 374
        _local_level = false;
375 375
      }
376 376
      _level = &elevator;
377 377
      return *this;
378 378
    }
379 379

	
380 380
    /// \brief Returns a const reference to the elevator.
381 381
    ///
382 382
    /// Returns a const reference to the elevator.
383 383
    ///
384 384
    /// \pre Either \ref run() or \ref init() must be called before
385 385
    /// using this function.
386 386
    const Elevator& elevator() const {
387 387
      return *_level;
388 388
    }
389 389

	
390 390
    /// \brief Sets the tolerance used by the algorithm.
391 391
    ///
392 392
    /// Sets the tolerance object used by the algorithm.
393 393
    /// \return <tt>(*this)</tt>
394 394
    Preflow& tolerance(const Tolerance& tolerance) {
395 395
      _tolerance = tolerance;
396 396
      return *this;
397 397
    }
398 398

	
399 399
    /// \brief Returns a const reference to the tolerance.
400 400
    ///
401 401
    /// Returns a const reference to the tolerance object used by
402 402
    /// the algorithm.
403 403
    const Tolerance& tolerance() const {
404 404
      return _tolerance;
405 405
    }
406 406

	
407 407
    /// \name Execution Control
408 408
    /// The simplest way to execute the preflow algorithm is to use
409 409
    /// \ref run() or \ref runMinCut().\n
410 410
    /// If you need better control on the initial solution or the execution,
411 411
    /// you have to call one of the \ref init() functions first, then
412 412
    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
413 413

	
414 414
    ///@{
415 415

	
416 416
    /// \brief Initializes the internal data structures.
417 417
    ///
418 418
    /// Initializes the internal data structures and sets the initial
419 419
    /// flow to zero on each arc.
420 420
    void init() {
421 421
      createStructures();
422 422

	
423 423
      _phase = true;
424 424
      for (NodeIt n(_graph); n != INVALID; ++n) {
425 425
        (*_excess)[n] = 0;
426 426
      }
427 427

	
428 428
      for (ArcIt e(_graph); e != INVALID; ++e) {
429 429
        _flow->set(e, 0);
430 430
      }
431 431

	
432 432
      typename Digraph::template NodeMap<bool> reached(_graph, false);
433 433

	
434 434
      _level->initStart();
435 435
      _level->initAddItem(_target);
436 436

	
437 437
      std::vector<Node> queue;
438 438
      reached[_source] = true;
439 439

	
440 440
      queue.push_back(_target);
441 441
      reached[_target] = true;
442 442
      while (!queue.empty()) {
443 443
        _level->initNewLevel();
444 444
        std::vector<Node> nqueue;
445 445
        for (int i = 0; i < int(queue.size()); ++i) {
446 446
          Node n = queue[i];
447 447
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
448 448
            Node u = _graph.source(e);
449 449
            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
450 450
              reached[u] = true;
451 451
              _level->initAddItem(u);
452 452
              nqueue.push_back(u);
453 453
            }
454 454
          }
455 455
        }
456 456
        queue.swap(nqueue);
457 457
      }
458 458
      _level->initFinish();
459 459

	
460 460
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
461 461
        if (_tolerance.positive((*_capacity)[e])) {
462 462
          Node u = _graph.target(e);
463 463
          if ((*_level)[u] == _level->maxLevel()) continue;
464 464
          _flow->set(e, (*_capacity)[e]);
465 465
          (*_excess)[u] += (*_capacity)[e];
466 466
          if (u != _target && !_level->active(u)) {
467 467
            _level->activate(u);
468 468
          }
469 469
        }
470 470
      }
471 471
    }
472 472

	
473 473
    /// \brief Initializes the internal data structures using the
474 474
    /// given flow map.
475 475
    ///
476 476
    /// Initializes the internal data structures and sets the initial
477 477
    /// flow to the given \c flowMap. The \c flowMap should contain a
478 478
    /// flow or at least a preflow, i.e. at each node excluding the
479 479
    /// source node the incoming flow should greater or equal to the
480 480
    /// outgoing flow.
481 481
    /// \return \c false if the given \c flowMap is not a preflow.
482 482
    template <typename FlowMap>
483 483
    bool init(const FlowMap& flowMap) {
484 484
      createStructures();
485 485

	
486 486
      for (ArcIt e(_graph); e != INVALID; ++e) {
487 487
        _flow->set(e, flowMap[e]);
488 488
      }
489 489

	
490 490
      for (NodeIt n(_graph); n != INVALID; ++n) {
491 491
        Value excess = 0;
492 492
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
493 493
          excess += (*_flow)[e];
494 494
        }
495 495
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
496 496
          excess -= (*_flow)[e];
497 497
        }
498 498
        if (excess < 0 && n != _source) return false;
499 499
        (*_excess)[n] = excess;
500 500
      }
501 501

	
502 502
      typename Digraph::template NodeMap<bool> reached(_graph, false);
503 503

	
504 504
      _level->initStart();
505 505
      _level->initAddItem(_target);
506 506

	
507 507
      std::vector<Node> queue;
508 508
      reached[_source] = true;
509 509

	
510 510
      queue.push_back(_target);
511 511
      reached[_target] = true;
512 512
      while (!queue.empty()) {
513 513
        _level->initNewLevel();
514 514
        std::vector<Node> nqueue;
515 515
        for (int i = 0; i < int(queue.size()); ++i) {
516 516
          Node n = queue[i];
517 517
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
518 518
            Node u = _graph.source(e);
519 519
            if (!reached[u] &&
520 520
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
521 521
              reached[u] = true;
522 522
              _level->initAddItem(u);
523 523
              nqueue.push_back(u);
524 524
            }
525 525
          }
526 526
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
527 527
            Node v = _graph.target(e);
528 528
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
529 529
              reached[v] = true;
530 530
              _level->initAddItem(v);
531 531
              nqueue.push_back(v);
532 532
            }
533 533
          }
534 534
        }
535 535
        queue.swap(nqueue);
536 536
      }
537 537
      _level->initFinish();
538 538

	
539 539
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
540 540
        Value rem = (*_capacity)[e] - (*_flow)[e];
541 541
        if (_tolerance.positive(rem)) {
542 542
          Node u = _graph.target(e);
543 543
          if ((*_level)[u] == _level->maxLevel()) continue;
544 544
          _flow->set(e, (*_capacity)[e]);
545 545
          (*_excess)[u] += rem;
546 546
          if (u != _target && !_level->active(u)) {
547 547
            _level->activate(u);
548 548
          }
549 549
        }
550 550
      }
551 551
      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
552 552
        Value rem = (*_flow)[e];
553 553
        if (_tolerance.positive(rem)) {
554 554
          Node v = _graph.source(e);
555 555
          if ((*_level)[v] == _level->maxLevel()) continue;
556 556
          _flow->set(e, 0);
557 557
          (*_excess)[v] += rem;
558 558
          if (v != _target && !_level->active(v)) {
559 559
            _level->activate(v);
560 560
          }
561 561
        }
562 562
      }
563 563
      return true;
564 564
    }
565 565

	
566 566
    /// \brief Starts the first phase of the preflow algorithm.
567 567
    ///
568 568
    /// The preflow algorithm consists of two phases, this method runs
569 569
    /// the first phase. After the first phase the maximum flow value
570 570
    /// and a minimum value cut can already be computed, although a
571 571
    /// maximum flow is not yet obtained. So after calling this method
572 572
    /// \ref flowValue() returns the value of a maximum flow and \ref
573 573
    /// minCut() returns a minimum cut.
574 574
    /// \pre One of the \ref init() functions must be called before
575 575
    /// using this function.
576 576
    void startFirstPhase() {
577 577
      _phase = true;
578 578

	
579
      Node n = _level->highestActive();
580
      int level = _level->highestActiveLevel();
581
      while (n != INVALID) {
579
      while (true) {
582 580
        int num = _node_num;
583 581

	
584
        while (num > 0 && n != INVALID) {
582
        Node n = INVALID;
583
        int level = -1;
584

	
585
        while (num > 0) {
586
          n = _level->highestActive();
587
          if (n == INVALID) goto first_phase_done;
588
          level = _level->highestActiveLevel();
589
          --num;
590
          
585 591
          Value excess = (*_excess)[n];
586 592
          int new_level = _level->maxLevel();
587 593

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

	
611 617
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
612 618
            Value rem = (*_flow)[e];
613 619
            if (!_tolerance.positive(rem)) continue;
614 620
            Node v = _graph.source(e);
615 621
            if ((*_level)[v] < level) {
616 622
              if (!_level->active(v) && v != _target) {
617 623
                _level->activate(v);
618 624
              }
619 625
              if (!_tolerance.less(rem, excess)) {
620 626
                _flow->set(e, (*_flow)[e] - excess);
621 627
                (*_excess)[v] += excess;
622 628
                excess = 0;
623 629
                goto no_more_push_1;
624 630
              } else {
625 631
                excess -= rem;
626 632
                (*_excess)[v] += rem;
627 633
                _flow->set(e, 0);
628 634
              }
629 635
            } else if (new_level > (*_level)[v]) {
630 636
              new_level = (*_level)[v];
631 637
            }
632 638
          }
633 639

	
634 640
        no_more_push_1:
635 641

	
636 642
          (*_excess)[n] = excess;
637 643

	
638 644
          if (excess != 0) {
639 645
            if (new_level + 1 < _level->maxLevel()) {
640 646
              _level->liftHighestActive(new_level + 1);
641 647
            } else {
642 648
              _level->liftHighestActiveToTop();
643 649
            }
644 650
            if (_level->emptyLevel(level)) {
645 651
              _level->liftToTop(level);
646 652
            }
647 653
          } else {
648 654
            _level->deactivate(n);
649 655
          }
650

	
651
          n = _level->highestActive();
652
          level = _level->highestActiveLevel();
653
          --num;
654 656
        }
655 657

	
656 658
        num = _node_num * 20;
657
        while (num > 0 && n != INVALID) {
659
        while (num > 0) {
660
          while (level >= 0 && _level->activeFree(level)) {
661
            --level;
662
          }
663
          if (level == -1) {
664
            n = _level->highestActive();
665
            level = _level->highestActiveLevel();
666
            if (n == INVALID) goto first_phase_done;
667
          } else {
668
            n = _level->activeOn(level);
669
          }
670
          --num;
671

	
658 672
          Value excess = (*_excess)[n];
659 673
          int new_level = _level->maxLevel();
660 674

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

	
684 698
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
685 699
            Value rem = (*_flow)[e];
686 700
            if (!_tolerance.positive(rem)) continue;
687 701
            Node v = _graph.source(e);
688 702
            if ((*_level)[v] < level) {
689 703
              if (!_level->active(v) && v != _target) {
690 704
                _level->activate(v);
691 705
              }
692 706
              if (!_tolerance.less(rem, excess)) {
693 707
                _flow->set(e, (*_flow)[e] - excess);
694 708
                (*_excess)[v] += excess;
695 709
                excess = 0;
696 710
                goto no_more_push_2;
697 711
              } else {
698 712
                excess -= rem;
699 713
                (*_excess)[v] += rem;
700 714
                _flow->set(e, 0);
701 715
              }
702 716
            } else if (new_level > (*_level)[v]) {
703 717
              new_level = (*_level)[v];
704 718
            }
705 719
          }
706 720

	
707 721
        no_more_push_2:
708 722

	
709 723
          (*_excess)[n] = excess;
710 724

	
711 725
          if (excess != 0) {
712 726
            if (new_level + 1 < _level->maxLevel()) {
713 727
              _level->liftActiveOn(level, new_level + 1);
714 728
            } else {
715 729
              _level->liftActiveToTop(level);
716 730
            }
717 731
            if (_level->emptyLevel(level)) {
718 732
              _level->liftToTop(level);
719 733
            }
720 734
          } else {
721 735
            _level->deactivate(n);
722 736
          }
723

	
724
          while (level >= 0 && _level->activeFree(level)) {
725
            --level;
726
          }
727
          if (level == -1) {
728
            n = _level->highestActive();
729
            level = _level->highestActiveLevel();
730
          } else {
731
            n = _level->activeOn(level);
732
          }
733
          --num;
734 737
        }
735 738
      }
739
    first_phase_done:;
736 740
    }
737 741

	
738 742
    /// \brief Starts the second phase of the preflow algorithm.
739 743
    ///
740 744
    /// The preflow algorithm consists of two phases, this method runs
741 745
    /// the second phase. After calling one of the \ref init() functions
742 746
    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
743 747
    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
744 748
    /// value of a maximum flow, \ref minCut() returns a minimum cut
745 749
    /// \pre One of the \ref init() functions and \ref startFirstPhase()
746 750
    /// must be called before using this function.
747 751
    void startSecondPhase() {
748 752
      _phase = false;
749 753

	
750 754
      typename Digraph::template NodeMap<bool> reached(_graph);
751 755
      for (NodeIt n(_graph); n != INVALID; ++n) {
752 756
        reached[n] = (*_level)[n] < _level->maxLevel();
753 757
      }
754 758

	
755 759
      _level->initStart();
756 760
      _level->initAddItem(_source);
757 761

	
758 762
      std::vector<Node> queue;
759 763
      queue.push_back(_source);
760 764
      reached[_source] = true;
761 765

	
762 766
      while (!queue.empty()) {
763 767
        _level->initNewLevel();
764 768
        std::vector<Node> nqueue;
765 769
        for (int i = 0; i < int(queue.size()); ++i) {
766 770
          Node n = queue[i];
767 771
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
768 772
            Node v = _graph.target(e);
769 773
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
770 774
              reached[v] = true;
771 775
              _level->initAddItem(v);
772 776
              nqueue.push_back(v);
773 777
            }
774 778
          }
775 779
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
776 780
            Node u = _graph.source(e);
777 781
            if (!reached[u] &&
778 782
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
779 783
              reached[u] = true;
780 784
              _level->initAddItem(u);
781 785
              nqueue.push_back(u);
782 786
            }
783 787
          }
784 788
        }
785 789
        queue.swap(nqueue);
786 790
      }
787 791
      _level->initFinish();
788 792

	
789 793
      for (NodeIt n(_graph); n != INVALID; ++n) {
790 794
        if (!reached[n]) {
791 795
          _level->dirtyTopButOne(n);
792 796
        } else if ((*_excess)[n] > 0 && _target != n) {
793 797
          _level->activate(n);
794 798
        }
795 799
      }
796 800

	
797 801
      Node n;
798 802
      while ((n = _level->highestActive()) != INVALID) {
799 803
        Value excess = (*_excess)[n];
800 804
        int level = _level->highestActiveLevel();
801 805
        int new_level = _level->maxLevel();
802 806

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

	
826 830
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
827 831
          Value rem = (*_flow)[e];
828 832
          if (!_tolerance.positive(rem)) continue;
829 833
          Node v = _graph.source(e);
830 834
          if ((*_level)[v] < level) {
831 835
            if (!_level->active(v) && v != _source) {
832 836
              _level->activate(v);
833 837
            }
834 838
            if (!_tolerance.less(rem, excess)) {
835 839
              _flow->set(e, (*_flow)[e] - excess);
836 840
              (*_excess)[v] += excess;
837 841
              excess = 0;
838 842
              goto no_more_push;
839 843
            } else {
840 844
              excess -= rem;
841 845
              (*_excess)[v] += rem;
842 846
              _flow->set(e, 0);
843 847
            }
844 848
          } else if (new_level > (*_level)[v]) {
845 849
            new_level = (*_level)[v];
846 850
          }
847 851
        }
848 852

	
849 853
      no_more_push:
850 854

	
851 855
        (*_excess)[n] = excess;
852 856

	
853 857
        if (excess != 0) {
854 858
          if (new_level + 1 < _level->maxLevel()) {
855 859
            _level->liftHighestActive(new_level + 1);
856 860
          } else {
857 861
            // Calculation error
858 862
            _level->liftHighestActiveToTop();
859 863
          }
860 864
          if (_level->emptyLevel(level)) {
861 865
            // Calculation error
862 866
            _level->liftToTop(level);
863 867
          }
864 868
        } else {
865 869
          _level->deactivate(n);
866 870
        }
867 871

	
868 872
      }
869 873
    }
870 874

	
871 875
    /// \brief Runs the preflow algorithm.
872 876
    ///
873 877
    /// Runs the preflow algorithm.
874 878
    /// \note pf.run() is just a shortcut of the following code.
875 879
    /// \code
876 880
    ///   pf.init();
877 881
    ///   pf.startFirstPhase();
878 882
    ///   pf.startSecondPhase();
879 883
    /// \endcode
880 884
    void run() {
881 885
      init();
882 886
      startFirstPhase();
883 887
      startSecondPhase();
884 888
    }
885 889

	
886 890
    /// \brief Runs the preflow algorithm to compute the minimum cut.
887 891
    ///
888 892
    /// Runs the preflow algorithm to compute the minimum cut.
889 893
    /// \note pf.runMinCut() is just a shortcut of the following code.
890 894
    /// \code
891 895
    ///   pf.init();
892 896
    ///   pf.startFirstPhase();
893 897
    /// \endcode
894 898
    void runMinCut() {
895 899
      init();
896 900
      startFirstPhase();
897 901
    }
898 902

	
899 903
    /// @}
900 904

	
901 905
    /// \name Query Functions
902 906
    /// The results of the preflow algorithm can be obtained using these
903 907
    /// functions.\n
904 908
    /// Either one of the \ref run() "run*()" functions or one of the
905 909
    /// \ref startFirstPhase() "start*()" functions should be called
906 910
    /// before using them.
907 911

	
908 912
    ///@{
909 913

	
910 914
    /// \brief Returns the value of the maximum flow.
911 915
    ///
912 916
    /// Returns the value of the maximum flow by returning the excess
913 917
    /// of the target node. This value equals to the value of
914 918
    /// the maximum flow already after the first phase of the algorithm.
915 919
    ///
916 920
    /// \pre Either \ref run() or \ref init() must be called before
917 921
    /// using this function.
918 922
    Value flowValue() const {
919 923
      return (*_excess)[_target];
920 924
    }
921 925

	
922 926
    /// \brief Returns the flow value on the given arc.
923 927
    ///
924 928
    /// Returns the flow value on the given arc. This method can
925 929
    /// be called after the second phase of the algorithm.
926 930
    ///
927 931
    /// \pre Either \ref run() or \ref init() must be called before
928 932
    /// using this function.
929 933
    Value flow(const Arc& arc) const {
930 934
      return (*_flow)[arc];
931 935
    }
932 936

	
933 937
    /// \brief Returns a const reference to the flow map.
934 938
    ///
935 939
    /// Returns a const reference to the arc map storing the found flow.
936 940
    /// This method can be called after the second phase of the algorithm.
937 941
    ///
938 942
    /// \pre Either \ref run() or \ref init() must be called before
939 943
    /// using this function.
940 944
    const FlowMap& flowMap() const {
941 945
      return *_flow;
942 946
    }
943 947

	
944 948
    /// \brief Returns \c true when the node is on the source side of the
945 949
    /// minimum cut.
946 950
    ///
947 951
    /// Returns true when the node is on the source side of the found
948 952
    /// minimum cut. This method can be called both after running \ref
949 953
    /// startFirstPhase() and \ref startSecondPhase().
950 954
    ///
951 955
    /// \pre Either \ref run() or \ref init() must be called before
952 956
    /// using this function.
953 957
    bool minCut(const Node& node) const {
954 958
      return ((*_level)[node] == _level->maxLevel()) == _phase;
955 959
    }
956 960

	
957 961
    /// \brief Gives back a minimum value cut.
958 962
    ///
959 963
    /// Sets \c cutMap to the characteristic vector of a minimum value
960 964
    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
961 965
    /// node map with \c bool (or convertible) value type.
962 966
    ///
963 967
    /// This method can be called both after running \ref startFirstPhase()
964 968
    /// and \ref startSecondPhase(). The result after the second phase
965 969
    /// could be slightly different if inexact computation is used.
966 970
    ///
967 971
    /// \note This function calls \ref minCut() for each node, so it runs in
968 972
    /// O(n) time.
969 973
    ///
970 974
    /// \pre Either \ref run() or \ref init() must be called before
971 975
    /// using this function.
972 976
    template <typename CutMap>
973 977
    void minCutMap(CutMap& cutMap) const {
974 978
      for (NodeIt n(_graph); n != INVALID; ++n) {
975 979
        cutMap.set(n, minCut(n));
976 980
      }
977 981
    }
978 982

	
979 983
    /// @}
980 984
  };
981 985
}
982 986

	
983 987
#endif
0 comments (0 inline)