gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Various doc improvements (#331) - Add notes to the graph classes about the time of item counting. - Clarify the doc for run() in BFS and DFS. - Other improvements.
0 11 0
default
11 files changed with 93 insertions and 43 deletions:
↑ Collapse diff ↑
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-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_ADAPTORS_H
20 20
#define LEMON_ADAPTORS_H
21 21

	
22 22
/// \ingroup graph_adaptors
23 23
/// \file
24 24
/// \brief Adaptor classes for digraphs and graphs
25 25
///
26 26
/// This file contains several useful adaptors for digraphs and graphs.
27 27

	
28 28
#include <lemon/core.h>
29 29
#include <lemon/maps.h>
30 30
#include <lemon/bits/variant.h>
31 31

	
32 32
#include <lemon/bits/graph_adaptor_extender.h>
33 33
#include <lemon/bits/map_extender.h>
34 34
#include <lemon/tolerance.h>
35 35

	
36 36
#include <algorithm>
37 37

	
38 38
namespace lemon {
39 39

	
40 40
#ifdef _MSC_VER
41 41
#define LEMON_SCOPE_FIX(OUTER, NESTED) OUTER::NESTED
42 42
#else
43 43
#define LEMON_SCOPE_FIX(OUTER, NESTED) typename OUTER::template NESTED
44 44
#endif
45 45

	
46 46
  template<typename DGR>
47 47
  class DigraphAdaptorBase {
48 48
  public:
49 49
    typedef DGR Digraph;
50 50
    typedef DigraphAdaptorBase Adaptor;
51 51

	
52 52
  protected:
53 53
    DGR* _digraph;
54 54
    DigraphAdaptorBase() : _digraph(0) { }
55 55
    void initialize(DGR& digraph) { _digraph = &digraph; }
56 56

	
57 57
  public:
58 58
    DigraphAdaptorBase(DGR& digraph) : _digraph(&digraph) { }
59 59

	
60 60
    typedef typename DGR::Node Node;
61 61
    typedef typename DGR::Arc Arc;
62 62

	
63 63
    void first(Node& i) const { _digraph->first(i); }
64 64
    void first(Arc& i) const { _digraph->first(i); }
65 65
    void firstIn(Arc& i, const Node& n) const { _digraph->firstIn(i, n); }
66 66
    void firstOut(Arc& i, const Node& n ) const { _digraph->firstOut(i, n); }
67 67

	
68 68
    void next(Node& i) const { _digraph->next(i); }
69 69
    void next(Arc& i) const { _digraph->next(i); }
70 70
    void nextIn(Arc& i) const { _digraph->nextIn(i); }
71 71
    void nextOut(Arc& i) const { _digraph->nextOut(i); }
72 72

	
73 73
    Node source(const Arc& a) const { return _digraph->source(a); }
74 74
    Node target(const Arc& a) const { return _digraph->target(a); }
75 75

	
76 76
    typedef NodeNumTagIndicator<DGR> NodeNumTag;
77 77
    int nodeNum() const { return _digraph->nodeNum(); }
78 78

	
79 79
    typedef ArcNumTagIndicator<DGR> ArcNumTag;
80 80
    int arcNum() const { return _digraph->arcNum(); }
81 81

	
82 82
    typedef FindArcTagIndicator<DGR> FindArcTag;
83 83
    Arc findArc(const Node& u, const Node& v, const Arc& prev = INVALID) const {
84 84
      return _digraph->findArc(u, v, prev);
85 85
    }
86 86

	
87 87
    Node addNode() { return _digraph->addNode(); }
88 88
    Arc addArc(const Node& u, const Node& v) { return _digraph->addArc(u, v); }
89 89

	
90 90
    void erase(const Node& n) { _digraph->erase(n); }
91 91
    void erase(const Arc& a) { _digraph->erase(a); }
92 92

	
93 93
    void clear() { _digraph->clear(); }
94 94

	
95 95
    int id(const Node& n) const { return _digraph->id(n); }
96 96
    int id(const Arc& a) const { return _digraph->id(a); }
97 97

	
98 98
    Node nodeFromId(int ix) const { return _digraph->nodeFromId(ix); }
99 99
    Arc arcFromId(int ix) const { return _digraph->arcFromId(ix); }
100 100

	
101 101
    int maxNodeId() const { return _digraph->maxNodeId(); }
102 102
    int maxArcId() const { return _digraph->maxArcId(); }
103 103

	
104 104
    typedef typename ItemSetTraits<DGR, Node>::ItemNotifier NodeNotifier;
105 105
    NodeNotifier& notifier(Node) const { return _digraph->notifier(Node()); }
106 106

	
107 107
    typedef typename ItemSetTraits<DGR, Arc>::ItemNotifier ArcNotifier;
108 108
    ArcNotifier& notifier(Arc) const { return _digraph->notifier(Arc()); }
109 109

	
110 110
    template <typename V>
111 111
    class NodeMap : public DGR::template NodeMap<V> {
112 112
      typedef typename DGR::template NodeMap<V> Parent;
113 113

	
114 114
    public:
115 115
      explicit NodeMap(const Adaptor& adaptor)
116 116
        : Parent(*adaptor._digraph) {}
117 117
      NodeMap(const Adaptor& adaptor, const V& value)
118 118
        : Parent(*adaptor._digraph, value) { }
119 119

	
120 120
    private:
121 121
      NodeMap& operator=(const NodeMap& cmap) {
122 122
        return operator=<NodeMap>(cmap);
123 123
      }
124 124

	
125 125
      template <typename CMap>
126 126
      NodeMap& operator=(const CMap& cmap) {
127 127
        Parent::operator=(cmap);
128 128
        return *this;
129 129
      }
130 130

	
131 131
    };
132 132

	
133 133
    template <typename V>
134 134
    class ArcMap : public DGR::template ArcMap<V> {
135 135
      typedef typename DGR::template ArcMap<V> Parent;
136 136

	
137 137
    public:
138 138
      explicit ArcMap(const DigraphAdaptorBase<DGR>& adaptor)
139 139
        : Parent(*adaptor._digraph) {}
140 140
      ArcMap(const DigraphAdaptorBase<DGR>& adaptor, const V& value)
141 141
        : Parent(*adaptor._digraph, value) {}
142 142

	
143 143
    private:
144 144
      ArcMap& operator=(const ArcMap& cmap) {
145 145
        return operator=<ArcMap>(cmap);
146 146
      }
147 147

	
148 148
      template <typename CMap>
149 149
      ArcMap& operator=(const CMap& cmap) {
150 150
        Parent::operator=(cmap);
151 151
        return *this;
152 152
      }
153 153

	
154 154
    };
155 155

	
156 156
  };
157 157

	
158 158
  template<typename GR>
159 159
  class GraphAdaptorBase {
160 160
  public:
161 161
    typedef GR Graph;
162 162

	
163 163
  protected:
164 164
    GR* _graph;
165 165

	
166 166
    GraphAdaptorBase() : _graph(0) {}
167 167

	
168 168
    void initialize(GR& graph) { _graph = &graph; }
169 169

	
170 170
  public:
171 171
    GraphAdaptorBase(GR& graph) : _graph(&graph) {}
172 172

	
173 173
    typedef typename GR::Node Node;
174 174
    typedef typename GR::Arc Arc;
175 175
    typedef typename GR::Edge Edge;
176 176

	
177 177
    void first(Node& i) const { _graph->first(i); }
178 178
    void first(Arc& i) const { _graph->first(i); }
179 179
    void first(Edge& i) const { _graph->first(i); }
180 180
    void firstIn(Arc& i, const Node& n) const { _graph->firstIn(i, n); }
181 181
    void firstOut(Arc& i, const Node& n ) const { _graph->firstOut(i, n); }
182 182
    void firstInc(Edge &i, bool &d, const Node &n) const {
183 183
      _graph->firstInc(i, d, n);
184 184
    }
185 185

	
186 186
    void next(Node& i) const { _graph->next(i); }
187 187
    void next(Arc& i) const { _graph->next(i); }
188 188
    void next(Edge& i) const { _graph->next(i); }
189 189
    void nextIn(Arc& i) const { _graph->nextIn(i); }
190 190
    void nextOut(Arc& i) const { _graph->nextOut(i); }
191 191
    void nextInc(Edge &i, bool &d) const { _graph->nextInc(i, d); }
192 192

	
193 193
    Node u(const Edge& e) const { return _graph->u(e); }
194 194
    Node v(const Edge& e) const { return _graph->v(e); }
195 195

	
196 196
    Node source(const Arc& a) const { return _graph->source(a); }
197 197
    Node target(const Arc& a) const { return _graph->target(a); }
198 198

	
199 199
    typedef NodeNumTagIndicator<Graph> NodeNumTag;
200 200
    int nodeNum() const { return _graph->nodeNum(); }
201 201

	
202 202
    typedef ArcNumTagIndicator<Graph> ArcNumTag;
203 203
    int arcNum() const { return _graph->arcNum(); }
204 204

	
205 205
    typedef EdgeNumTagIndicator<Graph> EdgeNumTag;
206 206
    int edgeNum() const { return _graph->edgeNum(); }
207 207

	
208 208
    typedef FindArcTagIndicator<Graph> FindArcTag;
209 209
    Arc findArc(const Node& u, const Node& v,
210 210
                const Arc& prev = INVALID) const {
211 211
      return _graph->findArc(u, v, prev);
212 212
    }
213 213

	
214 214
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
215 215
    Edge findEdge(const Node& u, const Node& v,
216 216
                  const Edge& prev = INVALID) const {
217 217
      return _graph->findEdge(u, v, prev);
218 218
    }
219 219

	
220 220
    Node addNode() { return _graph->addNode(); }
221 221
    Edge addEdge(const Node& u, const Node& v) { return _graph->addEdge(u, v); }
222 222

	
223 223
    void erase(const Node& i) { _graph->erase(i); }
224 224
    void erase(const Edge& i) { _graph->erase(i); }
225 225

	
226 226
    void clear() { _graph->clear(); }
227 227

	
228 228
    bool direction(const Arc& a) const { return _graph->direction(a); }
229 229
    Arc direct(const Edge& e, bool d) const { return _graph->direct(e, d); }
230 230

	
231 231
    int id(const Node& v) const { return _graph->id(v); }
232 232
    int id(const Arc& a) const { return _graph->id(a); }
233 233
    int id(const Edge& e) const { return _graph->id(e); }
234 234

	
235 235
    Node nodeFromId(int ix) const { return _graph->nodeFromId(ix); }
236 236
    Arc arcFromId(int ix) const { return _graph->arcFromId(ix); }
237 237
    Edge edgeFromId(int ix) const { return _graph->edgeFromId(ix); }
238 238

	
239 239
    int maxNodeId() const { return _graph->maxNodeId(); }
240 240
    int maxArcId() const { return _graph->maxArcId(); }
241 241
    int maxEdgeId() const { return _graph->maxEdgeId(); }
242 242

	
243 243
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
244 244
    NodeNotifier& notifier(Node) const { return _graph->notifier(Node()); }
245 245

	
246 246
    typedef typename ItemSetTraits<GR, Arc>::ItemNotifier ArcNotifier;
247 247
    ArcNotifier& notifier(Arc) const { return _graph->notifier(Arc()); }
248 248

	
249 249
    typedef typename ItemSetTraits<GR, Edge>::ItemNotifier EdgeNotifier;
250 250
    EdgeNotifier& notifier(Edge) const { return _graph->notifier(Edge()); }
251 251

	
252 252
    template <typename V>
253 253
    class NodeMap : public GR::template NodeMap<V> {
254 254
      typedef typename GR::template NodeMap<V> Parent;
255 255

	
256 256
    public:
257 257
      explicit NodeMap(const GraphAdaptorBase<GR>& adapter)
258 258
        : Parent(*adapter._graph) {}
259 259
      NodeMap(const GraphAdaptorBase<GR>& adapter, const V& value)
260 260
        : Parent(*adapter._graph, value) {}
261 261

	
262 262
    private:
263 263
      NodeMap& operator=(const NodeMap& cmap) {
264 264
        return operator=<NodeMap>(cmap);
265 265
      }
266 266

	
267 267
      template <typename CMap>
268 268
      NodeMap& operator=(const CMap& cmap) {
269 269
        Parent::operator=(cmap);
270 270
        return *this;
271 271
      }
272 272

	
273 273
    };
274 274

	
275 275
    template <typename V>
276 276
    class ArcMap : public GR::template ArcMap<V> {
277 277
      typedef typename GR::template ArcMap<V> Parent;
278 278

	
279 279
    public:
280 280
      explicit ArcMap(const GraphAdaptorBase<GR>& adapter)
281 281
        : Parent(*adapter._graph) {}
282 282
      ArcMap(const GraphAdaptorBase<GR>& adapter, const V& value)
283 283
        : Parent(*adapter._graph, value) {}
284 284

	
285 285
    private:
286 286
      ArcMap& operator=(const ArcMap& cmap) {
287 287
        return operator=<ArcMap>(cmap);
288 288
      }
289 289

	
290 290
      template <typename CMap>
291 291
      ArcMap& operator=(const CMap& cmap) {
292 292
        Parent::operator=(cmap);
293 293
        return *this;
294 294
      }
295 295
    };
296 296

	
297 297
    template <typename V>
298 298
    class EdgeMap : public GR::template EdgeMap<V> {
299 299
      typedef typename GR::template EdgeMap<V> Parent;
300 300

	
301 301
    public:
302 302
      explicit EdgeMap(const GraphAdaptorBase<GR>& adapter)
303 303
        : Parent(*adapter._graph) {}
304 304
      EdgeMap(const GraphAdaptorBase<GR>& adapter, const V& value)
305 305
        : Parent(*adapter._graph, value) {}
306 306

	
307 307
    private:
308 308
      EdgeMap& operator=(const EdgeMap& cmap) {
309 309
        return operator=<EdgeMap>(cmap);
310 310
      }
311 311

	
312 312
      template <typename CMap>
313 313
      EdgeMap& operator=(const CMap& cmap) {
314 314
        Parent::operator=(cmap);
315 315
        return *this;
316 316
      }
317 317
    };
318 318

	
319 319
  };
320 320

	
321 321
  template <typename DGR>
322 322
  class ReverseDigraphBase : public DigraphAdaptorBase<DGR> {
323 323
    typedef DigraphAdaptorBase<DGR> Parent;
324 324
  public:
325 325
    typedef DGR Digraph;
326 326
  protected:
327 327
    ReverseDigraphBase() : Parent() { }
328 328
  public:
329 329
    typedef typename Parent::Node Node;
330 330
    typedef typename Parent::Arc Arc;
331 331

	
332 332
    void firstIn(Arc& a, const Node& n) const { Parent::firstOut(a, n); }
333 333
    void firstOut(Arc& a, const Node& n ) const { Parent::firstIn(a, n); }
334 334

	
335 335
    void nextIn(Arc& a) const { Parent::nextOut(a); }
336 336
    void nextOut(Arc& a) const { Parent::nextIn(a); }
337 337

	
338 338
    Node source(const Arc& a) const { return Parent::target(a); }
339 339
    Node target(const Arc& a) const { return Parent::source(a); }
340 340

	
341 341
    Arc addArc(const Node& u, const Node& v) { return Parent::addArc(v, u); }
342 342

	
343 343
    typedef FindArcTagIndicator<DGR> FindArcTag;
344 344
    Arc findArc(const Node& u, const Node& v,
345 345
                const Arc& prev = INVALID) const {
346 346
      return Parent::findArc(v, u, prev);
347 347
    }
348 348

	
349 349
  };
350 350

	
351 351
  /// \ingroup graph_adaptors
352 352
  ///
353 353
  /// \brief Adaptor class for reversing the orientation of the arcs in
354 354
  /// a digraph.
355 355
  ///
356 356
  /// ReverseDigraph can be used for reversing the arcs in a digraph.
357 357
  /// It conforms to the \ref concepts::Digraph "Digraph" concept.
358 358
  ///
359 359
  /// The adapted digraph can also be modified through this adaptor
360 360
  /// by adding or removing nodes or arcs, unless the \c GR template
361 361
  /// parameter is set to be \c const.
362 362
  ///
363
  /// This class provides item counting in the same time as the adapted
364
  /// digraph structure.
365
  ///
363 366
  /// \tparam DGR The type of the adapted digraph.
364 367
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
365 368
  /// It can also be specified to be \c const.
366 369
  ///
367 370
  /// \note The \c Node and \c Arc types of this adaptor and the adapted
368 371
  /// digraph are convertible to each other.
369 372
  template<typename DGR>
370 373
#ifdef DOXYGEN
371 374
  class ReverseDigraph {
372 375
#else
373 376
  class ReverseDigraph :
374 377
    public DigraphAdaptorExtender<ReverseDigraphBase<DGR> > {
375 378
#endif
376 379
    typedef DigraphAdaptorExtender<ReverseDigraphBase<DGR> > Parent;
377 380
  public:
378 381
    /// The type of the adapted digraph.
379 382
    typedef DGR Digraph;
380 383
  protected:
381 384
    ReverseDigraph() { }
382 385
  public:
383 386

	
384 387
    /// \brief Constructor
385 388
    ///
386 389
    /// Creates a reverse digraph adaptor for the given digraph.
387 390
    explicit ReverseDigraph(DGR& digraph) {
388 391
      Parent::initialize(digraph);
389 392
    }
390 393
  };
391 394

	
392 395
  /// \brief Returns a read-only ReverseDigraph adaptor
393 396
  ///
394 397
  /// This function just returns a read-only \ref ReverseDigraph adaptor.
395 398
  /// \ingroup graph_adaptors
396 399
  /// \relates ReverseDigraph
397 400
  template<typename DGR>
398 401
  ReverseDigraph<const DGR> reverseDigraph(const DGR& digraph) {
399 402
    return ReverseDigraph<const DGR>(digraph);
400 403
  }
401 404

	
402 405

	
403 406
  template <typename DGR, typename NF, typename AF, bool ch = true>
404 407
  class SubDigraphBase : public DigraphAdaptorBase<DGR> {
405 408
    typedef DigraphAdaptorBase<DGR> Parent;
406 409
  public:
407 410
    typedef DGR Digraph;
408 411
    typedef NF NodeFilterMap;
409 412
    typedef AF ArcFilterMap;
410 413

	
411 414
    typedef SubDigraphBase Adaptor;
412 415
  protected:
413 416
    NF* _node_filter;
414 417
    AF* _arc_filter;
415 418
    SubDigraphBase()
416 419
      : Parent(), _node_filter(0), _arc_filter(0) { }
417 420

	
418 421
    void initialize(DGR& digraph, NF& node_filter, AF& arc_filter) {
419 422
      Parent::initialize(digraph);
420 423
      _node_filter = &node_filter;
421 424
      _arc_filter = &arc_filter;      
422 425
    }
423 426

	
424 427
  public:
425 428

	
426 429
    typedef typename Parent::Node Node;
427 430
    typedef typename Parent::Arc Arc;
428 431

	
429 432
    void first(Node& i) const {
430 433
      Parent::first(i);
431 434
      while (i != INVALID && !(*_node_filter)[i]) Parent::next(i);
432 435
    }
433 436

	
434 437
    void first(Arc& i) const {
435 438
      Parent::first(i);
436 439
      while (i != INVALID && (!(*_arc_filter)[i]
437 440
                              || !(*_node_filter)[Parent::source(i)]
438 441
                              || !(*_node_filter)[Parent::target(i)]))
439 442
        Parent::next(i);
440 443
    }
441 444

	
442 445
    void firstIn(Arc& i, const Node& n) const {
443 446
      Parent::firstIn(i, n);
444 447
      while (i != INVALID && (!(*_arc_filter)[i]
445 448
                              || !(*_node_filter)[Parent::source(i)]))
446 449
        Parent::nextIn(i);
447 450
    }
448 451

	
449 452
    void firstOut(Arc& i, const Node& n) const {
450 453
      Parent::firstOut(i, n);
451 454
      while (i != INVALID && (!(*_arc_filter)[i]
452 455
                              || !(*_node_filter)[Parent::target(i)]))
453 456
        Parent::nextOut(i);
454 457
    }
455 458

	
456 459
    void next(Node& i) const {
457 460
      Parent::next(i);
458 461
      while (i != INVALID && !(*_node_filter)[i]) Parent::next(i);
459 462
    }
460 463

	
461 464
    void next(Arc& i) const {
462 465
      Parent::next(i);
463 466
      while (i != INVALID && (!(*_arc_filter)[i]
464 467
                              || !(*_node_filter)[Parent::source(i)]
465 468
                              || !(*_node_filter)[Parent::target(i)]))
466 469
        Parent::next(i);
467 470
    }
468 471

	
469 472
    void nextIn(Arc& i) const {
470 473
      Parent::nextIn(i);
471 474
      while (i != INVALID && (!(*_arc_filter)[i]
472 475
                              || !(*_node_filter)[Parent::source(i)]))
473 476
        Parent::nextIn(i);
474 477
    }
475 478

	
476 479
    void nextOut(Arc& i) const {
477 480
      Parent::nextOut(i);
478 481
      while (i != INVALID && (!(*_arc_filter)[i]
479 482
                              || !(*_node_filter)[Parent::target(i)]))
480 483
        Parent::nextOut(i);
481 484
    }
482 485

	
483 486
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
484 487
    void status(const Arc& a, bool v) const { _arc_filter->set(a, v); }
485 488

	
486 489
    bool status(const Node& n) const { return (*_node_filter)[n]; }
487 490
    bool status(const Arc& a) const { return (*_arc_filter)[a]; }
488 491

	
489 492
    typedef False NodeNumTag;
490 493
    typedef False ArcNumTag;
491 494

	
492 495
    typedef FindArcTagIndicator<DGR> FindArcTag;
493 496
    Arc findArc(const Node& source, const Node& target,
494 497
                const Arc& prev = INVALID) const {
495 498
      if (!(*_node_filter)[source] || !(*_node_filter)[target]) {
496 499
        return INVALID;
497 500
      }
498 501
      Arc arc = Parent::findArc(source, target, prev);
499 502
      while (arc != INVALID && !(*_arc_filter)[arc]) {
500 503
        arc = Parent::findArc(source, target, arc);
501 504
      }
502 505
      return arc;
503 506
    }
504 507

	
505 508
  public:
506 509

	
507 510
    template <typename V>
508 511
    class NodeMap 
509 512
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>, 
510 513
	      LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> {
511 514
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
512 515
	LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> Parent;
513 516

	
514 517
    public:
515 518
      typedef V Value;
516 519

	
517 520
      NodeMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor)
518 521
        : Parent(adaptor) {}
519 522
      NodeMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor, const V& value)
520 523
        : Parent(adaptor, value) {}
521 524

	
522 525
    private:
523 526
      NodeMap& operator=(const NodeMap& cmap) {
524 527
        return operator=<NodeMap>(cmap);
525 528
      }
526 529

	
527 530
      template <typename CMap>
528 531
      NodeMap& operator=(const CMap& cmap) {
529 532
        Parent::operator=(cmap);
530 533
        return *this;
531 534
      }
532 535
    };
533 536

	
534 537
    template <typename V>
535 538
    class ArcMap 
536 539
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
537 540
	      LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> {
538 541
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
539 542
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> Parent;
540 543

	
541 544
    public:
542 545
      typedef V Value;
543 546

	
544 547
      ArcMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor)
545 548
        : Parent(adaptor) {}
546 549
      ArcMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor, const V& value)
547 550
        : Parent(adaptor, value) {}
548 551

	
549 552
    private:
550 553
      ArcMap& operator=(const ArcMap& cmap) {
551 554
        return operator=<ArcMap>(cmap);
552 555
      }
553 556

	
554 557
      template <typename CMap>
555 558
      ArcMap& operator=(const CMap& cmap) {
556 559
        Parent::operator=(cmap);
557 560
        return *this;
558 561
      }
559 562
    };
560 563

	
561 564
  };
562 565

	
563 566
  template <typename DGR, typename NF, typename AF>
564 567
  class SubDigraphBase<DGR, NF, AF, false>
565 568
    : public DigraphAdaptorBase<DGR> {
566 569
    typedef DigraphAdaptorBase<DGR> Parent;
567 570
  public:
568 571
    typedef DGR Digraph;
569 572
    typedef NF NodeFilterMap;
570 573
    typedef AF ArcFilterMap;
571 574

	
572 575
    typedef SubDigraphBase Adaptor;
573 576
  protected:
574 577
    NF* _node_filter;
575 578
    AF* _arc_filter;
576 579
    SubDigraphBase()
577 580
      : Parent(), _node_filter(0), _arc_filter(0) { }
578 581

	
579 582
    void initialize(DGR& digraph, NF& node_filter, AF& arc_filter) {
580 583
      Parent::initialize(digraph);
581 584
      _node_filter = &node_filter;
582 585
      _arc_filter = &arc_filter;      
583 586
    }
584 587

	
585 588
  public:
586 589

	
587 590
    typedef typename Parent::Node Node;
588 591
    typedef typename Parent::Arc Arc;
589 592

	
590 593
    void first(Node& i) const {
591 594
      Parent::first(i);
592 595
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
593 596
    }
594 597

	
595 598
    void first(Arc& i) const {
596 599
      Parent::first(i);
597 600
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::next(i);
598 601
    }
599 602

	
600 603
    void firstIn(Arc& i, const Node& n) const {
601 604
      Parent::firstIn(i, n);
602 605
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextIn(i);
603 606
    }
604 607

	
605 608
    void firstOut(Arc& i, const Node& n) const {
606 609
      Parent::firstOut(i, n);
607 610
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextOut(i);
608 611
    }
609 612

	
610 613
    void next(Node& i) const {
611 614
      Parent::next(i);
612 615
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
613 616
    }
614 617
    void next(Arc& i) const {
615 618
      Parent::next(i);
616 619
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::next(i);
617 620
    }
618 621
    void nextIn(Arc& i) const {
619 622
      Parent::nextIn(i);
620 623
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextIn(i);
621 624
    }
622 625

	
623 626
    void nextOut(Arc& i) const {
624 627
      Parent::nextOut(i);
625 628
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextOut(i);
626 629
    }
627 630

	
628 631
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
629 632
    void status(const Arc& a, bool v) const { _arc_filter->set(a, v); }
630 633

	
631 634
    bool status(const Node& n) const { return (*_node_filter)[n]; }
632 635
    bool status(const Arc& a) const { return (*_arc_filter)[a]; }
633 636

	
634 637
    typedef False NodeNumTag;
635 638
    typedef False ArcNumTag;
636 639

	
637 640
    typedef FindArcTagIndicator<DGR> FindArcTag;
638 641
    Arc findArc(const Node& source, const Node& target,
639 642
                const Arc& prev = INVALID) const {
640 643
      if (!(*_node_filter)[source] || !(*_node_filter)[target]) {
641 644
        return INVALID;
642 645
      }
643 646
      Arc arc = Parent::findArc(source, target, prev);
644 647
      while (arc != INVALID && !(*_arc_filter)[arc]) {
645 648
        arc = Parent::findArc(source, target, arc);
646 649
      }
647 650
      return arc;
648 651
    }
649 652

	
650 653
    template <typename V>
651 654
    class NodeMap 
652 655
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
653 656
          LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> {
654 657
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, false>, 
655 658
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> Parent;
656 659

	
657 660
    public:
658 661
      typedef V Value;
659 662

	
660 663
      NodeMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor)
661 664
        : Parent(adaptor) {}
662 665
      NodeMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor, const V& value)
663 666
        : Parent(adaptor, value) {}
664 667

	
665 668
    private:
666 669
      NodeMap& operator=(const NodeMap& cmap) {
667 670
        return operator=<NodeMap>(cmap);
668 671
      }
669 672

	
670 673
      template <typename CMap>
671 674
      NodeMap& operator=(const CMap& cmap) {
672 675
        Parent::operator=(cmap);
673 676
        return *this;
674 677
      }
675 678
    };
676 679

	
677 680
    template <typename V>
678 681
    class ArcMap 
679 682
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
680 683
          LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> {
681 684
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
682 685
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> Parent;
683 686

	
684 687
    public:
685 688
      typedef V Value;
686 689

	
687 690
      ArcMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor)
688 691
        : Parent(adaptor) {}
689 692
      ArcMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor, const V& value)
690 693
        : Parent(adaptor, value) {}
691 694

	
692 695
    private:
693 696
      ArcMap& operator=(const ArcMap& cmap) {
694 697
        return operator=<ArcMap>(cmap);
695 698
      }
696 699

	
697 700
      template <typename CMap>
698 701
      ArcMap& operator=(const CMap& cmap) {
699 702
        Parent::operator=(cmap);
700 703
        return *this;
701 704
      }
702 705
    };
703 706

	
704 707
  };
705 708

	
706 709
  /// \ingroup graph_adaptors
707 710
  ///
708 711
  /// \brief Adaptor class for hiding nodes and arcs in a digraph
709 712
  ///
710 713
  /// SubDigraph can be used for hiding nodes and arcs in a digraph.
711 714
  /// A \c bool node map and a \c bool arc map must be specified, which
712 715
  /// define the filters for nodes and arcs.
713 716
  /// Only the nodes and arcs with \c true filter value are
714 717
  /// shown in the subdigraph. The arcs that are incident to hidden
715 718
  /// nodes are also filtered out.
716 719
  /// This adaptor conforms to the \ref concepts::Digraph "Digraph" concept.
717 720
  ///
718 721
  /// The adapted digraph can also be modified through this adaptor
719 722
  /// by adding or removing nodes or arcs, unless the \c GR template
720 723
  /// parameter is set to be \c const.
721 724
  ///
725
  /// This class provides only linear time counting for nodes and arcs.
726
  ///
722 727
  /// \tparam DGR The type of the adapted digraph.
723 728
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
724 729
  /// It can also be specified to be \c const.
725 730
  /// \tparam NF The type of the node filter map.
726 731
  /// It must be a \c bool (or convertible) node map of the
727 732
  /// adapted digraph. The default type is
728 733
  /// \ref concepts::Digraph::NodeMap "DGR::NodeMap<bool>".
729 734
  /// \tparam AF The type of the arc filter map.
730 735
  /// It must be \c bool (or convertible) arc map of the
731 736
  /// adapted digraph. The default type is
732 737
  /// \ref concepts::Digraph::ArcMap "DGR::ArcMap<bool>".
733 738
  ///
734 739
  /// \note The \c Node and \c Arc types of this adaptor and the adapted
735 740
  /// digraph are convertible to each other.
736 741
  ///
737 742
  /// \see FilterNodes
738 743
  /// \see FilterArcs
739 744
#ifdef DOXYGEN
740 745
  template<typename DGR, typename NF, typename AF>
741 746
  class SubDigraph {
742 747
#else
743 748
  template<typename DGR,
744 749
           typename NF = typename DGR::template NodeMap<bool>,
745 750
           typename AF = typename DGR::template ArcMap<bool> >
746 751
  class SubDigraph :
747 752
    public DigraphAdaptorExtender<SubDigraphBase<DGR, NF, AF, true> > {
748 753
#endif
749 754
  public:
750 755
    /// The type of the adapted digraph.
751 756
    typedef DGR Digraph;
752 757
    /// The type of the node filter map.
753 758
    typedef NF NodeFilterMap;
754 759
    /// The type of the arc filter map.
755 760
    typedef AF ArcFilterMap;
756 761

	
757 762
    typedef DigraphAdaptorExtender<SubDigraphBase<DGR, NF, AF, true> >
758 763
      Parent;
759 764

	
760 765
    typedef typename Parent::Node Node;
761 766
    typedef typename Parent::Arc Arc;
762 767

	
763 768
  protected:
764 769
    SubDigraph() { }
765 770
  public:
766 771

	
767 772
    /// \brief Constructor
768 773
    ///
769 774
    /// Creates a subdigraph for the given digraph with the
770 775
    /// given node and arc filter maps.
771 776
    SubDigraph(DGR& digraph, NF& node_filter, AF& arc_filter) {
772 777
      Parent::initialize(digraph, node_filter, arc_filter);
773 778
    }
774 779

	
775 780
    /// \brief Sets the status of the given node
776 781
    ///
777 782
    /// This function sets the status of the given node.
778 783
    /// It is done by simply setting the assigned value of \c n
779 784
    /// to \c v in the node filter map.
780 785
    void status(const Node& n, bool v) const { Parent::status(n, v); }
781 786

	
782 787
    /// \brief Sets the status of the given arc
783 788
    ///
784 789
    /// This function sets the status of the given arc.
785 790
    /// It is done by simply setting the assigned value of \c a
786 791
    /// to \c v in the arc filter map.
787 792
    void status(const Arc& a, bool v) const { Parent::status(a, v); }
788 793

	
789 794
    /// \brief Returns the status of the given node
790 795
    ///
791 796
    /// This function returns the status of the given node.
792 797
    /// It is \c true if the given node is enabled (i.e. not hidden).
793 798
    bool status(const Node& n) const { return Parent::status(n); }
794 799

	
795 800
    /// \brief Returns the status of the given arc
796 801
    ///
797 802
    /// This function returns the status of the given arc.
798 803
    /// It is \c true if the given arc is enabled (i.e. not hidden).
799 804
    bool status(const Arc& a) const { return Parent::status(a); }
800 805

	
801 806
    /// \brief Disables the given node
802 807
    ///
803 808
    /// This function disables the given node in the subdigraph,
804 809
    /// so the iteration jumps over it.
805 810
    /// It is the same as \ref status() "status(n, false)".
806 811
    void disable(const Node& n) const { Parent::status(n, false); }
807 812

	
808 813
    /// \brief Disables the given arc
809 814
    ///
810 815
    /// This function disables the given arc in the subdigraph,
811 816
    /// so the iteration jumps over it.
812 817
    /// It is the same as \ref status() "status(a, false)".
813 818
    void disable(const Arc& a) const { Parent::status(a, false); }
814 819

	
815 820
    /// \brief Enables the given node
816 821
    ///
817 822
    /// This function enables the given node in the subdigraph.
818 823
    /// It is the same as \ref status() "status(n, true)".
819 824
    void enable(const Node& n) const { Parent::status(n, true); }
820 825

	
821 826
    /// \brief Enables the given arc
822 827
    ///
823 828
    /// This function enables the given arc in the subdigraph.
824 829
    /// It is the same as \ref status() "status(a, true)".
825 830
    void enable(const Arc& a) const { Parent::status(a, true); }
826 831

	
827 832
  };
828 833

	
829 834
  /// \brief Returns a read-only SubDigraph adaptor
830 835
  ///
831 836
  /// This function just returns a read-only \ref SubDigraph adaptor.
832 837
  /// \ingroup graph_adaptors
833 838
  /// \relates SubDigraph
834 839
  template<typename DGR, typename NF, typename AF>
835 840
  SubDigraph<const DGR, NF, AF>
836 841
  subDigraph(const DGR& digraph,
837 842
             NF& node_filter, AF& arc_filter) {
838 843
    return SubDigraph<const DGR, NF, AF>
839 844
      (digraph, node_filter, arc_filter);
840 845
  }
841 846

	
842 847
  template<typename DGR, typename NF, typename AF>
843 848
  SubDigraph<const DGR, const NF, AF>
844 849
  subDigraph(const DGR& digraph,
845 850
             const NF& node_filter, AF& arc_filter) {
846 851
    return SubDigraph<const DGR, const NF, AF>
847 852
      (digraph, node_filter, arc_filter);
848 853
  }
849 854

	
850 855
  template<typename DGR, typename NF, typename AF>
851 856
  SubDigraph<const DGR, NF, const AF>
852 857
  subDigraph(const DGR& digraph,
853 858
             NF& node_filter, const AF& arc_filter) {
854 859
    return SubDigraph<const DGR, NF, const AF>
855 860
      (digraph, node_filter, arc_filter);
856 861
  }
857 862

	
858 863
  template<typename DGR, typename NF, typename AF>
859 864
  SubDigraph<const DGR, const NF, const AF>
860 865
  subDigraph(const DGR& digraph,
861 866
             const NF& node_filter, const AF& arc_filter) {
862 867
    return SubDigraph<const DGR, const NF, const AF>
863 868
      (digraph, node_filter, arc_filter);
864 869
  }
865 870

	
866 871

	
867 872
  template <typename GR, typename NF, typename EF, bool ch = true>
868 873
  class SubGraphBase : public GraphAdaptorBase<GR> {
869 874
    typedef GraphAdaptorBase<GR> Parent;
870 875
  public:
871 876
    typedef GR Graph;
872 877
    typedef NF NodeFilterMap;
873 878
    typedef EF EdgeFilterMap;
874 879

	
875 880
    typedef SubGraphBase Adaptor;
876 881
  protected:
877 882

	
878 883
    NF* _node_filter;
879 884
    EF* _edge_filter;
880 885

	
881 886
    SubGraphBase()
882 887
      : Parent(), _node_filter(0), _edge_filter(0) { }
883 888

	
884 889
    void initialize(GR& graph, NF& node_filter, EF& edge_filter) {
885 890
      Parent::initialize(graph);
886 891
      _node_filter = &node_filter;
887 892
      _edge_filter = &edge_filter;
888 893
    }
889 894

	
890 895
  public:
891 896

	
892 897
    typedef typename Parent::Node Node;
893 898
    typedef typename Parent::Arc Arc;
894 899
    typedef typename Parent::Edge Edge;
895 900

	
896 901
    void first(Node& i) const {
897 902
      Parent::first(i);
898 903
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
899 904
    }
900 905

	
901 906
    void first(Arc& i) const {
902 907
      Parent::first(i);
903 908
      while (i!=INVALID && (!(*_edge_filter)[i]
904 909
                            || !(*_node_filter)[Parent::source(i)]
905 910
                            || !(*_node_filter)[Parent::target(i)]))
906 911
        Parent::next(i);
907 912
    }
908 913

	
909 914
    void first(Edge& i) const {
910 915
      Parent::first(i);
911 916
      while (i!=INVALID && (!(*_edge_filter)[i]
912 917
                            || !(*_node_filter)[Parent::u(i)]
913 918
                            || !(*_node_filter)[Parent::v(i)]))
914 919
        Parent::next(i);
915 920
    }
916 921

	
917 922
    void firstIn(Arc& i, const Node& n) const {
918 923
      Parent::firstIn(i, n);
919 924
      while (i!=INVALID && (!(*_edge_filter)[i]
920 925
                            || !(*_node_filter)[Parent::source(i)]))
921 926
        Parent::nextIn(i);
922 927
    }
923 928

	
924 929
    void firstOut(Arc& i, const Node& n) const {
925 930
      Parent::firstOut(i, n);
926 931
      while (i!=INVALID && (!(*_edge_filter)[i]
927 932
                            || !(*_node_filter)[Parent::target(i)]))
928 933
        Parent::nextOut(i);
929 934
    }
930 935

	
931 936
    void firstInc(Edge& i, bool& d, const Node& n) const {
932 937
      Parent::firstInc(i, d, n);
933 938
      while (i!=INVALID && (!(*_edge_filter)[i]
934 939
                            || !(*_node_filter)[Parent::u(i)]
935 940
                            || !(*_node_filter)[Parent::v(i)]))
936 941
        Parent::nextInc(i, d);
937 942
    }
938 943

	
939 944
    void next(Node& i) const {
940 945
      Parent::next(i);
941 946
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
942 947
    }
943 948

	
944 949
    void next(Arc& i) const {
945 950
      Parent::next(i);
946 951
      while (i!=INVALID && (!(*_edge_filter)[i]
947 952
                            || !(*_node_filter)[Parent::source(i)]
948 953
                            || !(*_node_filter)[Parent::target(i)]))
949 954
        Parent::next(i);
950 955
    }
951 956

	
952 957
    void next(Edge& i) const {
953 958
      Parent::next(i);
954 959
      while (i!=INVALID && (!(*_edge_filter)[i]
955 960
                            || !(*_node_filter)[Parent::u(i)]
956 961
                            || !(*_node_filter)[Parent::v(i)]))
957 962
        Parent::next(i);
958 963
    }
959 964

	
960 965
    void nextIn(Arc& i) const {
961 966
      Parent::nextIn(i);
962 967
      while (i!=INVALID && (!(*_edge_filter)[i]
963 968
                            || !(*_node_filter)[Parent::source(i)]))
964 969
        Parent::nextIn(i);
965 970
    }
966 971

	
967 972
    void nextOut(Arc& i) const {
968 973
      Parent::nextOut(i);
969 974
      while (i!=INVALID && (!(*_edge_filter)[i]
970 975
                            || !(*_node_filter)[Parent::target(i)]))
971 976
        Parent::nextOut(i);
972 977
    }
973 978

	
974 979
    void nextInc(Edge& i, bool& d) const {
975 980
      Parent::nextInc(i, d);
976 981
      while (i!=INVALID && (!(*_edge_filter)[i]
977 982
                            || !(*_node_filter)[Parent::u(i)]
978 983
                            || !(*_node_filter)[Parent::v(i)]))
979 984
        Parent::nextInc(i, d);
980 985
    }
981 986

	
982 987
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
983 988
    void status(const Edge& e, bool v) const { _edge_filter->set(e, v); }
984 989

	
985 990
    bool status(const Node& n) const { return (*_node_filter)[n]; }
986 991
    bool status(const Edge& e) const { return (*_edge_filter)[e]; }
987 992

	
988 993
    typedef False NodeNumTag;
989 994
    typedef False ArcNumTag;
990 995
    typedef False EdgeNumTag;
991 996

	
992 997
    typedef FindArcTagIndicator<Graph> FindArcTag;
993 998
    Arc findArc(const Node& u, const Node& v,
994 999
                const Arc& prev = INVALID) const {
995 1000
      if (!(*_node_filter)[u] || !(*_node_filter)[v]) {
996 1001
        return INVALID;
997 1002
      }
998 1003
      Arc arc = Parent::findArc(u, v, prev);
999 1004
      while (arc != INVALID && !(*_edge_filter)[arc]) {
1000 1005
        arc = Parent::findArc(u, v, arc);
1001 1006
      }
1002 1007
      return arc;
1003 1008
    }
1004 1009

	
1005 1010
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
1006 1011
    Edge findEdge(const Node& u, const Node& v,
1007 1012
                  const Edge& prev = INVALID) const {
1008 1013
      if (!(*_node_filter)[u] || !(*_node_filter)[v]) {
1009 1014
        return INVALID;
1010 1015
      }
1011 1016
      Edge edge = Parent::findEdge(u, v, prev);
1012 1017
      while (edge != INVALID && !(*_edge_filter)[edge]) {
1013 1018
        edge = Parent::findEdge(u, v, edge);
1014 1019
      }
1015 1020
      return edge;
1016 1021
    }
1017 1022

	
1018 1023
    template <typename V>
1019 1024
    class NodeMap 
1020 1025
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1021 1026
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> {
1022 1027
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1023 1028
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> Parent;
1024 1029

	
1025 1030
    public:
1026 1031
      typedef V Value;
1027 1032

	
1028 1033
      NodeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1029 1034
        : Parent(adaptor) {}
1030 1035
      NodeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1031 1036
        : Parent(adaptor, value) {}
1032 1037

	
1033 1038
    private:
1034 1039
      NodeMap& operator=(const NodeMap& cmap) {
1035 1040
        return operator=<NodeMap>(cmap);
1036 1041
      }
1037 1042

	
1038 1043
      template <typename CMap>
1039 1044
      NodeMap& operator=(const CMap& cmap) {
1040 1045
        Parent::operator=(cmap);
1041 1046
        return *this;
1042 1047
      }
1043 1048
    };
1044 1049

	
1045 1050
    template <typename V>
1046 1051
    class ArcMap 
1047 1052
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1048 1053
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> {
1049 1054
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1050 1055
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> Parent;
1051 1056

	
1052 1057
    public:
1053 1058
      typedef V Value;
1054 1059

	
1055 1060
      ArcMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1056 1061
        : Parent(adaptor) {}
1057 1062
      ArcMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1058 1063
        : Parent(adaptor, value) {}
1059 1064

	
1060 1065
    private:
1061 1066
      ArcMap& operator=(const ArcMap& cmap) {
1062 1067
        return operator=<ArcMap>(cmap);
1063 1068
      }
1064 1069

	
1065 1070
      template <typename CMap>
1066 1071
      ArcMap& operator=(const CMap& cmap) {
1067 1072
        Parent::operator=(cmap);
1068 1073
        return *this;
1069 1074
      }
1070 1075
    };
1071 1076

	
1072 1077
    template <typename V>
1073 1078
    class EdgeMap 
1074 1079
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1075 1080
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> {
1076 1081
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1077 1082
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1078 1083

	
1079 1084
    public:
1080 1085
      typedef V Value;
1081 1086

	
1082 1087
      EdgeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1083 1088
        : Parent(adaptor) {}
1084 1089

	
1085 1090
      EdgeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1086 1091
        : Parent(adaptor, value) {}
1087 1092

	
1088 1093
    private:
1089 1094
      EdgeMap& operator=(const EdgeMap& cmap) {
1090 1095
        return operator=<EdgeMap>(cmap);
1091 1096
      }
1092 1097

	
1093 1098
      template <typename CMap>
1094 1099
      EdgeMap& operator=(const CMap& cmap) {
1095 1100
        Parent::operator=(cmap);
1096 1101
        return *this;
1097 1102
      }
1098 1103
    };
1099 1104

	
1100 1105
  };
1101 1106

	
1102 1107
  template <typename GR, typename NF, typename EF>
1103 1108
  class SubGraphBase<GR, NF, EF, false>
1104 1109
    : public GraphAdaptorBase<GR> {
1105 1110
    typedef GraphAdaptorBase<GR> Parent;
1106 1111
  public:
1107 1112
    typedef GR Graph;
1108 1113
    typedef NF NodeFilterMap;
1109 1114
    typedef EF EdgeFilterMap;
1110 1115

	
1111 1116
    typedef SubGraphBase Adaptor;
1112 1117
  protected:
1113 1118
    NF* _node_filter;
1114 1119
    EF* _edge_filter;
1115 1120
    SubGraphBase() 
1116 1121
	  : Parent(), _node_filter(0), _edge_filter(0) { }
1117 1122

	
1118 1123
    void initialize(GR& graph, NF& node_filter, EF& edge_filter) {
1119 1124
      Parent::initialize(graph);
1120 1125
      _node_filter = &node_filter;
1121 1126
      _edge_filter = &edge_filter;
1122 1127
    }
1123 1128

	
1124 1129
  public:
1125 1130

	
1126 1131
    typedef typename Parent::Node Node;
1127 1132
    typedef typename Parent::Arc Arc;
1128 1133
    typedef typename Parent::Edge Edge;
1129 1134

	
1130 1135
    void first(Node& i) const {
1131 1136
      Parent::first(i);
1132 1137
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
1133 1138
    }
1134 1139

	
1135 1140
    void first(Arc& i) const {
1136 1141
      Parent::first(i);
1137 1142
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1138 1143
    }
1139 1144

	
1140 1145
    void first(Edge& i) const {
1141 1146
      Parent::first(i);
1142 1147
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1143 1148
    }
1144 1149

	
1145 1150
    void firstIn(Arc& i, const Node& n) const {
1146 1151
      Parent::firstIn(i, n);
1147 1152
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextIn(i);
1148 1153
    }
1149 1154

	
1150 1155
    void firstOut(Arc& i, const Node& n) const {
1151 1156
      Parent::firstOut(i, n);
1152 1157
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextOut(i);
1153 1158
    }
1154 1159

	
1155 1160
    void firstInc(Edge& i, bool& d, const Node& n) const {
1156 1161
      Parent::firstInc(i, d, n);
1157 1162
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextInc(i, d);
1158 1163
    }
1159 1164

	
1160 1165
    void next(Node& i) const {
1161 1166
      Parent::next(i);
1162 1167
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
1163 1168
    }
1164 1169
    void next(Arc& i) const {
1165 1170
      Parent::next(i);
1166 1171
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1167 1172
    }
1168 1173
    void next(Edge& i) const {
1169 1174
      Parent::next(i);
1170 1175
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1171 1176
    }
1172 1177
    void nextIn(Arc& i) const {
1173 1178
      Parent::nextIn(i);
1174 1179
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextIn(i);
1175 1180
    }
1176 1181

	
1177 1182
    void nextOut(Arc& i) const {
1178 1183
      Parent::nextOut(i);
1179 1184
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextOut(i);
1180 1185
    }
1181 1186
    void nextInc(Edge& i, bool& d) const {
1182 1187
      Parent::nextInc(i, d);
1183 1188
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextInc(i, d);
1184 1189
    }
1185 1190

	
1186 1191
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
1187 1192
    void status(const Edge& e, bool v) const { _edge_filter->set(e, v); }
1188 1193

	
1189 1194
    bool status(const Node& n) const { return (*_node_filter)[n]; }
1190 1195
    bool status(const Edge& e) const { return (*_edge_filter)[e]; }
1191 1196

	
1192 1197
    typedef False NodeNumTag;
1193 1198
    typedef False ArcNumTag;
1194 1199
    typedef False EdgeNumTag;
1195 1200

	
1196 1201
    typedef FindArcTagIndicator<Graph> FindArcTag;
1197 1202
    Arc findArc(const Node& u, const Node& v,
1198 1203
                const Arc& prev = INVALID) const {
1199 1204
      Arc arc = Parent::findArc(u, v, prev);
1200 1205
      while (arc != INVALID && !(*_edge_filter)[arc]) {
1201 1206
        arc = Parent::findArc(u, v, arc);
1202 1207
      }
1203 1208
      return arc;
1204 1209
    }
1205 1210

	
1206 1211
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
1207 1212
    Edge findEdge(const Node& u, const Node& v,
1208 1213
                  const Edge& prev = INVALID) const {
1209 1214
      Edge edge = Parent::findEdge(u, v, prev);
1210 1215
      while (edge != INVALID && !(*_edge_filter)[edge]) {
1211 1216
        edge = Parent::findEdge(u, v, edge);
1212 1217
      }
1213 1218
      return edge;
1214 1219
    }
1215 1220

	
1216 1221
    template <typename V>
1217 1222
    class NodeMap 
1218 1223
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1219 1224
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> {
1220 1225
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1221 1226
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> Parent;
1222 1227

	
1223 1228
    public:
1224 1229
      typedef V Value;
1225 1230

	
1226 1231
      NodeMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1227 1232
        : Parent(adaptor) {}
1228 1233
      NodeMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1229 1234
        : Parent(adaptor, value) {}
1230 1235

	
1231 1236
    private:
1232 1237
      NodeMap& operator=(const NodeMap& cmap) {
1233 1238
        return operator=<NodeMap>(cmap);
1234 1239
      }
1235 1240

	
1236 1241
      template <typename CMap>
1237 1242
      NodeMap& operator=(const CMap& cmap) {
1238 1243
        Parent::operator=(cmap);
1239 1244
        return *this;
1240 1245
      }
1241 1246
    };
1242 1247

	
1243 1248
    template <typename V>
1244 1249
    class ArcMap 
1245 1250
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1246 1251
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> {
1247 1252
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1248 1253
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> Parent;
1249 1254

	
1250 1255
    public:
1251 1256
      typedef V Value;
1252 1257

	
1253 1258
      ArcMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1254 1259
        : Parent(adaptor) {}
1255 1260
      ArcMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1256 1261
        : Parent(adaptor, value) {}
1257 1262

	
1258 1263
    private:
1259 1264
      ArcMap& operator=(const ArcMap& cmap) {
1260 1265
        return operator=<ArcMap>(cmap);
1261 1266
      }
1262 1267

	
1263 1268
      template <typename CMap>
1264 1269
      ArcMap& operator=(const CMap& cmap) {
1265 1270
        Parent::operator=(cmap);
1266 1271
        return *this;
1267 1272
      }
1268 1273
    };
1269 1274

	
1270 1275
    template <typename V>
1271 1276
    class EdgeMap 
1272 1277
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1273 1278
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> {
1274 1279
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1275 1280
	LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1276 1281

	
1277 1282
    public:
1278 1283
      typedef V Value;
1279 1284

	
1280 1285
      EdgeMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1281 1286
        : Parent(adaptor) {}
1282 1287

	
1283 1288
      EdgeMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1284 1289
        : Parent(adaptor, value) {}
1285 1290

	
1286 1291
    private:
1287 1292
      EdgeMap& operator=(const EdgeMap& cmap) {
1288 1293
        return operator=<EdgeMap>(cmap);
1289 1294
      }
1290 1295

	
1291 1296
      template <typename CMap>
1292 1297
      EdgeMap& operator=(const CMap& cmap) {
1293 1298
        Parent::operator=(cmap);
1294 1299
        return *this;
1295 1300
      }
1296 1301
    };
1297 1302

	
1298 1303
  };
1299 1304

	
1300 1305
  /// \ingroup graph_adaptors
1301 1306
  ///
1302 1307
  /// \brief Adaptor class for hiding nodes and edges in an undirected
1303 1308
  /// graph.
1304 1309
  ///
1305 1310
  /// SubGraph can be used for hiding nodes and edges in a graph.
1306 1311
  /// A \c bool node map and a \c bool edge map must be specified, which
1307 1312
  /// define the filters for nodes and edges.
1308 1313
  /// Only the nodes and edges with \c true filter value are
1309 1314
  /// shown in the subgraph. The edges that are incident to hidden
1310 1315
  /// nodes are also filtered out.
1311 1316
  /// This adaptor conforms to the \ref concepts::Graph "Graph" concept.
1312 1317
  ///
1313 1318
  /// The adapted graph can also be modified through this adaptor
1314 1319
  /// by adding or removing nodes or edges, unless the \c GR template
1315 1320
  /// parameter is set to be \c const.
1316 1321
  ///
1322
  /// This class provides only linear time counting for nodes, edges and arcs.
1323
  ///
1317 1324
  /// \tparam GR The type of the adapted graph.
1318 1325
  /// It must conform to the \ref concepts::Graph "Graph" concept.
1319 1326
  /// It can also be specified to be \c const.
1320 1327
  /// \tparam NF The type of the node filter map.
1321 1328
  /// It must be a \c bool (or convertible) node map of the
1322 1329
  /// adapted graph. The default type is
1323 1330
  /// \ref concepts::Graph::NodeMap "GR::NodeMap<bool>".
1324 1331
  /// \tparam EF The type of the edge filter map.
1325 1332
  /// It must be a \c bool (or convertible) edge map of the
1326 1333
  /// adapted graph. The default type is
1327 1334
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<bool>".
1328 1335
  ///
1329 1336
  /// \note The \c Node, \c Edge and \c Arc types of this adaptor and the
1330 1337
  /// adapted graph are convertible to each other.
1331 1338
  ///
1332 1339
  /// \see FilterNodes
1333 1340
  /// \see FilterEdges
1334 1341
#ifdef DOXYGEN
1335 1342
  template<typename GR, typename NF, typename EF>
1336 1343
  class SubGraph {
1337 1344
#else
1338 1345
  template<typename GR,
1339 1346
           typename NF = typename GR::template NodeMap<bool>,
1340 1347
           typename EF = typename GR::template EdgeMap<bool> >
1341 1348
  class SubGraph :
1342 1349
    public GraphAdaptorExtender<SubGraphBase<GR, NF, EF, true> > {
1343 1350
#endif
1344 1351
  public:
1345 1352
    /// The type of the adapted graph.
1346 1353
    typedef GR Graph;
1347 1354
    /// The type of the node filter map.
1348 1355
    typedef NF NodeFilterMap;
1349 1356
    /// The type of the edge filter map.
1350 1357
    typedef EF EdgeFilterMap;
1351 1358

	
1352 1359
    typedef GraphAdaptorExtender<SubGraphBase<GR, NF, EF, true> >
1353 1360
      Parent;
1354 1361

	
1355 1362
    typedef typename Parent::Node Node;
1356 1363
    typedef typename Parent::Edge Edge;
1357 1364

	
1358 1365
  protected:
1359 1366
    SubGraph() { }
1360 1367
  public:
1361 1368

	
1362 1369
    /// \brief Constructor
1363 1370
    ///
1364 1371
    /// Creates a subgraph for the given graph with the given node
1365 1372
    /// and edge filter maps.
1366 1373
    SubGraph(GR& graph, NF& node_filter, EF& edge_filter) {
1367 1374
      initialize(graph, node_filter, edge_filter);
1368 1375
    }
1369 1376

	
1370 1377
    /// \brief Sets the status of the given node
1371 1378
    ///
1372 1379
    /// This function sets the status of the given node.
1373 1380
    /// It is done by simply setting the assigned value of \c n
1374 1381
    /// to \c v in the node filter map.
1375 1382
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1376 1383

	
1377 1384
    /// \brief Sets the status of the given edge
1378 1385
    ///
1379 1386
    /// This function sets the status of the given edge.
1380 1387
    /// It is done by simply setting the assigned value of \c e
1381 1388
    /// to \c v in the edge filter map.
1382 1389
    void status(const Edge& e, bool v) const { Parent::status(e, v); }
1383 1390

	
1384 1391
    /// \brief Returns the status of the given node
1385 1392
    ///
1386 1393
    /// This function returns the status of the given node.
1387 1394
    /// It is \c true if the given node is enabled (i.e. not hidden).
1388 1395
    bool status(const Node& n) const { return Parent::status(n); }
1389 1396

	
1390 1397
    /// \brief Returns the status of the given edge
1391 1398
    ///
1392 1399
    /// This function returns the status of the given edge.
1393 1400
    /// It is \c true if the given edge is enabled (i.e. not hidden).
1394 1401
    bool status(const Edge& e) const { return Parent::status(e); }
1395 1402

	
1396 1403
    /// \brief Disables the given node
1397 1404
    ///
1398 1405
    /// This function disables the given node in the subdigraph,
1399 1406
    /// so the iteration jumps over it.
1400 1407
    /// It is the same as \ref status() "status(n, false)".
1401 1408
    void disable(const Node& n) const { Parent::status(n, false); }
1402 1409

	
1403 1410
    /// \brief Disables the given edge
1404 1411
    ///
1405 1412
    /// This function disables the given edge in the subgraph,
1406 1413
    /// so the iteration jumps over it.
1407 1414
    /// It is the same as \ref status() "status(e, false)".
1408 1415
    void disable(const Edge& e) const { Parent::status(e, false); }
1409 1416

	
1410 1417
    /// \brief Enables the given node
1411 1418
    ///
1412 1419
    /// This function enables the given node in the subdigraph.
1413 1420
    /// It is the same as \ref status() "status(n, true)".
1414 1421
    void enable(const Node& n) const { Parent::status(n, true); }
1415 1422

	
1416 1423
    /// \brief Enables the given edge
1417 1424
    ///
1418 1425
    /// This function enables the given edge in the subgraph.
1419 1426
    /// It is the same as \ref status() "status(e, true)".
1420 1427
    void enable(const Edge& e) const { Parent::status(e, true); }
1421 1428

	
1422 1429
  };
1423 1430

	
1424 1431
  /// \brief Returns a read-only SubGraph adaptor
1425 1432
  ///
1426 1433
  /// This function just returns a read-only \ref SubGraph adaptor.
1427 1434
  /// \ingroup graph_adaptors
1428 1435
  /// \relates SubGraph
1429 1436
  template<typename GR, typename NF, typename EF>
1430 1437
  SubGraph<const GR, NF, EF>
1431 1438
  subGraph(const GR& graph, NF& node_filter, EF& edge_filter) {
1432 1439
    return SubGraph<const GR, NF, EF>
1433 1440
      (graph, node_filter, edge_filter);
1434 1441
  }
1435 1442

	
1436 1443
  template<typename GR, typename NF, typename EF>
1437 1444
  SubGraph<const GR, const NF, EF>
1438 1445
  subGraph(const GR& graph, const NF& node_filter, EF& edge_filter) {
1439 1446
    return SubGraph<const GR, const NF, EF>
1440 1447
      (graph, node_filter, edge_filter);
1441 1448
  }
1442 1449

	
1443 1450
  template<typename GR, typename NF, typename EF>
1444 1451
  SubGraph<const GR, NF, const EF>
1445 1452
  subGraph(const GR& graph, NF& node_filter, const EF& edge_filter) {
1446 1453
    return SubGraph<const GR, NF, const EF>
1447 1454
      (graph, node_filter, edge_filter);
1448 1455
  }
1449 1456

	
1450 1457
  template<typename GR, typename NF, typename EF>
1451 1458
  SubGraph<const GR, const NF, const EF>
1452 1459
  subGraph(const GR& graph, const NF& node_filter, const EF& edge_filter) {
1453 1460
    return SubGraph<const GR, const NF, const EF>
1454 1461
      (graph, node_filter, edge_filter);
1455 1462
  }
1456 1463

	
1457 1464

	
1458 1465
  /// \ingroup graph_adaptors
1459 1466
  ///
1460 1467
  /// \brief Adaptor class for hiding nodes in a digraph or a graph.
1461 1468
  ///
1462 1469
  /// FilterNodes adaptor can be used for hiding nodes in a digraph or a
1463 1470
  /// graph. A \c bool node map must be specified, which defines the filter
1464 1471
  /// for the nodes. Only the nodes with \c true filter value and the
1465 1472
  /// arcs/edges incident to nodes both with \c true filter value are shown
1466 1473
  /// in the subgraph. This adaptor conforms to the \ref concepts::Digraph
1467 1474
  /// "Digraph" concept or the \ref concepts::Graph "Graph" concept
1468 1475
  /// depending on the \c GR template parameter.
1469 1476
  ///
1470 1477
  /// The adapted (di)graph can also be modified through this adaptor
1471 1478
  /// by adding or removing nodes or arcs/edges, unless the \c GR template
1472 1479
  /// parameter is set to be \c const.
1473 1480
  ///
1481
  /// This class provides only linear time item counting.
1482
  ///
1474 1483
  /// \tparam GR The type of the adapted digraph or graph.
1475 1484
  /// It must conform to the \ref concepts::Digraph "Digraph" concept
1476 1485
  /// or the \ref concepts::Graph "Graph" concept.
1477 1486
  /// It can also be specified to be \c const.
1478 1487
  /// \tparam NF The type of the node filter map.
1479 1488
  /// It must be a \c bool (or convertible) node map of the
1480 1489
  /// adapted (di)graph. The default type is
1481 1490
  /// \ref concepts::Graph::NodeMap "GR::NodeMap<bool>".
1482 1491
  ///
1483 1492
  /// \note The \c Node and <tt>Arc/Edge</tt> types of this adaptor and the
1484 1493
  /// adapted (di)graph are convertible to each other.
1485 1494
#ifdef DOXYGEN
1486 1495
  template<typename GR, typename NF>
1487 1496
  class FilterNodes {
1488 1497
#else
1489 1498
  template<typename GR,
1490 1499
           typename NF = typename GR::template NodeMap<bool>,
1491 1500
           typename Enable = void>
1492 1501
  class FilterNodes :
1493 1502
    public DigraphAdaptorExtender<
1494 1503
      SubDigraphBase<GR, NF, ConstMap<typename GR::Arc, Const<bool, true> >,
1495 1504
                     true> > {
1496 1505
#endif
1497 1506
    typedef DigraphAdaptorExtender<
1498 1507
      SubDigraphBase<GR, NF, ConstMap<typename GR::Arc, Const<bool, true> >, 
1499 1508
                     true> > Parent;
1500 1509

	
1501 1510
  public:
1502 1511

	
1503 1512
    typedef GR Digraph;
1504 1513
    typedef NF NodeFilterMap;
1505 1514

	
1506 1515
    typedef typename Parent::Node Node;
1507 1516

	
1508 1517
  protected:
1509 1518
    ConstMap<typename Digraph::Arc, Const<bool, true> > const_true_map;
1510 1519

	
1511 1520
    FilterNodes() : const_true_map() {}
1512 1521

	
1513 1522
  public:
1514 1523

	
1515 1524
    /// \brief Constructor
1516 1525
    ///
1517 1526
    /// Creates a subgraph for the given digraph or graph with the
1518 1527
    /// given node filter map.
1519 1528
    FilterNodes(GR& graph, NF& node_filter) 
1520 1529
      : Parent(), const_true_map()
1521 1530
    {
1522 1531
      Parent::initialize(graph, node_filter, const_true_map);
1523 1532
    }
1524 1533

	
1525 1534
    /// \brief Sets the status of the given node
1526 1535
    ///
1527 1536
    /// This function sets the status of the given node.
1528 1537
    /// It is done by simply setting the assigned value of \c n
1529 1538
    /// to \c v in the node filter map.
1530 1539
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1531 1540

	
1532 1541
    /// \brief Returns the status of the given node
1533 1542
    ///
1534 1543
    /// This function returns the status of the given node.
1535 1544
    /// It is \c true if the given node is enabled (i.e. not hidden).
1536 1545
    bool status(const Node& n) const { return Parent::status(n); }
1537 1546

	
1538 1547
    /// \brief Disables the given node
1539 1548
    ///
1540 1549
    /// This function disables the given node, so the iteration
1541 1550
    /// jumps over it.
1542 1551
    /// It is the same as \ref status() "status(n, false)".
1543 1552
    void disable(const Node& n) const { Parent::status(n, false); }
1544 1553

	
1545 1554
    /// \brief Enables the given node
1546 1555
    ///
1547 1556
    /// This function enables the given node.
1548 1557
    /// It is the same as \ref status() "status(n, true)".
1549 1558
    void enable(const Node& n) const { Parent::status(n, true); }
1550 1559

	
1551 1560
  };
1552 1561

	
1553 1562
  template<typename GR, typename NF>
1554 1563
  class FilterNodes<GR, NF,
1555 1564
                    typename enable_if<UndirectedTagIndicator<GR> >::type> :
1556 1565
    public GraphAdaptorExtender<
1557 1566
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >, 
1558 1567
                   true> > {
1559 1568

	
1560 1569
    typedef GraphAdaptorExtender<
1561 1570
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >, 
1562 1571
                   true> > Parent;
1563 1572

	
1564 1573
  public:
1565 1574

	
1566 1575
    typedef GR Graph;
1567 1576
    typedef NF NodeFilterMap;
1568 1577

	
1569 1578
    typedef typename Parent::Node Node;
1570 1579

	
1571 1580
  protected:
1572 1581
    ConstMap<typename GR::Edge, Const<bool, true> > const_true_map;
1573 1582

	
1574 1583
    FilterNodes() : const_true_map() {}
1575 1584

	
1576 1585
  public:
1577 1586

	
1578 1587
    FilterNodes(GR& graph, NodeFilterMap& node_filter) :
1579 1588
      Parent(), const_true_map() {
1580 1589
      Parent::initialize(graph, node_filter, const_true_map);
1581 1590
    }
1582 1591

	
1583 1592
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1584 1593
    bool status(const Node& n) const { return Parent::status(n); }
1585 1594
    void disable(const Node& n) const { Parent::status(n, false); }
1586 1595
    void enable(const Node& n) const { Parent::status(n, true); }
1587 1596

	
1588 1597
  };
1589 1598

	
1590 1599

	
1591 1600
  /// \brief Returns a read-only FilterNodes adaptor
1592 1601
  ///
1593 1602
  /// This function just returns a read-only \ref FilterNodes adaptor.
1594 1603
  /// \ingroup graph_adaptors
1595 1604
  /// \relates FilterNodes
1596 1605
  template<typename GR, typename NF>
1597 1606
  FilterNodes<const GR, NF>
1598 1607
  filterNodes(const GR& graph, NF& node_filter) {
1599 1608
    return FilterNodes<const GR, NF>(graph, node_filter);
1600 1609
  }
1601 1610

	
1602 1611
  template<typename GR, typename NF>
1603 1612
  FilterNodes<const GR, const NF>
1604 1613
  filterNodes(const GR& graph, const NF& node_filter) {
1605 1614
    return FilterNodes<const GR, const NF>(graph, node_filter);
1606 1615
  }
1607 1616

	
1608 1617
  /// \ingroup graph_adaptors
1609 1618
  ///
1610 1619
  /// \brief Adaptor class for hiding arcs in a digraph.
1611 1620
  ///
1612 1621
  /// FilterArcs adaptor can be used for hiding arcs in a digraph.
1613 1622
  /// A \c bool arc map must be specified, which defines the filter for
1614 1623
  /// the arcs. Only the arcs with \c true filter value are shown in the
1615 1624
  /// subdigraph. This adaptor conforms to the \ref concepts::Digraph
1616 1625
  /// "Digraph" concept.
1617 1626
  ///
1618 1627
  /// The adapted digraph can also be modified through this adaptor
1619 1628
  /// by adding or removing nodes or arcs, unless the \c GR template
1620 1629
  /// parameter is set to be \c const.
1621 1630
  ///
1631
  /// This class provides only linear time counting for nodes and arcs.
1632
  ///
1622 1633
  /// \tparam DGR The type of the adapted digraph.
1623 1634
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
1624 1635
  /// It can also be specified to be \c const.
1625 1636
  /// \tparam AF The type of the arc filter map.
1626 1637
  /// It must be a \c bool (or convertible) arc map of the
1627 1638
  /// adapted digraph. The default type is
1628 1639
  /// \ref concepts::Digraph::ArcMap "DGR::ArcMap<bool>".
1629 1640
  ///
1630 1641
  /// \note The \c Node and \c Arc types of this adaptor and the adapted
1631 1642
  /// digraph are convertible to each other.
1632 1643
#ifdef DOXYGEN
1633 1644
  template<typename DGR,
1634 1645
           typename AF>
1635 1646
  class FilterArcs {
1636 1647
#else
1637 1648
  template<typename DGR,
1638 1649
           typename AF = typename DGR::template ArcMap<bool> >
1639 1650
  class FilterArcs :
1640 1651
    public DigraphAdaptorExtender<
1641 1652
      SubDigraphBase<DGR, ConstMap<typename DGR::Node, Const<bool, true> >,
1642 1653
                     AF, false> > {
1643 1654
#endif
1644 1655
    typedef DigraphAdaptorExtender<
1645 1656
      SubDigraphBase<DGR, ConstMap<typename DGR::Node, Const<bool, true> >, 
1646 1657
                     AF, false> > Parent;
1647 1658

	
1648 1659
  public:
1649 1660

	
1650 1661
    /// The type of the adapted digraph.
1651 1662
    typedef DGR Digraph;
1652 1663
    /// The type of the arc filter map.
1653 1664
    typedef AF ArcFilterMap;
1654 1665

	
1655 1666
    typedef typename Parent::Arc Arc;
1656 1667

	
1657 1668
  protected:
1658 1669
    ConstMap<typename DGR::Node, Const<bool, true> > const_true_map;
1659 1670

	
1660 1671
    FilterArcs() : const_true_map() {}
1661 1672

	
1662 1673
  public:
1663 1674

	
1664 1675
    /// \brief Constructor
1665 1676
    ///
1666 1677
    /// Creates a subdigraph for the given digraph with the given arc
1667 1678
    /// filter map.
1668 1679
    FilterArcs(DGR& digraph, ArcFilterMap& arc_filter)
1669 1680
      : Parent(), const_true_map() {
1670 1681
      Parent::initialize(digraph, const_true_map, arc_filter);
1671 1682
    }
1672 1683

	
1673 1684
    /// \brief Sets the status of the given arc
1674 1685
    ///
1675 1686
    /// This function sets the status of the given arc.
1676 1687
    /// It is done by simply setting the assigned value of \c a
1677 1688
    /// to \c v in the arc filter map.
1678 1689
    void status(const Arc& a, bool v) const { Parent::status(a, v); }
1679 1690

	
1680 1691
    /// \brief Returns the status of the given arc
1681 1692
    ///
1682 1693
    /// This function returns the status of the given arc.
1683 1694
    /// It is \c true if the given arc is enabled (i.e. not hidden).
1684 1695
    bool status(const Arc& a) const { return Parent::status(a); }
1685 1696

	
1686 1697
    /// \brief Disables the given arc
1687 1698
    ///
1688 1699
    /// This function disables the given arc in the subdigraph,
1689 1700
    /// so the iteration jumps over it.
1690 1701
    /// It is the same as \ref status() "status(a, false)".
1691 1702
    void disable(const Arc& a) const { Parent::status(a, false); }
1692 1703

	
1693 1704
    /// \brief Enables the given arc
1694 1705
    ///
1695 1706
    /// This function enables the given arc in the subdigraph.
1696 1707
    /// It is the same as \ref status() "status(a, true)".
1697 1708
    void enable(const Arc& a) const { Parent::status(a, true); }
1698 1709

	
1699 1710
  };
1700 1711

	
1701 1712
  /// \brief Returns a read-only FilterArcs adaptor
1702 1713
  ///
1703 1714
  /// This function just returns a read-only \ref FilterArcs adaptor.
1704 1715
  /// \ingroup graph_adaptors
1705 1716
  /// \relates FilterArcs
1706 1717
  template<typename DGR, typename AF>
1707 1718
  FilterArcs<const DGR, AF>
1708 1719
  filterArcs(const DGR& digraph, AF& arc_filter) {
1709 1720
    return FilterArcs<const DGR, AF>(digraph, arc_filter);
1710 1721
  }
1711 1722

	
1712 1723
  template<typename DGR, typename AF>
1713 1724
  FilterArcs<const DGR, const AF>
1714 1725
  filterArcs(const DGR& digraph, const AF& arc_filter) {
1715 1726
    return FilterArcs<const DGR, const AF>(digraph, arc_filter);
1716 1727
  }
1717 1728

	
1718 1729
  /// \ingroup graph_adaptors
1719 1730
  ///
1720 1731
  /// \brief Adaptor class for hiding edges in a graph.
1721 1732
  ///
1722 1733
  /// FilterEdges adaptor can be used for hiding edges in a graph.
1723 1734
  /// A \c bool edge map must be specified, which defines the filter for
1724 1735
  /// the edges. Only the edges with \c true filter value are shown in the
1725 1736
  /// subgraph. This adaptor conforms to the \ref concepts::Graph
1726 1737
  /// "Graph" concept.
1727 1738
  ///
1728 1739
  /// The adapted graph can also be modified through this adaptor
1729 1740
  /// by adding or removing nodes or edges, unless the \c GR template
1730 1741
  /// parameter is set to be \c const.
1731 1742
  ///
1743
  /// This class provides only linear time counting for nodes, edges and arcs.
1744
  ///
1732 1745
  /// \tparam GR The type of the adapted graph.
1733 1746
  /// It must conform to the \ref concepts::Graph "Graph" concept.
1734 1747
  /// It can also be specified to be \c const.
1735 1748
  /// \tparam EF The type of the edge filter map.
1736 1749
  /// It must be a \c bool (or convertible) edge map of the
1737 1750
  /// adapted graph. The default type is
1738 1751
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<bool>".
1739 1752
  ///
1740 1753
  /// \note The \c Node, \c Edge and \c Arc types of this adaptor and the
1741 1754
  /// adapted graph are convertible to each other.
1742 1755
#ifdef DOXYGEN
1743 1756
  template<typename GR,
1744 1757
           typename EF>
1745 1758
  class FilterEdges {
1746 1759
#else
1747 1760
  template<typename GR,
1748 1761
           typename EF = typename GR::template EdgeMap<bool> >
1749 1762
  class FilterEdges :
1750 1763
    public GraphAdaptorExtender<
1751 1764
      SubGraphBase<GR, ConstMap<typename GR::Node, Const<bool, true> >, 
1752 1765
                   EF, false> > {
1753 1766
#endif
1754 1767
    typedef GraphAdaptorExtender<
1755 1768
      SubGraphBase<GR, ConstMap<typename GR::Node, Const<bool, true > >, 
1756 1769
                   EF, false> > Parent;
1757 1770

	
1758 1771
  public:
1759 1772

	
1760 1773
    /// The type of the adapted graph.
1761 1774
    typedef GR Graph;
1762 1775
    /// The type of the edge filter map.
1763 1776
    typedef EF EdgeFilterMap;
1764 1777

	
1765 1778
    typedef typename Parent::Edge Edge;
1766 1779

	
1767 1780
  protected:
1768 1781
    ConstMap<typename GR::Node, Const<bool, true> > const_true_map;
1769 1782

	
1770 1783
    FilterEdges() : const_true_map(true) {
1771 1784
      Parent::setNodeFilterMap(const_true_map);
1772 1785
    }
1773 1786

	
1774 1787
  public:
1775 1788

	
1776 1789
    /// \brief Constructor
1777 1790
    ///
1778 1791
    /// Creates a subgraph for the given graph with the given edge
1779 1792
    /// filter map.
1780 1793
    FilterEdges(GR& graph, EF& edge_filter) 
1781 1794
      : Parent(), const_true_map() {
1782 1795
      Parent::initialize(graph, const_true_map, edge_filter);
1783 1796
    }
1784 1797

	
1785 1798
    /// \brief Sets the status of the given edge
1786 1799
    ///
1787 1800
    /// This function sets the status of the given edge.
1788 1801
    /// It is done by simply setting the assigned value of \c e
1789 1802
    /// to \c v in the edge filter map.
1790 1803
    void status(const Edge& e, bool v) const { Parent::status(e, v); }
1791 1804

	
1792 1805
    /// \brief Returns the status of the given edge
1793 1806
    ///
1794 1807
    /// This function returns the status of the given edge.
1795 1808
    /// It is \c true if the given edge is enabled (i.e. not hidden).
1796 1809
    bool status(const Edge& e) const { return Parent::status(e); }
1797 1810

	
1798 1811
    /// \brief Disables the given edge
1799 1812
    ///
1800 1813
    /// This function disables the given edge in the subgraph,
1801 1814
    /// so the iteration jumps over it.
1802 1815
    /// It is the same as \ref status() "status(e, false)".
1803 1816
    void disable(const Edge& e) const { Parent::status(e, false); }
1804 1817

	
1805 1818
    /// \brief Enables the given edge
1806 1819
    ///
1807 1820
    /// This function enables the given edge in the subgraph.
1808 1821
    /// It is the same as \ref status() "status(e, true)".
1809 1822
    void enable(const Edge& e) const { Parent::status(e, true); }
1810 1823

	
1811 1824
  };
1812 1825

	
1813 1826
  /// \brief Returns a read-only FilterEdges adaptor
1814 1827
  ///
1815 1828
  /// This function just returns a read-only \ref FilterEdges adaptor.
1816 1829
  /// \ingroup graph_adaptors
1817 1830
  /// \relates FilterEdges
1818 1831
  template<typename GR, typename EF>
1819 1832
  FilterEdges<const GR, EF>
1820 1833
  filterEdges(const GR& graph, EF& edge_filter) {
1821 1834
    return FilterEdges<const GR, EF>(graph, edge_filter);
1822 1835
  }
1823 1836

	
1824 1837
  template<typename GR, typename EF>
1825 1838
  FilterEdges<const GR, const EF>
1826 1839
  filterEdges(const GR& graph, const EF& edge_filter) {
1827 1840
    return FilterEdges<const GR, const EF>(graph, edge_filter);
1828 1841
  }
1829 1842

	
1830 1843

	
1831 1844
  template <typename DGR>
1832 1845
  class UndirectorBase {
1833 1846
  public:
1834 1847
    typedef DGR Digraph;
1835 1848
    typedef UndirectorBase Adaptor;
1836 1849

	
1837 1850
    typedef True UndirectedTag;
1838 1851

	
1839 1852
    typedef typename Digraph::Arc Edge;
1840 1853
    typedef typename Digraph::Node Node;
1841 1854

	
1842 1855
    class Arc {
1843 1856
      friend class UndirectorBase;
1844 1857
    protected:
1845 1858
      Edge _edge;
1846 1859
      bool _forward;
1847 1860

	
1848 1861
      Arc(const Edge& edge, bool forward) 
1849 1862
        : _edge(edge), _forward(forward) {}
1850 1863

	
1851 1864
    public:
1852 1865
      Arc() {}
1853 1866

	
1854 1867
      Arc(Invalid) : _edge(INVALID), _forward(true) {}
1855 1868

	
1856 1869
      operator const Edge&() const { return _edge; }
1857 1870

	
1858 1871
      bool operator==(const Arc &other) const {
1859 1872
        return _forward == other._forward && _edge == other._edge;
1860 1873
      }
1861 1874
      bool operator!=(const Arc &other) const {
1862 1875
        return _forward != other._forward || _edge != other._edge;
1863 1876
      }
1864 1877
      bool operator<(const Arc &other) const {
1865 1878
        return _forward < other._forward ||
1866 1879
          (_forward == other._forward && _edge < other._edge);
1867 1880
      }
1868 1881
    };
1869 1882

	
1870 1883
    void first(Node& n) const {
1871 1884
      _digraph->first(n);
1872 1885
    }
1873 1886

	
1874 1887
    void next(Node& n) const {
1875 1888
      _digraph->next(n);
1876 1889
    }
1877 1890

	
1878 1891
    void first(Arc& a) const {
1879 1892
      _digraph->first(a._edge);
1880 1893
      a._forward = true;
1881 1894
    }
1882 1895

	
1883 1896
    void next(Arc& a) const {
1884 1897
      if (a._forward) {
1885 1898
        a._forward = false;
1886 1899
      } else {
1887 1900
        _digraph->next(a._edge);
1888 1901
        a._forward = true;
1889 1902
      }
1890 1903
    }
1891 1904

	
1892 1905
    void first(Edge& e) const {
1893 1906
      _digraph->first(e);
1894 1907
    }
1895 1908

	
1896 1909
    void next(Edge& e) const {
1897 1910
      _digraph->next(e);
1898 1911
    }
1899 1912

	
1900 1913
    void firstOut(Arc& a, const Node& n) const {
1901 1914
      _digraph->firstIn(a._edge, n);
1902 1915
      if (a._edge != INVALID ) {
1903 1916
        a._forward = false;
1904 1917
      } else {
1905 1918
        _digraph->firstOut(a._edge, n);
1906 1919
        a._forward = true;
1907 1920
      }
1908 1921
    }
1909 1922
    void nextOut(Arc &a) const {
1910 1923
      if (!a._forward) {
1911 1924
        Node n = _digraph->target(a._edge);
1912 1925
        _digraph->nextIn(a._edge);
1913 1926
        if (a._edge == INVALID) {
1914 1927
          _digraph->firstOut(a._edge, n);
1915 1928
          a._forward = true;
1916 1929
        }
1917 1930
      }
1918 1931
      else {
1919 1932
        _digraph->nextOut(a._edge);
1920 1933
      }
1921 1934
    }
1922 1935

	
1923 1936
    void firstIn(Arc &a, const Node &n) const {
1924 1937
      _digraph->firstOut(a._edge, n);
1925 1938
      if (a._edge != INVALID ) {
1926 1939
        a._forward = false;
1927 1940
      } else {
1928 1941
        _digraph->firstIn(a._edge, n);
1929 1942
        a._forward = true;
1930 1943
      }
1931 1944
    }
1932 1945
    void nextIn(Arc &a) const {
1933 1946
      if (!a._forward) {
1934 1947
        Node n = _digraph->source(a._edge);
1935 1948
        _digraph->nextOut(a._edge);
1936 1949
        if (a._edge == INVALID ) {
1937 1950
          _digraph->firstIn(a._edge, n);
1938 1951
          a._forward = true;
1939 1952
        }
1940 1953
      }
1941 1954
      else {
1942 1955
        _digraph->nextIn(a._edge);
1943 1956
      }
1944 1957
    }
1945 1958

	
1946 1959
    void firstInc(Edge &e, bool &d, const Node &n) const {
1947 1960
      d = true;
1948 1961
      _digraph->firstOut(e, n);
1949 1962
      if (e != INVALID) return;
1950 1963
      d = false;
1951 1964
      _digraph->firstIn(e, n);
1952 1965
    }
1953 1966

	
1954 1967
    void nextInc(Edge &e, bool &d) const {
1955 1968
      if (d) {
1956 1969
        Node s = _digraph->source(e);
1957 1970
        _digraph->nextOut(e);
1958 1971
        if (e != INVALID) return;
1959 1972
        d = false;
1960 1973
        _digraph->firstIn(e, s);
1961 1974
      } else {
1962 1975
        _digraph->nextIn(e);
1963 1976
      }
1964 1977
    }
1965 1978

	
1966 1979
    Node u(const Edge& e) const {
1967 1980
      return _digraph->source(e);
1968 1981
    }
1969 1982

	
1970 1983
    Node v(const Edge& e) const {
1971 1984
      return _digraph->target(e);
1972 1985
    }
1973 1986

	
1974 1987
    Node source(const Arc &a) const {
1975 1988
      return a._forward ? _digraph->source(a._edge) : _digraph->target(a._edge);
1976 1989
    }
1977 1990

	
1978 1991
    Node target(const Arc &a) const {
1979 1992
      return a._forward ? _digraph->target(a._edge) : _digraph->source(a._edge);
1980 1993
    }
1981 1994

	
1982 1995
    static Arc direct(const Edge &e, bool d) {
1983 1996
      return Arc(e, d);
1984 1997
    }
1985 1998

	
1986 1999
    static bool direction(const Arc &a) { return a._forward; }
1987 2000

	
1988 2001
    Node nodeFromId(int ix) const { return _digraph->nodeFromId(ix); }
1989 2002
    Arc arcFromId(int ix) const {
1990 2003
      return direct(_digraph->arcFromId(ix >> 1), bool(ix & 1));
1991 2004
    }
1992 2005
    Edge edgeFromId(int ix) const { return _digraph->arcFromId(ix); }
1993 2006

	
1994 2007
    int id(const Node &n) const { return _digraph->id(n); }
1995 2008
    int id(const Arc &a) const {
1996 2009
      return  (_digraph->id(a) << 1) | (a._forward ? 1 : 0);
1997 2010
    }
1998 2011
    int id(const Edge &e) const { return _digraph->id(e); }
1999 2012

	
2000 2013
    int maxNodeId() const { return _digraph->maxNodeId(); }
2001 2014
    int maxArcId() const { return (_digraph->maxArcId() << 1) | 1; }
2002 2015
    int maxEdgeId() const { return _digraph->maxArcId(); }
2003 2016

	
2004 2017
    Node addNode() { return _digraph->addNode(); }
2005 2018
    Edge addEdge(const Node& u, const Node& v) {
2006 2019
      return _digraph->addArc(u, v);
2007 2020
    }
2008 2021

	
2009 2022
    void erase(const Node& i) { _digraph->erase(i); }
2010 2023
    void erase(const Edge& i) { _digraph->erase(i); }
2011 2024

	
2012 2025
    void clear() { _digraph->clear(); }
2013 2026

	
2014 2027
    typedef NodeNumTagIndicator<Digraph> NodeNumTag;
2015 2028
    int nodeNum() const { return _digraph->nodeNum(); }
2016 2029

	
2017 2030
    typedef ArcNumTagIndicator<Digraph> ArcNumTag;
2018 2031
    int arcNum() const { return 2 * _digraph->arcNum(); }
2019 2032

	
2020 2033
    typedef ArcNumTag EdgeNumTag;
2021 2034
    int edgeNum() const { return _digraph->arcNum(); }
2022 2035

	
2023 2036
    typedef FindArcTagIndicator<Digraph> FindArcTag;
2024 2037
    Arc findArc(Node s, Node t, Arc p = INVALID) const {
2025 2038
      if (p == INVALID) {
2026 2039
        Edge arc = _digraph->findArc(s, t);
2027 2040
        if (arc != INVALID) return direct(arc, true);
2028 2041
        arc = _digraph->findArc(t, s);
2029 2042
        if (arc != INVALID) return direct(arc, false);
2030 2043
      } else if (direction(p)) {
2031 2044
        Edge arc = _digraph->findArc(s, t, p);
2032 2045
        if (arc != INVALID) return direct(arc, true);
2033 2046
        arc = _digraph->findArc(t, s);
2034 2047
        if (arc != INVALID) return direct(arc, false);
2035 2048
      } else {
2036 2049
        Edge arc = _digraph->findArc(t, s, p);
2037 2050
        if (arc != INVALID) return direct(arc, false);
2038 2051
      }
2039 2052
      return INVALID;
2040 2053
    }
2041 2054

	
2042 2055
    typedef FindArcTag FindEdgeTag;
2043 2056
    Edge findEdge(Node s, Node t, Edge p = INVALID) const {
2044 2057
      if (s != t) {
2045 2058
        if (p == INVALID) {
2046 2059
          Edge arc = _digraph->findArc(s, t);
2047 2060
          if (arc != INVALID) return arc;
2048 2061
          arc = _digraph->findArc(t, s);
2049 2062
          if (arc != INVALID) return arc;
2050 2063
        } else if (_digraph->source(p) == s) {
2051 2064
          Edge arc = _digraph->findArc(s, t, p);
2052 2065
          if (arc != INVALID) return arc;
2053 2066
          arc = _digraph->findArc(t, s);
2054 2067
          if (arc != INVALID) return arc;
2055 2068
        } else {
2056 2069
          Edge arc = _digraph->findArc(t, s, p);
2057 2070
          if (arc != INVALID) return arc;
2058 2071
        }
2059 2072
      } else {
2060 2073
        return _digraph->findArc(s, t, p);
2061 2074
      }
2062 2075
      return INVALID;
2063 2076
    }
2064 2077

	
2065 2078
  private:
2066 2079

	
2067 2080
    template <typename V>
2068 2081
    class ArcMapBase {
2069 2082
    private:
2070 2083

	
2071 2084
      typedef typename DGR::template ArcMap<V> MapImpl;
2072 2085

	
2073 2086
    public:
2074 2087

	
2075 2088
      typedef typename MapTraits<MapImpl>::ReferenceMapTag ReferenceMapTag;
2076 2089

	
2077 2090
      typedef V Value;
2078 2091
      typedef Arc Key;
2079 2092
      typedef typename MapTraits<MapImpl>::ConstReturnValue ConstReturnValue;
2080 2093
      typedef typename MapTraits<MapImpl>::ReturnValue ReturnValue;
2081 2094
      typedef typename MapTraits<MapImpl>::ConstReturnValue ConstReference;
2082 2095
      typedef typename MapTraits<MapImpl>::ReturnValue Reference;
2083 2096

	
2084 2097
      ArcMapBase(const UndirectorBase<DGR>& adaptor) :
2085 2098
        _forward(*adaptor._digraph), _backward(*adaptor._digraph) {}
2086 2099

	
2087 2100
      ArcMapBase(const UndirectorBase<DGR>& adaptor, const V& value)
2088 2101
        : _forward(*adaptor._digraph, value), 
2089 2102
          _backward(*adaptor._digraph, value) {}
2090 2103

	
2091 2104
      void set(const Arc& a, const V& value) {
2092 2105
        if (direction(a)) {
2093 2106
          _forward.set(a, value);
2094 2107
        } else {
2095 2108
          _backward.set(a, value);
2096 2109
        }
2097 2110
      }
2098 2111

	
2099 2112
      ConstReturnValue operator[](const Arc& a) const {
2100 2113
        if (direction(a)) {
2101 2114
          return _forward[a];
2102 2115
        } else {
2103 2116
          return _backward[a];
2104 2117
        }
2105 2118
      }
2106 2119

	
2107 2120
      ReturnValue operator[](const Arc& a) {
2108 2121
        if (direction(a)) {
2109 2122
          return _forward[a];
2110 2123
        } else {
2111 2124
          return _backward[a];
2112 2125
        }
2113 2126
      }
2114 2127

	
2115 2128
    protected:
2116 2129

	
2117 2130
      MapImpl _forward, _backward;
2118 2131

	
2119 2132
    };
2120 2133

	
2121 2134
  public:
2122 2135

	
2123 2136
    template <typename V>
2124 2137
    class NodeMap : public DGR::template NodeMap<V> {
2125 2138
      typedef typename DGR::template NodeMap<V> Parent;
2126 2139

	
2127 2140
    public:
2128 2141
      typedef V Value;
2129 2142

	
2130 2143
      explicit NodeMap(const UndirectorBase<DGR>& adaptor)
2131 2144
        : Parent(*adaptor._digraph) {}
2132 2145

	
2133 2146
      NodeMap(const UndirectorBase<DGR>& adaptor, const V& value)
2134 2147
        : Parent(*adaptor._digraph, value) { }
2135 2148

	
2136 2149
    private:
2137 2150
      NodeMap& operator=(const NodeMap& cmap) {
2138 2151
        return operator=<NodeMap>(cmap);
2139 2152
      }
2140 2153

	
2141 2154
      template <typename CMap>
2142 2155
      NodeMap& operator=(const CMap& cmap) {
2143 2156
        Parent::operator=(cmap);
2144 2157
        return *this;
2145 2158
      }
2146 2159

	
2147 2160
    };
2148 2161

	
2149 2162
    template <typename V>
2150 2163
    class ArcMap
2151 2164
      : public SubMapExtender<UndirectorBase<DGR>, ArcMapBase<V> > {
2152 2165
      typedef SubMapExtender<UndirectorBase<DGR>, ArcMapBase<V> > Parent;
2153 2166

	
2154 2167
    public:
2155 2168
      typedef V Value;
2156 2169

	
2157 2170
      explicit ArcMap(const UndirectorBase<DGR>& adaptor)
2158 2171
        : Parent(adaptor) {}
2159 2172

	
2160 2173
      ArcMap(const UndirectorBase<DGR>& adaptor, const V& value)
2161 2174
        : Parent(adaptor, value) {}
2162 2175

	
2163 2176
    private:
2164 2177
      ArcMap& operator=(const ArcMap& cmap) {
2165 2178
        return operator=<ArcMap>(cmap);
2166 2179
      }
2167 2180

	
2168 2181
      template <typename CMap>
2169 2182
      ArcMap& operator=(const CMap& cmap) {
2170 2183
        Parent::operator=(cmap);
2171 2184
        return *this;
2172 2185
      }
2173 2186
    };
2174 2187

	
2175 2188
    template <typename V>
2176 2189
    class EdgeMap : public Digraph::template ArcMap<V> {
2177 2190
      typedef typename Digraph::template ArcMap<V> Parent;
2178 2191

	
2179 2192
    public:
2180 2193
      typedef V Value;
2181 2194

	
2182 2195
      explicit EdgeMap(const UndirectorBase<DGR>& adaptor)
2183 2196
        : Parent(*adaptor._digraph) {}
2184 2197

	
2185 2198
      EdgeMap(const UndirectorBase<DGR>& adaptor, const V& value)
2186 2199
        : Parent(*adaptor._digraph, value) {}
2187 2200

	
2188 2201
    private:
2189 2202
      EdgeMap& operator=(const EdgeMap& cmap) {
2190 2203
        return operator=<EdgeMap>(cmap);
2191 2204
      }
2192 2205

	
2193 2206
      template <typename CMap>
2194 2207
      EdgeMap& operator=(const CMap& cmap) {
2195 2208
        Parent::operator=(cmap);
2196 2209
        return *this;
2197 2210
      }
2198 2211

	
2199 2212
    };
2200 2213

	
2201 2214
    typedef typename ItemSetTraits<DGR, Node>::ItemNotifier NodeNotifier;
2202 2215
    NodeNotifier& notifier(Node) const { return _digraph->notifier(Node()); }
2203 2216

	
2204 2217
    typedef typename ItemSetTraits<DGR, Edge>::ItemNotifier EdgeNotifier;
2205 2218
    EdgeNotifier& notifier(Edge) const { return _digraph->notifier(Edge()); }
2206 2219
    
2207 2220
    typedef EdgeNotifier ArcNotifier;
2208 2221
    ArcNotifier& notifier(Arc) const { return _digraph->notifier(Edge()); }
2209 2222

	
2210 2223
  protected:
2211 2224

	
2212 2225
    UndirectorBase() : _digraph(0) {}
2213 2226

	
2214 2227
    DGR* _digraph;
2215 2228

	
2216 2229
    void initialize(DGR& digraph) {
2217 2230
      _digraph = &digraph;
2218 2231
    }
2219 2232

	
2220 2233
  };
2221 2234

	
2222 2235
  /// \ingroup graph_adaptors
2223 2236
  ///
2224 2237
  /// \brief Adaptor class for viewing a digraph as an undirected graph.
2225 2238
  ///
2226 2239
  /// Undirector adaptor can be used for viewing a digraph as an undirected
2227 2240
  /// graph. All arcs of the underlying digraph are showed in the
2228 2241
  /// adaptor as an edge (and also as a pair of arcs, of course).
2229 2242
  /// This adaptor conforms to the \ref concepts::Graph "Graph" concept.
2230 2243
  ///
2231 2244
  /// The adapted digraph can also be modified through this adaptor
2232 2245
  /// by adding or removing nodes or edges, unless the \c GR template
2233 2246
  /// parameter is set to be \c const.
2234 2247
  ///
2248
  /// This class provides item counting in the same time as the adapted
2249
  /// digraph structure.
2250
  ///
2235 2251
  /// \tparam DGR The type of the adapted digraph.
2236 2252
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
2237 2253
  /// It can also be specified to be \c const.
2238 2254
  ///
2239 2255
  /// \note The \c Node type of this adaptor and the adapted digraph are
2240 2256
  /// convertible to each other, moreover the \c Edge type of the adaptor
2241 2257
  /// and the \c Arc type of the adapted digraph are also convertible to
2242 2258
  /// each other.
2243 2259
  /// (Thus the \c Arc type of the adaptor is convertible to the \c Arc type
2244 2260
  /// of the adapted digraph.)
2245 2261
  template<typename DGR>
2246 2262
#ifdef DOXYGEN
2247 2263
  class Undirector {
2248 2264
#else
2249 2265
  class Undirector :
2250 2266
    public GraphAdaptorExtender<UndirectorBase<DGR> > {
2251 2267
#endif
2252 2268
    typedef GraphAdaptorExtender<UndirectorBase<DGR> > Parent;
2253 2269
  public:
2254 2270
    /// The type of the adapted digraph.
2255 2271
    typedef DGR Digraph;
2256 2272
  protected:
2257 2273
    Undirector() { }
2258 2274
  public:
2259 2275

	
2260 2276
    /// \brief Constructor
2261 2277
    ///
2262 2278
    /// Creates an undirected graph from the given digraph.
2263 2279
    Undirector(DGR& digraph) {
2264 2280
      initialize(digraph);
2265 2281
    }
2266 2282

	
2267 2283
    /// \brief Arc map combined from two original arc maps
2268 2284
    ///
2269 2285
    /// This map adaptor class adapts two arc maps of the underlying
2270 2286
    /// digraph to get an arc map of the undirected graph.
2271 2287
    /// Its value type is inherited from the first arc map type (\c FW).
2272 2288
    /// \tparam FW The type of the "foward" arc map.
2273 2289
    /// \tparam BK The type of the "backward" arc map.
2274 2290
    template <typename FW, typename BK>
2275 2291
    class CombinedArcMap {
2276 2292
    public:
2277 2293

	
2278 2294
      /// The key type of the map
2279 2295
      typedef typename Parent::Arc Key;
2280 2296
      /// The value type of the map
2281 2297
      typedef typename FW::Value Value;
2282 2298

	
2283 2299
      typedef typename MapTraits<FW>::ReferenceMapTag ReferenceMapTag;
2284 2300

	
2285 2301
      typedef typename MapTraits<FW>::ReturnValue ReturnValue;
2286 2302
      typedef typename MapTraits<FW>::ConstReturnValue ConstReturnValue;
2287 2303
      typedef typename MapTraits<FW>::ReturnValue Reference;
2288 2304
      typedef typename MapTraits<FW>::ConstReturnValue ConstReference;
2289 2305

	
2290 2306
      /// Constructor
2291 2307
      CombinedArcMap(FW& forward, BK& backward)
2292 2308
        : _forward(&forward), _backward(&backward) {}
2293 2309

	
2294 2310
      /// Sets the value associated with the given key.
2295 2311
      void set(const Key& e, const Value& a) {
2296 2312
        if (Parent::direction(e)) {
2297 2313
          _forward->set(e, a);
2298 2314
        } else {
2299 2315
          _backward->set(e, a);
2300 2316
        }
2301 2317
      }
2302 2318

	
2303 2319
      /// Returns the value associated with the given key.
2304 2320
      ConstReturnValue operator[](const Key& e) const {
2305 2321
        if (Parent::direction(e)) {
2306 2322
          return (*_forward)[e];
2307 2323
        } else {
2308 2324
          return (*_backward)[e];
2309 2325
        }
2310 2326
      }
2311 2327

	
2312 2328
      /// Returns a reference to the value associated with the given key.
2313 2329
      ReturnValue operator[](const Key& e) {
2314 2330
        if (Parent::direction(e)) {
2315 2331
          return (*_forward)[e];
2316 2332
        } else {
2317 2333
          return (*_backward)[e];
2318 2334
        }
2319 2335
      }
2320 2336

	
2321 2337
    protected:
2322 2338

	
2323 2339
      FW* _forward;
2324 2340
      BK* _backward;
2325 2341

	
2326 2342
    };
2327 2343

	
2328 2344
    /// \brief Returns a combined arc map
2329 2345
    ///
2330 2346
    /// This function just returns a combined arc map.
2331 2347
    template <typename FW, typename BK>
2332 2348
    static CombinedArcMap<FW, BK>
2333 2349
    combinedArcMap(FW& forward, BK& backward) {
2334 2350
      return CombinedArcMap<FW, BK>(forward, backward);
2335 2351
    }
2336 2352

	
2337 2353
    template <typename FW, typename BK>
2338 2354
    static CombinedArcMap<const FW, BK>
2339 2355
    combinedArcMap(const FW& forward, BK& backward) {
2340 2356
      return CombinedArcMap<const FW, BK>(forward, backward);
2341 2357
    }
2342 2358

	
2343 2359
    template <typename FW, typename BK>
2344 2360
    static CombinedArcMap<FW, const BK>
2345 2361
    combinedArcMap(FW& forward, const BK& backward) {
2346 2362
      return CombinedArcMap<FW, const BK>(forward, backward);
2347 2363
    }
2348 2364

	
2349 2365
    template <typename FW, typename BK>
2350 2366
    static CombinedArcMap<const FW, const BK>
2351 2367
    combinedArcMap(const FW& forward, const BK& backward) {
2352 2368
      return CombinedArcMap<const FW, const BK>(forward, backward);
2353 2369
    }
2354 2370

	
2355 2371
  };
2356 2372

	
2357 2373
  /// \brief Returns a read-only Undirector adaptor
2358 2374
  ///
2359 2375
  /// This function just returns a read-only \ref Undirector adaptor.
2360 2376
  /// \ingroup graph_adaptors
2361 2377
  /// \relates Undirector
2362 2378
  template<typename DGR>
2363 2379
  Undirector<const DGR> undirector(const DGR& digraph) {
2364 2380
    return Undirector<const DGR>(digraph);
2365 2381
  }
2366 2382

	
2367 2383

	
2368 2384
  template <typename GR, typename DM>
2369 2385
  class OrienterBase {
2370 2386
  public:
2371 2387

	
2372 2388
    typedef GR Graph;
2373 2389
    typedef DM DirectionMap;
2374 2390

	
2375 2391
    typedef typename GR::Node Node;
2376 2392
    typedef typename GR::Edge Arc;
2377 2393

	
2378 2394
    void reverseArc(const Arc& arc) {
2379 2395
      _direction->set(arc, !(*_direction)[arc]);
2380 2396
    }
2381 2397

	
2382 2398
    void first(Node& i) const { _graph->first(i); }
2383 2399
    void first(Arc& i) const { _graph->first(i); }
2384 2400
    void firstIn(Arc& i, const Node& n) const {
2385 2401
      bool d = true;
2386 2402
      _graph->firstInc(i, d, n);
2387 2403
      while (i != INVALID && d == (*_direction)[i]) _graph->nextInc(i, d);
2388 2404
    }
2389 2405
    void firstOut(Arc& i, const Node& n ) const {
2390 2406
      bool d = true;
2391 2407
      _graph->firstInc(i, d, n);
2392 2408
      while (i != INVALID && d != (*_direction)[i]) _graph->nextInc(i, d);
2393 2409
    }
2394 2410

	
2395 2411
    void next(Node& i) const { _graph->next(i); }
2396 2412
    void next(Arc& i) const { _graph->next(i); }
2397 2413
    void nextIn(Arc& i) const {
2398 2414
      bool d = !(*_direction)[i];
2399 2415
      _graph->nextInc(i, d);
2400 2416
      while (i != INVALID && d == (*_direction)[i]) _graph->nextInc(i, d);
2401 2417
    }
2402 2418
    void nextOut(Arc& i) const {
2403 2419
      bool d = (*_direction)[i];
2404 2420
      _graph->nextInc(i, d);
2405 2421
      while (i != INVALID && d != (*_direction)[i]) _graph->nextInc(i, d);
2406 2422
    }
2407 2423

	
2408 2424
    Node source(const Arc& e) const {
2409 2425
      return (*_direction)[e] ? _graph->u(e) : _graph->v(e);
2410 2426
    }
2411 2427
    Node target(const Arc& e) const {
2412 2428
      return (*_direction)[e] ? _graph->v(e) : _graph->u(e);
2413 2429
    }
2414 2430

	
2415 2431
    typedef NodeNumTagIndicator<Graph> NodeNumTag;
2416 2432
    int nodeNum() const { return _graph->nodeNum(); }
2417 2433

	
2418 2434
    typedef EdgeNumTagIndicator<Graph> ArcNumTag;
2419 2435
    int arcNum() const { return _graph->edgeNum(); }
2420 2436

	
2421 2437
    typedef FindEdgeTagIndicator<Graph> FindArcTag;
2422 2438
    Arc findArc(const Node& u, const Node& v,
2423 2439
                const Arc& prev = INVALID) const {
2424 2440
      Arc arc = _graph->findEdge(u, v, prev);
2425 2441
      while (arc != INVALID && source(arc) != u) {
2426 2442
        arc = _graph->findEdge(u, v, arc);
2427 2443
      }
2428 2444
      return arc;
2429 2445
    }
2430 2446

	
2431 2447
    Node addNode() {
2432 2448
      return Node(_graph->addNode());
2433 2449
    }
2434 2450

	
2435 2451
    Arc addArc(const Node& u, const Node& v) {
2436 2452
      Arc arc = _graph->addEdge(u, v);
2437 2453
      _direction->set(arc, _graph->u(arc) == u);
2438 2454
      return arc;
2439 2455
    }
2440 2456

	
2441 2457
    void erase(const Node& i) { _graph->erase(i); }
2442 2458
    void erase(const Arc& i) { _graph->erase(i); }
2443 2459

	
2444 2460
    void clear() { _graph->clear(); }
2445 2461

	
2446 2462
    int id(const Node& v) const { return _graph->id(v); }
2447 2463
    int id(const Arc& e) const { return _graph->id(e); }
2448 2464

	
2449 2465
    Node nodeFromId(int idx) const { return _graph->nodeFromId(idx); }
2450 2466
    Arc arcFromId(int idx) const { return _graph->edgeFromId(idx); }
2451 2467

	
2452 2468
    int maxNodeId() const { return _graph->maxNodeId(); }
2453 2469
    int maxArcId() const { return _graph->maxEdgeId(); }
2454 2470

	
2455 2471
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
2456 2472
    NodeNotifier& notifier(Node) const { return _graph->notifier(Node()); }
2457 2473

	
2458 2474
    typedef typename ItemSetTraits<GR, Arc>::ItemNotifier ArcNotifier;
2459 2475
    ArcNotifier& notifier(Arc) const { return _graph->notifier(Arc()); }
2460 2476

	
2461 2477
    template <typename V>
2462 2478
    class NodeMap : public GR::template NodeMap<V> {
2463 2479
      typedef typename GR::template NodeMap<V> Parent;
2464 2480

	
2465 2481
    public:
2466 2482

	
2467 2483
      explicit NodeMap(const OrienterBase<GR, DM>& adapter)
2468 2484
        : Parent(*adapter._graph) {}
2469 2485

	
2470 2486
      NodeMap(const OrienterBase<GR, DM>& adapter, const V& value)
2471 2487
        : Parent(*adapter._graph, value) {}
2472 2488

	
2473 2489
    private:
2474 2490
      NodeMap& operator=(const NodeMap& cmap) {
2475 2491
        return operator=<NodeMap>(cmap);
2476 2492
      }
2477 2493

	
2478 2494
      template <typename CMap>
2479 2495
      NodeMap& operator=(const CMap& cmap) {
2480 2496
        Parent::operator=(cmap);
2481 2497
        return *this;
2482 2498
      }
2483 2499

	
2484 2500
    };
2485 2501

	
2486 2502
    template <typename V>
2487 2503
    class ArcMap : public GR::template EdgeMap<V> {
2488 2504
      typedef typename Graph::template EdgeMap<V> Parent;
2489 2505

	
2490 2506
    public:
2491 2507

	
2492 2508
      explicit ArcMap(const OrienterBase<GR, DM>& adapter)
2493 2509
        : Parent(*adapter._graph) { }
2494 2510

	
2495 2511
      ArcMap(const OrienterBase<GR, DM>& adapter, const V& value)
2496 2512
        : Parent(*adapter._graph, value) { }
2497 2513

	
2498 2514
    private:
2499 2515
      ArcMap& operator=(const ArcMap& cmap) {
2500 2516
        return operator=<ArcMap>(cmap);
2501 2517
      }
2502 2518

	
2503 2519
      template <typename CMap>
2504 2520
      ArcMap& operator=(const CMap& cmap) {
2505 2521
        Parent::operator=(cmap);
2506 2522
        return *this;
2507 2523
      }
2508 2524
    };
2509 2525

	
2510 2526

	
2511 2527

	
2512 2528
  protected:
2513 2529
    Graph* _graph;
2514 2530
    DM* _direction;
2515 2531

	
2516 2532
    void initialize(GR& graph, DM& direction) {
2517 2533
      _graph = &graph;
2518 2534
      _direction = &direction;
2519 2535
    }
2520 2536

	
2521 2537
  };
2522 2538

	
2523 2539
  /// \ingroup graph_adaptors
2524 2540
  ///
2525 2541
  /// \brief Adaptor class for orienting the edges of a graph to get a digraph
2526 2542
  ///
2527 2543
  /// Orienter adaptor can be used for orienting the edges of a graph to
2528 2544
  /// get a digraph. A \c bool edge map of the underlying graph must be
2529 2545
  /// specified, which define the direction of the arcs in the adaptor.
2530 2546
  /// The arcs can be easily reversed by the \c reverseArc() member function
2531 2547
  /// of the adaptor.
2532 2548
  /// This class conforms to the \ref concepts::Digraph "Digraph" concept.
2533 2549
  ///
2534 2550
  /// The adapted graph can also be modified through this adaptor
2535 2551
  /// by adding or removing nodes or arcs, unless the \c GR template
2536 2552
  /// parameter is set to be \c const.
2537 2553
  ///
2554
  /// This class provides item counting in the same time as the adapted
2555
  /// graph structure.
2556
  ///
2538 2557
  /// \tparam GR The type of the adapted graph.
2539 2558
  /// It must conform to the \ref concepts::Graph "Graph" concept.
2540 2559
  /// It can also be specified to be \c const.
2541 2560
  /// \tparam DM The type of the direction map.
2542 2561
  /// It must be a \c bool (or convertible) edge map of the
2543 2562
  /// adapted graph. The default type is
2544 2563
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<bool>".
2545 2564
  ///
2546 2565
  /// \note The \c Node type of this adaptor and the adapted graph are
2547 2566
  /// convertible to each other, moreover the \c Arc type of the adaptor
2548 2567
  /// and the \c Edge type of the adapted graph are also convertible to
2549 2568
  /// each other.
2550 2569
#ifdef DOXYGEN
2551 2570
  template<typename GR,
2552 2571
           typename DM>
2553 2572
  class Orienter {
2554 2573
#else
2555 2574
  template<typename GR,
2556 2575
           typename DM = typename GR::template EdgeMap<bool> >
2557 2576
  class Orienter :
2558 2577
    public DigraphAdaptorExtender<OrienterBase<GR, DM> > {
2559 2578
#endif
2560 2579
    typedef DigraphAdaptorExtender<OrienterBase<GR, DM> > Parent;
2561 2580
  public:
2562 2581

	
2563 2582
    /// The type of the adapted graph.
2564 2583
    typedef GR Graph;
2565 2584
    /// The type of the direction edge map.
2566 2585
    typedef DM DirectionMap;
2567 2586

	
2568 2587
    typedef typename Parent::Arc Arc;
2569 2588

	
2570 2589
  protected:
2571 2590
    Orienter() { }
2572 2591

	
2573 2592
  public:
2574 2593

	
2575 2594
    /// \brief Constructor
2576 2595
    ///
2577 2596
    /// Constructor of the adaptor.
2578 2597
    Orienter(GR& graph, DM& direction) {
2579 2598
      Parent::initialize(graph, direction);
2580 2599
    }
2581 2600

	
2582 2601
    /// \brief Reverses the given arc
2583 2602
    ///
2584 2603
    /// This function reverses the given arc.
2585 2604
    /// It is done by simply negate the assigned value of \c a
2586 2605
    /// in the direction map.
2587 2606
    void reverseArc(const Arc& a) {
2588 2607
      Parent::reverseArc(a);
2589 2608
    }
2590 2609
  };
2591 2610

	
2592 2611
  /// \brief Returns a read-only Orienter adaptor
2593 2612
  ///
2594 2613
  /// This function just returns a read-only \ref Orienter adaptor.
2595 2614
  /// \ingroup graph_adaptors
2596 2615
  /// \relates Orienter
2597 2616
  template<typename GR, typename DM>
2598 2617
  Orienter<const GR, DM>
2599 2618
  orienter(const GR& graph, DM& direction) {
2600 2619
    return Orienter<const GR, DM>(graph, direction);
2601 2620
  }
2602 2621

	
2603 2622
  template<typename GR, typename DM>
2604 2623
  Orienter<const GR, const DM>
2605 2624
  orienter(const GR& graph, const DM& direction) {
2606 2625
    return Orienter<const GR, const DM>(graph, direction);
2607 2626
  }
2608 2627

	
2609 2628
  namespace _adaptor_bits {
2610 2629

	
2611 2630
    template <typename DGR, typename CM, typename FM, typename TL>
2612 2631
    class ResForwardFilter {
2613 2632
    public:
2614 2633

	
2615 2634
      typedef typename DGR::Arc Key;
2616 2635
      typedef bool Value;
2617 2636

	
2618 2637
    private:
2619 2638

	
2620 2639
      const CM* _capacity;
2621 2640
      const FM* _flow;
2622 2641
      TL _tolerance;
2623 2642

	
2624 2643
    public:
2625 2644

	
2626 2645
      ResForwardFilter(const CM& capacity, const FM& flow,
2627 2646
                       const TL& tolerance = TL())
2628 2647
        : _capacity(&capacity), _flow(&flow), _tolerance(tolerance) { }
2629 2648

	
2630 2649
      bool operator[](const typename DGR::Arc& a) const {
2631 2650
        return _tolerance.positive((*_capacity)[a] - (*_flow)[a]);
2632 2651
      }
2633 2652
    };
2634 2653

	
2635 2654
    template<typename DGR,typename CM, typename FM, typename TL>
2636 2655
    class ResBackwardFilter {
2637 2656
    public:
2638 2657

	
2639 2658
      typedef typename DGR::Arc Key;
2640 2659
      typedef bool Value;
2641 2660

	
2642 2661
    private:
2643 2662

	
2644 2663
      const CM* _capacity;
2645 2664
      const FM* _flow;
2646 2665
      TL _tolerance;
2647 2666

	
2648 2667
    public:
2649 2668

	
2650 2669
      ResBackwardFilter(const CM& capacity, const FM& flow,
2651 2670
                        const TL& tolerance = TL())
2652 2671
        : _capacity(&capacity), _flow(&flow), _tolerance(tolerance) { }
2653 2672

	
2654 2673
      bool operator[](const typename DGR::Arc& a) const {
2655 2674
        return _tolerance.positive((*_flow)[a]);
2656 2675
      }
2657 2676
    };
2658 2677

	
2659 2678
  }
2660 2679

	
2661 2680
  /// \ingroup graph_adaptors
2662 2681
  ///
2663 2682
  /// \brief Adaptor class for composing the residual digraph for directed
2664 2683
  /// flow and circulation problems.
2665 2684
  ///
2666 2685
  /// ResidualDigraph can be used for composing the \e residual digraph
2667 2686
  /// for directed flow and circulation problems. Let \f$ G=(V, A) \f$
2668 2687
  /// be a directed graph and let \f$ F \f$ be a number type.
2669 2688
  /// Let \f$ flow, cap: A\to F \f$ be functions on the arcs.
2670 2689
  /// This adaptor implements a digraph structure with node set \f$ V \f$
2671 2690
  /// and arc set \f$ A_{forward}\cup A_{backward} \f$,
2672 2691
  /// where \f$ A_{forward}=\{uv : uv\in A, flow(uv)<cap(uv)\} \f$ and
2673 2692
  /// \f$ A_{backward}=\{vu : uv\in A, flow(uv)>0\} \f$, i.e. the so
2674 2693
  /// called residual digraph.
2675 2694
  /// When the union \f$ A_{forward}\cup A_{backward} \f$ is taken,
2676 2695
  /// multiplicities are counted, i.e. the adaptor has exactly
2677 2696
  /// \f$ |A_{forward}| + |A_{backward}|\f$ arcs (it may have parallel
2678 2697
  /// arcs).
2679 2698
  /// This class conforms to the \ref concepts::Digraph "Digraph" concept.
2680 2699
  ///
2700
  /// This class provides only linear time counting for nodes and arcs.
2701
  ///
2681 2702
  /// \tparam DGR The type of the adapted digraph.
2682 2703
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
2683 2704
  /// It is implicitly \c const.
2684 2705
  /// \tparam CM The type of the capacity map.
2685 2706
  /// It must be an arc map of some numerical type, which defines
2686 2707
  /// the capacities in the flow problem. It is implicitly \c const.
2687 2708
  /// The default type is
2688 2709
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
2689 2710
  /// \tparam FM The type of the flow map.
2690 2711
  /// It must be an arc map of some numerical type, which defines
2691 2712
  /// the flow values in the flow problem. The default type is \c CM.
2692 2713
  /// \tparam TL The tolerance type for handling inexact computation.
2693 2714
  /// The default tolerance type depends on the value type of the
2694 2715
  /// capacity map.
2695 2716
  ///
2696 2717
  /// \note This adaptor is implemented using Undirector and FilterArcs
2697 2718
  /// adaptors.
2698 2719
  ///
2699 2720
  /// \note The \c Node type of this adaptor and the adapted digraph are
2700 2721
  /// convertible to each other, moreover the \c Arc type of the adaptor
2701 2722
  /// is convertible to the \c Arc type of the adapted digraph.
2702 2723
#ifdef DOXYGEN
2703 2724
  template<typename DGR, typename CM, typename FM, typename TL>
2704 2725
  class ResidualDigraph
2705 2726
#else
2706 2727
  template<typename DGR,
2707 2728
           typename CM = typename DGR::template ArcMap<int>,
2708 2729
           typename FM = CM,
2709 2730
           typename TL = Tolerance<typename CM::Value> >
2710 2731
  class ResidualDigraph 
2711 2732
    : public SubDigraph<
2712 2733
        Undirector<const DGR>,
2713 2734
        ConstMap<typename DGR::Node, Const<bool, true> >,
2714 2735
        typename Undirector<const DGR>::template CombinedArcMap<
2715 2736
          _adaptor_bits::ResForwardFilter<const DGR, CM, FM, TL>,
2716 2737
          _adaptor_bits::ResBackwardFilter<const DGR, CM, FM, TL> > >
2717 2738
#endif
2718 2739
  {
2719 2740
  public:
2720 2741

	
2721 2742
    /// The type of the underlying digraph.
2722 2743
    typedef DGR Digraph;
2723 2744
    /// The type of the capacity map.
2724 2745
    typedef CM CapacityMap;
2725 2746
    /// The type of the flow map.
2726 2747
    typedef FM FlowMap;
2727 2748
    /// The tolerance type.
2728 2749
    typedef TL Tolerance;
2729 2750

	
2730 2751
    typedef typename CapacityMap::Value Value;
2731 2752
    typedef ResidualDigraph Adaptor;
2732 2753

	
2733 2754
  protected:
2734 2755

	
2735 2756
    typedef Undirector<const Digraph> Undirected;
2736 2757

	
2737 2758
    typedef ConstMap<typename DGR::Node, Const<bool, true> > NodeFilter;
2738 2759

	
2739 2760
    typedef _adaptor_bits::ResForwardFilter<const DGR, CM,
2740 2761
                                            FM, TL> ForwardFilter;
2741 2762

	
2742 2763
    typedef _adaptor_bits::ResBackwardFilter<const DGR, CM,
2743 2764
                                             FM, TL> BackwardFilter;
2744 2765

	
2745 2766
    typedef typename Undirected::
2746 2767
      template CombinedArcMap<ForwardFilter, BackwardFilter> ArcFilter;
2747 2768

	
2748 2769
    typedef SubDigraph<Undirected, NodeFilter, ArcFilter> Parent;
2749 2770

	
2750 2771
    const CapacityMap* _capacity;
2751 2772
    FlowMap* _flow;
2752 2773

	
2753 2774
    Undirected _graph;
2754 2775
    NodeFilter _node_filter;
2755 2776
    ForwardFilter _forward_filter;
2756 2777
    BackwardFilter _backward_filter;
2757 2778
    ArcFilter _arc_filter;
2758 2779

	
2759 2780
  public:
2760 2781

	
2761 2782
    /// \brief Constructor
2762 2783
    ///
2763 2784
    /// Constructor of the residual digraph adaptor. The parameters are the
2764 2785
    /// digraph, the capacity map, the flow map, and a tolerance object.
2765 2786
    ResidualDigraph(const DGR& digraph, const CM& capacity,
2766 2787
                    FM& flow, const TL& tolerance = Tolerance())
2767 2788
      : Parent(), _capacity(&capacity), _flow(&flow), 
2768 2789
        _graph(digraph), _node_filter(),
2769 2790
        _forward_filter(capacity, flow, tolerance),
2770 2791
        _backward_filter(capacity, flow, tolerance),
2771 2792
        _arc_filter(_forward_filter, _backward_filter)
2772 2793
    {
2773 2794
      Parent::initialize(_graph, _node_filter, _arc_filter);
2774 2795
    }
2775 2796

	
2776 2797
    typedef typename Parent::Arc Arc;
2777 2798

	
2778 2799
    /// \brief Returns the residual capacity of the given arc.
2779 2800
    ///
2780 2801
    /// Returns the residual capacity of the given arc.
2781 2802
    Value residualCapacity(const Arc& a) const {
2782 2803
      if (Undirected::direction(a)) {
2783 2804
        return (*_capacity)[a] - (*_flow)[a];
2784 2805
      } else {
2785 2806
        return (*_flow)[a];
2786 2807
      }
2787 2808
    }
2788 2809

	
2789 2810
    /// \brief Augments on the given arc in the residual digraph.
2790 2811
    ///
2791 2812
    /// Augments on the given arc in the residual digraph. It increases
2792 2813
    /// or decreases the flow value on the original arc according to the
2793 2814
    /// direction of the residual arc.
2794 2815
    void augment(const Arc& a, const Value& v) const {
2795 2816
      if (Undirected::direction(a)) {
2796 2817
        _flow->set(a, (*_flow)[a] + v);
2797 2818
      } else {
2798 2819
        _flow->set(a, (*_flow)[a] - v);
2799 2820
      }
2800 2821
    }
2801 2822

	
2802 2823
    /// \brief Returns \c true if the given residual arc is a forward arc.
2803 2824
    ///
2804 2825
    /// Returns \c true if the given residual arc has the same orientation
2805 2826
    /// as the original arc, i.e. it is a so called forward arc.
2806 2827
    static bool forward(const Arc& a) {
2807 2828
      return Undirected::direction(a);
2808 2829
    }
2809 2830

	
2810 2831
    /// \brief Returns \c true if the given residual arc is a backward arc.
2811 2832
    ///
2812 2833
    /// Returns \c true if the given residual arc has the opposite orientation
2813 2834
    /// than the original arc, i.e. it is a so called backward arc.
2814 2835
    static bool backward(const Arc& a) {
2815 2836
      return !Undirected::direction(a);
2816 2837
    }
2817 2838

	
2818 2839
    /// \brief Returns the forward oriented residual arc.
2819 2840
    ///
2820 2841
    /// Returns the forward oriented residual arc related to the given
2821 2842
    /// arc of the underlying digraph.
2822 2843
    static Arc forward(const typename Digraph::Arc& a) {
2823 2844
      return Undirected::direct(a, true);
2824 2845
    }
2825 2846

	
2826 2847
    /// \brief Returns the backward oriented residual arc.
2827 2848
    ///
2828 2849
    /// Returns the backward oriented residual arc related to the given
2829 2850
    /// arc of the underlying digraph.
2830 2851
    static Arc backward(const typename Digraph::Arc& a) {
2831 2852
      return Undirected::direct(a, false);
2832 2853
    }
2833 2854

	
2834 2855
    /// \brief Residual capacity map.
2835 2856
    ///
2836 2857
    /// This map adaptor class can be used for obtaining the residual
2837 2858
    /// capacities as an arc map of the residual digraph.
2838 2859
    /// Its value type is inherited from the capacity map.
2839 2860
    class ResidualCapacity {
2840 2861
    protected:
2841 2862
      const Adaptor* _adaptor;
2842 2863
    public:
2843 2864
      /// The key type of the map
2844 2865
      typedef Arc Key;
2845 2866
      /// The value type of the map
2846 2867
      typedef typename CapacityMap::Value Value;
2847 2868

	
2848 2869
      /// Constructor
2849 2870
      ResidualCapacity(const ResidualDigraph<DGR, CM, FM, TL>& adaptor) 
2850 2871
        : _adaptor(&adaptor) {}
2851 2872

	
2852 2873
      /// Returns the value associated with the given residual arc
2853 2874
      Value operator[](const Arc& a) const {
2854 2875
        return _adaptor->residualCapacity(a);
2855 2876
      }
2856 2877

	
2857 2878
    };
2858 2879

	
2859 2880
    /// \brief Returns a residual capacity map
2860 2881
    ///
2861 2882
    /// This function just returns a residual capacity map.
2862 2883
    ResidualCapacity residualCapacity() const {
2863 2884
      return ResidualCapacity(*this);
2864 2885
    }
2865 2886

	
2866 2887
  };
2867 2888

	
2868 2889
  /// \brief Returns a (read-only) Residual adaptor
2869 2890
  ///
2870 2891
  /// This function just returns a (read-only) \ref ResidualDigraph adaptor.
2871 2892
  /// \ingroup graph_adaptors
2872 2893
  /// \relates ResidualDigraph
2873 2894
    template<typename DGR, typename CM, typename FM>
2874 2895
  ResidualDigraph<DGR, CM, FM>
2875 2896
  residualDigraph(const DGR& digraph, const CM& capacity_map, FM& flow_map) {
2876 2897
    return ResidualDigraph<DGR, CM, FM> (digraph, capacity_map, flow_map);
2877 2898
  }
2878 2899

	
2879 2900

	
2880 2901
  template <typename DGR>
2881 2902
  class SplitNodesBase {
2882 2903
    typedef DigraphAdaptorBase<const DGR> Parent;
2883 2904

	
2884 2905
  public:
2885 2906

	
2886 2907
    typedef DGR Digraph;
2887 2908
    typedef SplitNodesBase Adaptor;
2888 2909

	
2889 2910
    typedef typename DGR::Node DigraphNode;
2890 2911
    typedef typename DGR::Arc DigraphArc;
2891 2912

	
2892 2913
    class Node;
2893 2914
    class Arc;
2894 2915

	
2895 2916
  private:
2896 2917

	
2897 2918
    template <typename T> class NodeMapBase;
2898 2919
    template <typename T> class ArcMapBase;
2899 2920

	
2900 2921
  public:
2901 2922

	
2902 2923
    class Node : public DigraphNode {
2903 2924
      friend class SplitNodesBase;
2904 2925
      template <typename T> friend class NodeMapBase;
2905 2926
    private:
2906 2927

	
2907 2928
      bool _in;
2908 2929
      Node(DigraphNode node, bool in)
2909 2930
        : DigraphNode(node), _in(in) {}
2910 2931

	
2911 2932
    public:
2912 2933

	
2913 2934
      Node() {}
2914 2935
      Node(Invalid) : DigraphNode(INVALID), _in(true) {}
2915 2936

	
2916 2937
      bool operator==(const Node& node) const {
2917 2938
        return DigraphNode::operator==(node) && _in == node._in;
2918 2939
      }
2919 2940

	
2920 2941
      bool operator!=(const Node& node) const {
2921 2942
        return !(*this == node);
2922 2943
      }
2923 2944

	
2924 2945
      bool operator<(const Node& node) const {
2925 2946
        return DigraphNode::operator<(node) ||
2926 2947
          (DigraphNode::operator==(node) && _in < node._in);
2927 2948
      }
2928 2949
    };
2929 2950

	
2930 2951
    class Arc {
2931 2952
      friend class SplitNodesBase;
2932 2953
      template <typename T> friend class ArcMapBase;
2933 2954
    private:
2934 2955
      typedef BiVariant<DigraphArc, DigraphNode> ArcImpl;
2935 2956

	
2936 2957
      explicit Arc(const DigraphArc& arc) : _item(arc) {}
2937 2958
      explicit Arc(const DigraphNode& node) : _item(node) {}
2938 2959

	
2939 2960
      ArcImpl _item;
2940 2961

	
2941 2962
    public:
2942 2963
      Arc() {}
2943 2964
      Arc(Invalid) : _item(DigraphArc(INVALID)) {}
2944 2965

	
2945 2966
      bool operator==(const Arc& arc) const {
2946 2967
        if (_item.firstState()) {
2947 2968
          if (arc._item.firstState()) {
2948 2969
            return _item.first() == arc._item.first();
2949 2970
          }
2950 2971
        } else {
2951 2972
          if (arc._item.secondState()) {
2952 2973
            return _item.second() == arc._item.second();
2953 2974
          }
2954 2975
        }
2955 2976
        return false;
2956 2977
      }
2957 2978

	
2958 2979
      bool operator!=(const Arc& arc) const {
2959 2980
        return !(*this == arc);
2960 2981
      }
2961 2982

	
2962 2983
      bool operator<(const Arc& arc) const {
2963 2984
        if (_item.firstState()) {
2964 2985
          if (arc._item.firstState()) {
2965 2986
            return _item.first() < arc._item.first();
2966 2987
          }
2967 2988
          return false;
2968 2989
        } else {
2969 2990
          if (arc._item.secondState()) {
2970 2991
            return _item.second() < arc._item.second();
2971 2992
          }
2972 2993
          return true;
2973 2994
        }
2974 2995
      }
2975 2996

	
2976 2997
      operator DigraphArc() const { return _item.first(); }
2977 2998
      operator DigraphNode() const { return _item.second(); }
2978 2999

	
2979 3000
    };
2980 3001

	
2981 3002
    void first(Node& n) const {
2982 3003
      _digraph->first(n);
2983 3004
      n._in = true;
2984 3005
    }
2985 3006

	
2986 3007
    void next(Node& n) const {
2987 3008
      if (n._in) {
2988 3009
        n._in = false;
2989 3010
      } else {
2990 3011
        n._in = true;
2991 3012
        _digraph->next(n);
2992 3013
      }
2993 3014
    }
2994 3015

	
2995 3016
    void first(Arc& e) const {
2996 3017
      e._item.setSecond();
2997 3018
      _digraph->first(e._item.second());
2998 3019
      if (e._item.second() == INVALID) {
2999 3020
        e._item.setFirst();
3000 3021
        _digraph->first(e._item.first());
3001 3022
      }
3002 3023
    }
3003 3024

	
3004 3025
    void next(Arc& e) const {
3005 3026
      if (e._item.secondState()) {
3006 3027
        _digraph->next(e._item.second());
3007 3028
        if (e._item.second() == INVALID) {
3008 3029
          e._item.setFirst();
3009 3030
          _digraph->first(e._item.first());
3010 3031
        }
3011 3032
      } else {
3012 3033
        _digraph->next(e._item.first());
3013 3034
      }
3014 3035
    }
3015 3036

	
3016 3037
    void firstOut(Arc& e, const Node& n) const {
3017 3038
      if (n._in) {
3018 3039
        e._item.setSecond(n);
3019 3040
      } else {
3020 3041
        e._item.setFirst();
3021 3042
        _digraph->firstOut(e._item.first(), n);
3022 3043
      }
3023 3044
    }
3024 3045

	
3025 3046
    void nextOut(Arc& e) const {
3026 3047
      if (!e._item.firstState()) {
3027 3048
        e._item.setFirst(INVALID);
3028 3049
      } else {
3029 3050
        _digraph->nextOut(e._item.first());
3030 3051
      }
3031 3052
    }
3032 3053

	
3033 3054
    void firstIn(Arc& e, const Node& n) const {
3034 3055
      if (!n._in) {
3035 3056
        e._item.setSecond(n);
3036 3057
      } else {
3037 3058
        e._item.setFirst();
3038 3059
        _digraph->firstIn(e._item.first(), n);
3039 3060
      }
3040 3061
    }
3041 3062

	
3042 3063
    void nextIn(Arc& e) const {
3043 3064
      if (!e._item.firstState()) {
3044 3065
        e._item.setFirst(INVALID);
3045 3066
      } else {
3046 3067
        _digraph->nextIn(e._item.first());
3047 3068
      }
3048 3069
    }
3049 3070

	
3050 3071
    Node source(const Arc& e) const {
3051 3072
      if (e._item.firstState()) {
3052 3073
        return Node(_digraph->source(e._item.first()), false);
3053 3074
      } else {
3054 3075
        return Node(e._item.second(), true);
3055 3076
      }
3056 3077
    }
3057 3078

	
3058 3079
    Node target(const Arc& e) const {
3059 3080
      if (e._item.firstState()) {
3060 3081
        return Node(_digraph->target(e._item.first()), true);
3061 3082
      } else {
3062 3083
        return Node(e._item.second(), false);
3063 3084
      }
3064 3085
    }
3065 3086

	
3066 3087
    int id(const Node& n) const {
3067 3088
      return (_digraph->id(n) << 1) | (n._in ? 0 : 1);
3068 3089
    }
3069 3090
    Node nodeFromId(int ix) const {
3070 3091
      return Node(_digraph->nodeFromId(ix >> 1), (ix & 1) == 0);
3071 3092
    }
3072 3093
    int maxNodeId() const {
3073 3094
      return 2 * _digraph->maxNodeId() + 1;
3074 3095
    }
3075 3096

	
3076 3097
    int id(const Arc& e) const {
3077 3098
      if (e._item.firstState()) {
3078 3099
        return _digraph->id(e._item.first()) << 1;
3079 3100
      } else {
3080 3101
        return (_digraph->id(e._item.second()) << 1) | 1;
3081 3102
      }
3082 3103
    }
3083 3104
    Arc arcFromId(int ix) const {
3084 3105
      if ((ix & 1) == 0) {
3085 3106
        return Arc(_digraph->arcFromId(ix >> 1));
3086 3107
      } else {
3087 3108
        return Arc(_digraph->nodeFromId(ix >> 1));
3088 3109
      }
3089 3110
    }
3090 3111
    int maxArcId() const {
3091 3112
      return std::max(_digraph->maxNodeId() << 1,
3092 3113
                      (_digraph->maxArcId() << 1) | 1);
3093 3114
    }
3094 3115

	
3095 3116
    static bool inNode(const Node& n) {
3096 3117
      return n._in;
3097 3118
    }
3098 3119

	
3099 3120
    static bool outNode(const Node& n) {
3100 3121
      return !n._in;
3101 3122
    }
3102 3123

	
3103 3124
    static bool origArc(const Arc& e) {
3104 3125
      return e._item.firstState();
3105 3126
    }
3106 3127

	
3107 3128
    static bool bindArc(const Arc& e) {
3108 3129
      return e._item.secondState();
3109 3130
    }
3110 3131

	
3111 3132
    static Node inNode(const DigraphNode& n) {
3112 3133
      return Node(n, true);
3113 3134
    }
3114 3135

	
3115 3136
    static Node outNode(const DigraphNode& n) {
3116 3137
      return Node(n, false);
3117 3138
    }
3118 3139

	
3119 3140
    static Arc arc(const DigraphNode& n) {
3120 3141
      return Arc(n);
3121 3142
    }
3122 3143

	
3123 3144
    static Arc arc(const DigraphArc& e) {
3124 3145
      return Arc(e);
3125 3146
    }
3126 3147

	
3127 3148
    typedef True NodeNumTag;
3128 3149
    int nodeNum() const {
3129 3150
      return  2 * countNodes(*_digraph);
3130 3151
    }
3131 3152

	
3132 3153
    typedef True ArcNumTag;
3133 3154
    int arcNum() const {
3134 3155
      return countArcs(*_digraph) + countNodes(*_digraph);
3135 3156
    }
3136 3157

	
3137 3158
    typedef True FindArcTag;
3138 3159
    Arc findArc(const Node& u, const Node& v,
3139 3160
                const Arc& prev = INVALID) const {
3140 3161
      if (inNode(u) && outNode(v)) {
3141 3162
        if (static_cast<const DigraphNode&>(u) ==
3142 3163
            static_cast<const DigraphNode&>(v) && prev == INVALID) {
3143 3164
          return Arc(u);
3144 3165
        }
3145 3166
      }
3146 3167
      else if (outNode(u) && inNode(v)) {
3147 3168
        return Arc(::lemon::findArc(*_digraph, u, v, prev));
3148 3169
      }
3149 3170
      return INVALID;
3150 3171
    }
3151 3172

	
3152 3173
  private:
3153 3174

	
3154 3175
    template <typename V>
3155 3176
    class NodeMapBase
3156 3177
      : public MapTraits<typename Parent::template NodeMap<V> > {
3157 3178
      typedef typename Parent::template NodeMap<V> NodeImpl;
3158 3179
    public:
3159 3180
      typedef Node Key;
3160 3181
      typedef V Value;
3161 3182
      typedef typename MapTraits<NodeImpl>::ReferenceMapTag ReferenceMapTag;
3162 3183
      typedef typename MapTraits<NodeImpl>::ReturnValue ReturnValue;
3163 3184
      typedef typename MapTraits<NodeImpl>::ConstReturnValue ConstReturnValue;
3164 3185
      typedef typename MapTraits<NodeImpl>::ReturnValue Reference;
3165 3186
      typedef typename MapTraits<NodeImpl>::ConstReturnValue ConstReference;
3166 3187

	
3167 3188
      NodeMapBase(const SplitNodesBase<DGR>& adaptor)
3168 3189
        : _in_map(*adaptor._digraph), _out_map(*adaptor._digraph) {}
3169 3190
      NodeMapBase(const SplitNodesBase<DGR>& adaptor, const V& value)
3170 3191
        : _in_map(*adaptor._digraph, value),
3171 3192
          _out_map(*adaptor._digraph, value) {}
3172 3193

	
3173 3194
      void set(const Node& key, const V& val) {
3174 3195
        if (SplitNodesBase<DGR>::inNode(key)) { _in_map.set(key, val); }
3175 3196
        else {_out_map.set(key, val); }
3176 3197
      }
3177 3198

	
3178 3199
      ReturnValue operator[](const Node& key) {
3179 3200
        if (SplitNodesBase<DGR>::inNode(key)) { return _in_map[key]; }
3180 3201
        else { return _out_map[key]; }
3181 3202
      }
3182 3203

	
3183 3204
      ConstReturnValue operator[](const Node& key) const {
3184 3205
        if (Adaptor::inNode(key)) { return _in_map[key]; }
3185 3206
        else { return _out_map[key]; }
3186 3207
      }
3187 3208

	
3188 3209
    private:
3189 3210
      NodeImpl _in_map, _out_map;
3190 3211
    };
3191 3212

	
3192 3213
    template <typename V>
3193 3214
    class ArcMapBase
3194 3215
      : public MapTraits<typename Parent::template ArcMap<V> > {
3195 3216
      typedef typename Parent::template ArcMap<V> ArcImpl;
3196 3217
      typedef typename Parent::template NodeMap<V> NodeImpl;
3197 3218
    public:
3198 3219
      typedef Arc Key;
3199 3220
      typedef V Value;
3200 3221
      typedef typename MapTraits<ArcImpl>::ReferenceMapTag ReferenceMapTag;
3201 3222
      typedef typename MapTraits<ArcImpl>::ReturnValue ReturnValue;
3202 3223
      typedef typename MapTraits<ArcImpl>::ConstReturnValue ConstReturnValue;
3203 3224
      typedef typename MapTraits<ArcImpl>::ReturnValue Reference;
3204 3225
      typedef typename MapTraits<ArcImpl>::ConstReturnValue ConstReference;
3205 3226

	
3206 3227
      ArcMapBase(const SplitNodesBase<DGR>& adaptor)
3207 3228
        : _arc_map(*adaptor._digraph), _node_map(*adaptor._digraph) {}
3208 3229
      ArcMapBase(const SplitNodesBase<DGR>& adaptor, const V& value)
3209 3230
        : _arc_map(*adaptor._digraph, value),
3210 3231
          _node_map(*adaptor._digraph, value) {}
3211 3232

	
3212 3233
      void set(const Arc& key, const V& val) {
3213 3234
        if (SplitNodesBase<DGR>::origArc(key)) {
3214 3235
          _arc_map.set(static_cast<const DigraphArc&>(key), val);
3215 3236
        } else {
3216 3237
          _node_map.set(static_cast<const DigraphNode&>(key), val);
3217 3238
        }
3218 3239
      }
3219 3240

	
3220 3241
      ReturnValue operator[](const Arc& key) {
3221 3242
        if (SplitNodesBase<DGR>::origArc(key)) {
3222 3243
          return _arc_map[static_cast<const DigraphArc&>(key)];
3223 3244
        } else {
3224 3245
          return _node_map[static_cast<const DigraphNode&>(key)];
3225 3246
        }
3226 3247
      }
3227 3248

	
3228 3249
      ConstReturnValue operator[](const Arc& key) const {
3229 3250
        if (SplitNodesBase<DGR>::origArc(key)) {
3230 3251
          return _arc_map[static_cast<const DigraphArc&>(key)];
3231 3252
        } else {
3232 3253
          return _node_map[static_cast<const DigraphNode&>(key)];
3233 3254
        }
3234 3255
      }
3235 3256

	
3236 3257
    private:
3237 3258
      ArcImpl _arc_map;
3238 3259
      NodeImpl _node_map;
3239 3260
    };
3240 3261

	
3241 3262
  public:
3242 3263

	
3243 3264
    template <typename V>
3244 3265
    class NodeMap
3245 3266
      : public SubMapExtender<SplitNodesBase<DGR>, NodeMapBase<V> > {
3246 3267
      typedef SubMapExtender<SplitNodesBase<DGR>, NodeMapBase<V> > Parent;
3247 3268

	
3248 3269
    public:
3249 3270
      typedef V Value;
3250 3271

	
3251 3272
      NodeMap(const SplitNodesBase<DGR>& adaptor)
3252 3273
        : Parent(adaptor) {}
3253 3274

	
3254 3275
      NodeMap(const SplitNodesBase<DGR>& adaptor, const V& value)
3255 3276
        : Parent(adaptor, value) {}
3256 3277

	
3257 3278
    private:
3258 3279
      NodeMap& operator=(const NodeMap& cmap) {
3259 3280
        return operator=<NodeMap>(cmap);
3260 3281
      }
3261 3282

	
3262 3283
      template <typename CMap>
3263 3284
      NodeMap& operator=(const CMap& cmap) {
3264 3285
        Parent::operator=(cmap);
3265 3286
        return *this;
3266 3287
      }
3267 3288
    };
3268 3289

	
3269 3290
    template <typename V>
3270 3291
    class ArcMap
3271 3292
      : public SubMapExtender<SplitNodesBase<DGR>, ArcMapBase<V> > {
3272 3293
      typedef SubMapExtender<SplitNodesBase<DGR>, ArcMapBase<V> > Parent;
3273 3294

	
3274 3295
    public:
3275 3296
      typedef V Value;
3276 3297

	
3277 3298
      ArcMap(const SplitNodesBase<DGR>& adaptor)
3278 3299
        : Parent(adaptor) {}
3279 3300

	
3280 3301
      ArcMap(const SplitNodesBase<DGR>& adaptor, const V& value)
3281 3302
        : Parent(adaptor, value) {}
3282 3303

	
3283 3304
    private:
3284 3305
      ArcMap& operator=(const ArcMap& cmap) {
3285 3306
        return operator=<ArcMap>(cmap);
3286 3307
      }
3287 3308

	
3288 3309
      template <typename CMap>
3289 3310
      ArcMap& operator=(const CMap& cmap) {
3290 3311
        Parent::operator=(cmap);
3291 3312
        return *this;
3292 3313
      }
3293 3314
    };
3294 3315

	
3295 3316
  protected:
3296 3317

	
3297 3318
    SplitNodesBase() : _digraph(0) {}
3298 3319

	
3299 3320
    DGR* _digraph;
3300 3321

	
3301 3322
    void initialize(Digraph& digraph) {
3302 3323
      _digraph = &digraph;
3303 3324
    }
3304 3325

	
3305 3326
  };
3306 3327

	
3307 3328
  /// \ingroup graph_adaptors
3308 3329
  ///
3309 3330
  /// \brief Adaptor class for splitting the nodes of a digraph.
3310 3331
  ///
3311 3332
  /// SplitNodes adaptor can be used for splitting each node into an
3312 3333
  /// \e in-node and an \e out-node in a digraph. Formaly, the adaptor
3313 3334
  /// replaces each node \f$ u \f$ in the digraph with two nodes,
3314 3335
  /// namely node \f$ u_{in} \f$ and node \f$ u_{out} \f$.
3315 3336
  /// If there is a \f$ (v, u) \f$ arc in the original digraph, then the
3316 3337
  /// new target of the arc will be \f$ u_{in} \f$ and similarly the
3317 3338
  /// source of each original \f$ (u, v) \f$ arc will be \f$ u_{out} \f$.
3318 3339
  /// The adaptor adds an additional \e bind \e arc from \f$ u_{in} \f$
3319 3340
  /// to \f$ u_{out} \f$ for each node \f$ u \f$ of the original digraph.
3320 3341
  ///
3321 3342
  /// The aim of this class is running an algorithm with respect to node
3322 3343
  /// costs or capacities if the algorithm considers only arc costs or
3323 3344
  /// capacities directly.
3324 3345
  /// In this case you can use \c SplitNodes adaptor, and set the node
3325 3346
  /// costs/capacities of the original digraph to the \e bind \e arcs
3326 3347
  /// in the adaptor.
3327 3348
  ///
3349
  /// This class provides item counting in the same time as the adapted
3350
  /// digraph structure.
3351
  ///
3328 3352
  /// \tparam DGR The type of the adapted digraph.
3329 3353
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
3330 3354
  /// It is implicitly \c const.
3331 3355
  ///
3332 3356
  /// \note The \c Node type of this adaptor is converible to the \c Node
3333 3357
  /// type of the adapted digraph.
3334 3358
  template <typename DGR>
3335 3359
#ifdef DOXYGEN
3336 3360
  class SplitNodes {
3337 3361
#else
3338 3362
  class SplitNodes
3339 3363
    : public DigraphAdaptorExtender<SplitNodesBase<const DGR> > {
3340 3364
#endif
3341 3365
    typedef DigraphAdaptorExtender<SplitNodesBase<const DGR> > Parent;
3342 3366

	
3343 3367
  public:
3344 3368
    typedef DGR Digraph;
3345 3369

	
3346 3370
    typedef typename DGR::Node DigraphNode;
3347 3371
    typedef typename DGR::Arc DigraphArc;
3348 3372

	
3349 3373
    typedef typename Parent::Node Node;
3350 3374
    typedef typename Parent::Arc Arc;
3351 3375

	
3352 3376
    /// \brief Constructor
3353 3377
    ///
3354 3378
    /// Constructor of the adaptor.
3355 3379
    SplitNodes(const DGR& g) {
3356 3380
      Parent::initialize(g);
3357 3381
    }
3358 3382

	
3359 3383
    /// \brief Returns \c true if the given node is an in-node.
3360 3384
    ///
3361 3385
    /// Returns \c true if the given node is an in-node.
3362 3386
    static bool inNode(const Node& n) {
3363 3387
      return Parent::inNode(n);
3364 3388
    }
3365 3389

	
3366 3390
    /// \brief Returns \c true if the given node is an out-node.
3367 3391
    ///
3368 3392
    /// Returns \c true if the given node is an out-node.
3369 3393
    static bool outNode(const Node& n) {
3370 3394
      return Parent::outNode(n);
3371 3395
    }
3372 3396

	
3373 3397
    /// \brief Returns \c true if the given arc is an original arc.
3374 3398
    ///
3375 3399
    /// Returns \c true if the given arc is one of the arcs in the
3376 3400
    /// original digraph.
3377 3401
    static bool origArc(const Arc& a) {
3378 3402
      return Parent::origArc(a);
3379 3403
    }
3380 3404

	
3381 3405
    /// \brief Returns \c true if the given arc is a bind arc.
3382 3406
    ///
3383 3407
    /// Returns \c true if the given arc is a bind arc, i.e. it connects
3384 3408
    /// an in-node and an out-node.
3385 3409
    static bool bindArc(const Arc& a) {
3386 3410
      return Parent::bindArc(a);
3387 3411
    }
3388 3412

	
3389 3413
    /// \brief Returns the in-node created from the given original node.
3390 3414
    ///
3391 3415
    /// Returns the in-node created from the given original node.
3392 3416
    static Node inNode(const DigraphNode& n) {
3393 3417
      return Parent::inNode(n);
3394 3418
    }
3395 3419

	
3396 3420
    /// \brief Returns the out-node created from the given original node.
3397 3421
    ///
3398 3422
    /// Returns the out-node created from the given original node.
3399 3423
    static Node outNode(const DigraphNode& n) {
3400 3424
      return Parent::outNode(n);
3401 3425
    }
3402 3426

	
3403 3427
    /// \brief Returns the bind arc that corresponds to the given
3404 3428
    /// original node.
3405 3429
    ///
3406 3430
    /// Returns the bind arc in the adaptor that corresponds to the given
3407 3431
    /// original node, i.e. the arc connecting the in-node and out-node
3408 3432
    /// of \c n.
3409 3433
    static Arc arc(const DigraphNode& n) {
3410 3434
      return Parent::arc(n);
3411 3435
    }
3412 3436

	
3413 3437
    /// \brief Returns the arc that corresponds to the given original arc.
3414 3438
    ///
3415 3439
    /// Returns the arc in the adaptor that corresponds to the given
3416 3440
    /// original arc.
3417 3441
    static Arc arc(const DigraphArc& a) {
3418 3442
      return Parent::arc(a);
3419 3443
    }
3420 3444

	
3421 3445
    /// \brief Node map combined from two original node maps
3422 3446
    ///
3423 3447
    /// This map adaptor class adapts two node maps of the original digraph
3424 3448
    /// to get a node map of the split digraph.
3425 3449
    /// Its value type is inherited from the first node map type (\c IN).
3426 3450
    /// \tparam IN The type of the node map for the in-nodes. 
3427 3451
    /// \tparam OUT The type of the node map for the out-nodes.
3428 3452
    template <typename IN, typename OUT>
3429 3453
    class CombinedNodeMap {
3430 3454
    public:
3431 3455

	
3432 3456
      /// The key type of the map
3433 3457
      typedef Node Key;
3434 3458
      /// The value type of the map
3435 3459
      typedef typename IN::Value Value;
3436 3460

	
3437 3461
      typedef typename MapTraits<IN>::ReferenceMapTag ReferenceMapTag;
3438 3462
      typedef typename MapTraits<IN>::ReturnValue ReturnValue;
3439 3463
      typedef typename MapTraits<IN>::ConstReturnValue ConstReturnValue;
3440 3464
      typedef typename MapTraits<IN>::ReturnValue Reference;
3441 3465
      typedef typename MapTraits<IN>::ConstReturnValue ConstReference;
3442 3466

	
3443 3467
      /// Constructor
3444 3468
      CombinedNodeMap(IN& in_map, OUT& out_map)
3445 3469
        : _in_map(in_map), _out_map(out_map) {}
3446 3470

	
3447 3471
      /// Returns the value associated with the given key.
3448 3472
      Value operator[](const Key& key) const {
3449 3473
        if (SplitNodesBase<const DGR>::inNode(key)) {
3450 3474
          return _in_map[key];
3451 3475
        } else {
3452 3476
          return _out_map[key];
3453 3477
        }
3454 3478
      }
3455 3479

	
3456 3480
      /// Returns a reference to the value associated with the given key.
3457 3481
      Value& operator[](const Key& key) {
3458 3482
        if (SplitNodesBase<const DGR>::inNode(key)) {
3459 3483
          return _in_map[key];
3460 3484
        } else {
3461 3485
          return _out_map[key];
3462 3486
        }
3463 3487
      }
3464 3488

	
3465 3489
      /// Sets the value associated with the given key.
3466 3490
      void set(const Key& key, const Value& value) {
3467 3491
        if (SplitNodesBase<const DGR>::inNode(key)) {
3468 3492
          _in_map.set(key, value);
3469 3493
        } else {
3470 3494
          _out_map.set(key, value);
3471 3495
        }
3472 3496
      }
3473 3497

	
3474 3498
    private:
3475 3499

	
3476 3500
      IN& _in_map;
3477 3501
      OUT& _out_map;
3478 3502

	
3479 3503
    };
3480 3504

	
3481 3505

	
3482 3506
    /// \brief Returns a combined node map
3483 3507
    ///
3484 3508
    /// This function just returns a combined node map.
3485 3509
    template <typename IN, typename OUT>
3486 3510
    static CombinedNodeMap<IN, OUT>
3487 3511
    combinedNodeMap(IN& in_map, OUT& out_map) {
3488 3512
      return CombinedNodeMap<IN, OUT>(in_map, out_map);
3489 3513
    }
3490 3514

	
3491 3515
    template <typename IN, typename OUT>
3492 3516
    static CombinedNodeMap<const IN, OUT>
3493 3517
    combinedNodeMap(const IN& in_map, OUT& out_map) {
3494 3518
      return CombinedNodeMap<const IN, OUT>(in_map, out_map);
3495 3519
    }
3496 3520

	
3497 3521
    template <typename IN, typename OUT>
3498 3522
    static CombinedNodeMap<IN, const OUT>
3499 3523
    combinedNodeMap(IN& in_map, const OUT& out_map) {
3500 3524
      return CombinedNodeMap<IN, const OUT>(in_map, out_map);
3501 3525
    }
3502 3526

	
3503 3527
    template <typename IN, typename OUT>
3504 3528
    static CombinedNodeMap<const IN, const OUT>
3505 3529
    combinedNodeMap(const IN& in_map, const OUT& out_map) {
3506 3530
      return CombinedNodeMap<const IN, const OUT>(in_map, out_map);
3507 3531
    }
3508 3532

	
3509 3533
    /// \brief Arc map combined from an arc map and a node map of the
3510 3534
    /// original digraph.
3511 3535
    ///
3512 3536
    /// This map adaptor class adapts an arc map and a node map of the
3513 3537
    /// original digraph to get an arc map of the split digraph.
3514 3538
    /// Its value type is inherited from the original arc map type (\c AM).
3515 3539
    /// \tparam AM The type of the arc map.
3516 3540
    /// \tparam NM the type of the node map.
3517 3541
    template <typename AM, typename NM>
3518 3542
    class CombinedArcMap {
3519 3543
    public:
3520 3544

	
3521 3545
      /// The key type of the map
3522 3546
      typedef Arc Key;
3523 3547
      /// The value type of the map
3524 3548
      typedef typename AM::Value Value;
3525 3549

	
3526 3550
      typedef typename MapTraits<AM>::ReferenceMapTag ReferenceMapTag;
3527 3551
      typedef typename MapTraits<AM>::ReturnValue ReturnValue;
3528 3552
      typedef typename MapTraits<AM>::ConstReturnValue ConstReturnValue;
3529 3553
      typedef typename MapTraits<AM>::ReturnValue Reference;
3530 3554
      typedef typename MapTraits<AM>::ConstReturnValue ConstReference;
3531 3555

	
3532 3556
      /// Constructor
3533 3557
      CombinedArcMap(AM& arc_map, NM& node_map)
3534 3558
        : _arc_map(arc_map), _node_map(node_map) {}
3535 3559

	
3536 3560
      /// Returns the value associated with the given key.
3537 3561
      Value operator[](const Key& arc) const {
3538 3562
        if (SplitNodesBase<const DGR>::origArc(arc)) {
3539 3563
          return _arc_map[arc];
3540 3564
        } else {
3541 3565
          return _node_map[arc];
3542 3566
        }
3543 3567
      }
3544 3568

	
3545 3569
      /// Returns a reference to the value associated with the given key.
3546 3570
      Value& operator[](const Key& arc) {
3547 3571
        if (SplitNodesBase<const DGR>::origArc(arc)) {
3548 3572
          return _arc_map[arc];
3549 3573
        } else {
3550 3574
          return _node_map[arc];
3551 3575
        }
3552 3576
      }
3553 3577

	
3554 3578
      /// Sets the value associated with the given key.
3555 3579
      void set(const Arc& arc, const Value& val) {
3556 3580
        if (SplitNodesBase<const DGR>::origArc(arc)) {
3557 3581
          _arc_map.set(arc, val);
3558 3582
        } else {
3559 3583
          _node_map.set(arc, val);
3560 3584
        }
3561 3585
      }
3562 3586

	
3563 3587
    private:
3564 3588

	
3565 3589
      AM& _arc_map;
3566 3590
      NM& _node_map;
3567 3591

	
3568 3592
    };
3569 3593

	
3570 3594
    /// \brief Returns a combined arc map
3571 3595
    ///
3572 3596
    /// This function just returns a combined arc map.
3573 3597
    template <typename ArcMap, typename NodeMap>
3574 3598
    static CombinedArcMap<ArcMap, NodeMap>
3575 3599
    combinedArcMap(ArcMap& arc_map, NodeMap& node_map) {
3576 3600
      return CombinedArcMap<ArcMap, NodeMap>(arc_map, node_map);
3577 3601
    }
3578 3602

	
3579 3603
    template <typename ArcMap, typename NodeMap>
3580 3604
    static CombinedArcMap<const ArcMap, NodeMap>
3581 3605
    combinedArcMap(const ArcMap& arc_map, NodeMap& node_map) {
3582 3606
      return CombinedArcMap<const ArcMap, NodeMap>(arc_map, node_map);
3583 3607
    }
3584 3608

	
3585 3609
    template <typename ArcMap, typename NodeMap>
3586 3610
    static CombinedArcMap<ArcMap, const NodeMap>
3587 3611
    combinedArcMap(ArcMap& arc_map, const NodeMap& node_map) {
3588 3612
      return CombinedArcMap<ArcMap, const NodeMap>(arc_map, node_map);
3589 3613
    }
3590 3614

	
3591 3615
    template <typename ArcMap, typename NodeMap>
3592 3616
    static CombinedArcMap<const ArcMap, const NodeMap>
3593 3617
    combinedArcMap(const ArcMap& arc_map, const NodeMap& node_map) {
3594 3618
      return CombinedArcMap<const ArcMap, const NodeMap>(arc_map, node_map);
3595 3619
    }
3596 3620

	
3597 3621
  };
3598 3622

	
3599 3623
  /// \brief Returns a (read-only) SplitNodes adaptor
3600 3624
  ///
3601 3625
  /// This function just returns a (read-only) \ref SplitNodes adaptor.
3602 3626
  /// \ingroup graph_adaptors
3603 3627
  /// \relates SplitNodes
3604 3628
  template<typename DGR>
3605 3629
  SplitNodes<DGR>
3606 3630
  splitNodes(const DGR& digraph) {
3607 3631
    return SplitNodes<DGR>(digraph);
3608 3632
  }
3609 3633

	
3610 3634
#undef LEMON_SCOPE_FIX
3611 3635

	
3612 3636
} //namespace lemon
3613 3637

	
3614 3638
#endif //LEMON_ADAPTORS_H
Ignore white space 6 line context
... ...
@@ -320,1430 +320,1422 @@
320 320
    ///Constructor.
321 321
    ///\param g The digraph the algorithm runs on.
322 322
    Bfs(const Digraph &g) :
323 323
      G(&g),
324 324
      _pred(NULL), local_pred(false),
325 325
      _dist(NULL), local_dist(false),
326 326
      _reached(NULL), local_reached(false),
327 327
      _processed(NULL), local_processed(false)
328 328
    { }
329 329

	
330 330
    ///Destructor.
331 331
    ~Bfs()
332 332
    {
333 333
      if(local_pred) delete _pred;
334 334
      if(local_dist) delete _dist;
335 335
      if(local_reached) delete _reached;
336 336
      if(local_processed) delete _processed;
337 337
    }
338 338

	
339 339
    ///Sets the map that stores the predecessor arcs.
340 340

	
341 341
    ///Sets the map that stores the predecessor arcs.
342 342
    ///If you don't use this function before calling \ref run(Node) "run()"
343 343
    ///or \ref init(), an instance will be allocated automatically.
344 344
    ///The destructor deallocates this automatically allocated map,
345 345
    ///of course.
346 346
    ///\return <tt> (*this) </tt>
347 347
    Bfs &predMap(PredMap &m)
348 348
    {
349 349
      if(local_pred) {
350 350
        delete _pred;
351 351
        local_pred=false;
352 352
      }
353 353
      _pred = &m;
354 354
      return *this;
355 355
    }
356 356

	
357 357
    ///Sets the map that indicates which nodes are reached.
358 358

	
359 359
    ///Sets the map that indicates which nodes are reached.
360 360
    ///If you don't use this function before calling \ref run(Node) "run()"
361 361
    ///or \ref init(), an instance will be allocated automatically.
362 362
    ///The destructor deallocates this automatically allocated map,
363 363
    ///of course.
364 364
    ///\return <tt> (*this) </tt>
365 365
    Bfs &reachedMap(ReachedMap &m)
366 366
    {
367 367
      if(local_reached) {
368 368
        delete _reached;
369 369
        local_reached=false;
370 370
      }
371 371
      _reached = &m;
372 372
      return *this;
373 373
    }
374 374

	
375 375
    ///Sets the map that indicates which nodes are processed.
376 376

	
377 377
    ///Sets the map that indicates which nodes are processed.
378 378
    ///If you don't use this function before calling \ref run(Node) "run()"
379 379
    ///or \ref init(), an instance will be allocated automatically.
380 380
    ///The destructor deallocates this automatically allocated map,
381 381
    ///of course.
382 382
    ///\return <tt> (*this) </tt>
383 383
    Bfs &processedMap(ProcessedMap &m)
384 384
    {
385 385
      if(local_processed) {
386 386
        delete _processed;
387 387
        local_processed=false;
388 388
      }
389 389
      _processed = &m;
390 390
      return *this;
391 391
    }
392 392

	
393 393
    ///Sets the map that stores the distances of the nodes.
394 394

	
395 395
    ///Sets the map that stores the distances of the nodes calculated by
396 396
    ///the algorithm.
397 397
    ///If you don't use this function before calling \ref run(Node) "run()"
398 398
    ///or \ref init(), an instance will be allocated automatically.
399 399
    ///The destructor deallocates this automatically allocated map,
400 400
    ///of course.
401 401
    ///\return <tt> (*this) </tt>
402 402
    Bfs &distMap(DistMap &m)
403 403
    {
404 404
      if(local_dist) {
405 405
        delete _dist;
406 406
        local_dist=false;
407 407
      }
408 408
      _dist = &m;
409 409
      return *this;
410 410
    }
411 411

	
412 412
  public:
413 413

	
414 414
    ///\name Execution Control
415 415
    ///The simplest way to execute the BFS algorithm is to use one of the
416 416
    ///member functions called \ref run(Node) "run()".\n
417 417
    ///If you need better control on the execution, you have to call
418 418
    ///\ref init() first, then you can add several source nodes with
419 419
    ///\ref addSource(). Finally the actual path computation can be
420 420
    ///performed with one of the \ref start() functions.
421 421

	
422 422
    ///@{
423 423

	
424 424
    ///\brief Initializes the internal data structures.
425 425
    ///
426 426
    ///Initializes the internal data structures.
427 427
    void init()
428 428
    {
429 429
      create_maps();
430 430
      _queue.resize(countNodes(*G));
431 431
      _queue_head=_queue_tail=0;
432 432
      _curr_dist=1;
433 433
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
434 434
        _pred->set(u,INVALID);
435 435
        _reached->set(u,false);
436 436
        _processed->set(u,false);
437 437
      }
438 438
    }
439 439

	
440 440
    ///Adds a new source node.
441 441

	
442 442
    ///Adds a new source node to the set of nodes to be processed.
443 443
    ///
444 444
    void addSource(Node s)
445 445
    {
446 446
      if(!(*_reached)[s])
447 447
        {
448 448
          _reached->set(s,true);
449 449
          _pred->set(s,INVALID);
450 450
          _dist->set(s,0);
451 451
          _queue[_queue_head++]=s;
452 452
          _queue_next_dist=_queue_head;
453 453
        }
454 454
    }
455 455

	
456 456
    ///Processes the next node.
457 457

	
458 458
    ///Processes the next node.
459 459
    ///
460 460
    ///\return The processed node.
461 461
    ///
462 462
    ///\pre The queue must not be empty.
463 463
    Node processNextNode()
464 464
    {
465 465
      if(_queue_tail==_queue_next_dist) {
466 466
        _curr_dist++;
467 467
        _queue_next_dist=_queue_head;
468 468
      }
469 469
      Node n=_queue[_queue_tail++];
470 470
      _processed->set(n,true);
471 471
      Node m;
472 472
      for(OutArcIt e(*G,n);e!=INVALID;++e)
473 473
        if(!(*_reached)[m=G->target(e)]) {
474 474
          _queue[_queue_head++]=m;
475 475
          _reached->set(m,true);
476 476
          _pred->set(m,e);
477 477
          _dist->set(m,_curr_dist);
478 478
        }
479 479
      return n;
480 480
    }
481 481

	
482 482
    ///Processes the next node.
483 483

	
484 484
    ///Processes the next node and checks if the given target node
485 485
    ///is reached. If the target node is reachable from the processed
486 486
    ///node, then the \c reach parameter will be set to \c true.
487 487
    ///
488 488
    ///\param target The target node.
489 489
    ///\retval reach Indicates if the target node is reached.
490 490
    ///It should be initially \c false.
491 491
    ///
492 492
    ///\return The processed node.
493 493
    ///
494 494
    ///\pre The queue must not be empty.
495 495
    Node processNextNode(Node target, bool& reach)
496 496
    {
497 497
      if(_queue_tail==_queue_next_dist) {
498 498
        _curr_dist++;
499 499
        _queue_next_dist=_queue_head;
500 500
      }
501 501
      Node n=_queue[_queue_tail++];
502 502
      _processed->set(n,true);
503 503
      Node m;
504 504
      for(OutArcIt e(*G,n);e!=INVALID;++e)
505 505
        if(!(*_reached)[m=G->target(e)]) {
506 506
          _queue[_queue_head++]=m;
507 507
          _reached->set(m,true);
508 508
          _pred->set(m,e);
509 509
          _dist->set(m,_curr_dist);
510 510
          reach = reach || (target == m);
511 511
        }
512 512
      return n;
513 513
    }
514 514

	
515 515
    ///Processes the next node.
516 516

	
517 517
    ///Processes the next node and checks if at least one of reached
518 518
    ///nodes has \c true value in the \c nm node map. If one node
519 519
    ///with \c true value is reachable from the processed node, then the
520 520
    ///\c rnode parameter will be set to the first of such nodes.
521 521
    ///
522 522
    ///\param nm A \c bool (or convertible) node map that indicates the
523 523
    ///possible targets.
524 524
    ///\retval rnode The reached target node.
525 525
    ///It should be initially \c INVALID.
526 526
    ///
527 527
    ///\return The processed node.
528 528
    ///
529 529
    ///\pre The queue must not be empty.
530 530
    template<class NM>
531 531
    Node processNextNode(const NM& nm, Node& rnode)
532 532
    {
533 533
      if(_queue_tail==_queue_next_dist) {
534 534
        _curr_dist++;
535 535
        _queue_next_dist=_queue_head;
536 536
      }
537 537
      Node n=_queue[_queue_tail++];
538 538
      _processed->set(n,true);
539 539
      Node m;
540 540
      for(OutArcIt e(*G,n);e!=INVALID;++e)
541 541
        if(!(*_reached)[m=G->target(e)]) {
542 542
          _queue[_queue_head++]=m;
543 543
          _reached->set(m,true);
544 544
          _pred->set(m,e);
545 545
          _dist->set(m,_curr_dist);
546 546
          if (nm[m] && rnode == INVALID) rnode = m;
547 547
        }
548 548
      return n;
549 549
    }
550 550

	
551 551
    ///The next node to be processed.
552 552

	
553 553
    ///Returns the next node to be processed or \c INVALID if the queue
554 554
    ///is empty.
555 555
    Node nextNode() const
556 556
    {
557 557
      return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
558 558
    }
559 559

	
560 560
    ///Returns \c false if there are nodes to be processed.
561 561

	
562 562
    ///Returns \c false if there are nodes to be processed
563 563
    ///in the queue.
564 564
    bool emptyQueue() const { return _queue_tail==_queue_head; }
565 565

	
566 566
    ///Returns the number of the nodes to be processed.
567 567

	
568 568
    ///Returns the number of the nodes to be processed
569 569
    ///in the queue.
570 570
    int queueSize() const { return _queue_head-_queue_tail; }
571 571

	
572 572
    ///Executes the algorithm.
573 573

	
574 574
    ///Executes the algorithm.
575 575
    ///
576 576
    ///This method runs the %BFS algorithm from the root node(s)
577 577
    ///in order to compute the shortest path to each node.
578 578
    ///
579 579
    ///The algorithm computes
580 580
    ///- the shortest path tree (forest),
581 581
    ///- the distance of each node from the root(s).
582 582
    ///
583 583
    ///\pre init() must be called and at least one root node should be
584 584
    ///added with addSource() before using this function.
585 585
    ///
586 586
    ///\note <tt>b.start()</tt> is just a shortcut of the following code.
587 587
    ///\code
588 588
    ///  while ( !b.emptyQueue() ) {
589 589
    ///    b.processNextNode();
590 590
    ///  }
591 591
    ///\endcode
592 592
    void start()
593 593
    {
594 594
      while ( !emptyQueue() ) processNextNode();
595 595
    }
596 596

	
597 597
    ///Executes the algorithm until the given target node is reached.
598 598

	
599 599
    ///Executes the algorithm until the given target node is reached.
600 600
    ///
601 601
    ///This method runs the %BFS algorithm from the root node(s)
602 602
    ///in order to compute the shortest path to \c t.
603 603
    ///
604 604
    ///The algorithm computes
605 605
    ///- the shortest path to \c t,
606 606
    ///- the distance of \c t from the root(s).
607 607
    ///
608 608
    ///\pre init() must be called and at least one root node should be
609 609
    ///added with addSource() before using this function.
610 610
    ///
611 611
    ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
612 612
    ///\code
613 613
    ///  bool reach = false;
614 614
    ///  while ( !b.emptyQueue() && !reach ) {
615 615
    ///    b.processNextNode(t, reach);
616 616
    ///  }
617 617
    ///\endcode
618 618
    void start(Node t)
619 619
    {
620 620
      bool reach = false;
621 621
      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
622 622
    }
623 623

	
624 624
    ///Executes the algorithm until a condition is met.
625 625

	
626 626
    ///Executes the algorithm until a condition is met.
627 627
    ///
628 628
    ///This method runs the %BFS algorithm from the root node(s) in
629 629
    ///order to compute the shortest path to a node \c v with
630 630
    /// <tt>nm[v]</tt> true, if such a node can be found.
631 631
    ///
632 632
    ///\param nm A \c bool (or convertible) node map. The algorithm
633 633
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
634 634
    ///
635 635
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
636 636
    ///\c INVALID if no such node was found.
637 637
    ///
638 638
    ///\pre init() must be called and at least one root node should be
639 639
    ///added with addSource() before using this function.
640 640
    ///
641 641
    ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
642 642
    ///\code
643 643
    ///  Node rnode = INVALID;
644 644
    ///  while ( !b.emptyQueue() && rnode == INVALID ) {
645 645
    ///    b.processNextNode(nm, rnode);
646 646
    ///  }
647 647
    ///  return rnode;
648 648
    ///\endcode
649 649
    template<class NodeBoolMap>
650 650
    Node start(const NodeBoolMap &nm)
651 651
    {
652 652
      Node rnode = INVALID;
653 653
      while ( !emptyQueue() && rnode == INVALID ) {
654 654
        processNextNode(nm, rnode);
655 655
      }
656 656
      return rnode;
657 657
    }
658 658

	
659 659
    ///Runs the algorithm from the given source node.
660 660

	
661 661
    ///This method runs the %BFS algorithm from node \c s
662 662
    ///in order to compute the shortest path to each node.
663 663
    ///
664 664
    ///The algorithm computes
665 665
    ///- the shortest path tree,
666 666
    ///- the distance of each node from the root.
667 667
    ///
668 668
    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
669 669
    ///\code
670 670
    ///  b.init();
671 671
    ///  b.addSource(s);
672 672
    ///  b.start();
673 673
    ///\endcode
674 674
    void run(Node s) {
675 675
      init();
676 676
      addSource(s);
677 677
      start();
678 678
    }
679 679

	
680 680
    ///Finds the shortest path between \c s and \c t.
681 681

	
682 682
    ///This method runs the %BFS algorithm from node \c s
683 683
    ///in order to compute the shortest path to node \c t
684 684
    ///(it stops searching when \c t is processed).
685 685
    ///
686 686
    ///\return \c true if \c t is reachable form \c s.
687 687
    ///
688 688
    ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
689 689
    ///shortcut of the following code.
690 690
    ///\code
691 691
    ///  b.init();
692 692
    ///  b.addSource(s);
693 693
    ///  b.start(t);
694 694
    ///\endcode
695 695
    bool run(Node s,Node t) {
696 696
      init();
697 697
      addSource(s);
698 698
      start(t);
699 699
      return reached(t);
700 700
    }
701 701

	
702 702
    ///Runs the algorithm to visit all nodes in the digraph.
703 703

	
704
    ///This method runs the %BFS algorithm in order to
705
    ///compute the shortest path to each node.
706
    ///
707
    ///The algorithm computes
708
    ///- the shortest path tree (forest),
709
    ///- the distance of each node from the root(s).
704
    ///This method runs the %BFS algorithm in order to visit all nodes
705
    ///in the digraph.
710 706
    ///
711 707
    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
712 708
    ///\code
713 709
    ///  b.init();
714 710
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
715 711
    ///    if (!b.reached(n)) {
716 712
    ///      b.addSource(n);
717 713
    ///      b.start();
718 714
    ///    }
719 715
    ///  }
720 716
    ///\endcode
721 717
    void run() {
722 718
      init();
723 719
      for (NodeIt n(*G); n != INVALID; ++n) {
724 720
        if (!reached(n)) {
725 721
          addSource(n);
726 722
          start();
727 723
        }
728 724
      }
729 725
    }
730 726

	
731 727
    ///@}
732 728

	
733 729
    ///\name Query Functions
734 730
    ///The results of the BFS algorithm can be obtained using these
735 731
    ///functions.\n
736 732
    ///Either \ref run(Node) "run()" or \ref start() should be called
737 733
    ///before using them.
738 734

	
739 735
    ///@{
740 736

	
741 737
    ///The shortest path to the given node.
742 738

	
743 739
    ///Returns the shortest path to the given node from the root(s).
744 740
    ///
745 741
    ///\warning \c t should be reached from the root(s).
746 742
    ///
747 743
    ///\pre Either \ref run(Node) "run()" or \ref init()
748 744
    ///must be called before using this function.
749 745
    Path path(Node t) const { return Path(*G, *_pred, t); }
750 746

	
751 747
    ///The distance of the given node from the root(s).
752 748

	
753 749
    ///Returns the distance of the given node from the root(s).
754 750
    ///
755 751
    ///\warning If node \c v is not reached from the root(s), then
756 752
    ///the return value of this function is undefined.
757 753
    ///
758 754
    ///\pre Either \ref run(Node) "run()" or \ref init()
759 755
    ///must be called before using this function.
760 756
    int dist(Node v) const { return (*_dist)[v]; }
761 757

	
762 758
    ///\brief Returns the 'previous arc' of the shortest path tree for
763 759
    ///the given node.
764 760
    ///
765 761
    ///This function returns the 'previous arc' of the shortest path
766 762
    ///tree for the node \c v, i.e. it returns the last arc of a
767 763
    ///shortest path from a root to \c v. It is \c INVALID if \c v
768 764
    ///is not reached from the root(s) or if \c v is a root.
769 765
    ///
770 766
    ///The shortest path tree used here is equal to the shortest path
771 767
    ///tree used in \ref predNode() and \ref predMap().
772 768
    ///
773 769
    ///\pre Either \ref run(Node) "run()" or \ref init()
774 770
    ///must be called before using this function.
775 771
    Arc predArc(Node v) const { return (*_pred)[v];}
776 772

	
777 773
    ///\brief Returns the 'previous node' of the shortest path tree for
778 774
    ///the given node.
779 775
    ///
780 776
    ///This function returns the 'previous node' of the shortest path
781 777
    ///tree for the node \c v, i.e. it returns the last but one node
782 778
    ///of a shortest path from a root to \c v. It is \c INVALID
783 779
    ///if \c v is not reached from the root(s) or if \c v is a root.
784 780
    ///
785 781
    ///The shortest path tree used here is equal to the shortest path
786 782
    ///tree used in \ref predArc() and \ref predMap().
787 783
    ///
788 784
    ///\pre Either \ref run(Node) "run()" or \ref init()
789 785
    ///must be called before using this function.
790 786
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
791 787
                                  G->source((*_pred)[v]); }
792 788

	
793 789
    ///\brief Returns a const reference to the node map that stores the
794 790
    /// distances of the nodes.
795 791
    ///
796 792
    ///Returns a const reference to the node map that stores the distances
797 793
    ///of the nodes calculated by the algorithm.
798 794
    ///
799 795
    ///\pre Either \ref run(Node) "run()" or \ref init()
800 796
    ///must be called before using this function.
801 797
    const DistMap &distMap() const { return *_dist;}
802 798

	
803 799
    ///\brief Returns a const reference to the node map that stores the
804 800
    ///predecessor arcs.
805 801
    ///
806 802
    ///Returns a const reference to the node map that stores the predecessor
807 803
    ///arcs, which form the shortest path tree (forest).
808 804
    ///
809 805
    ///\pre Either \ref run(Node) "run()" or \ref init()
810 806
    ///must be called before using this function.
811 807
    const PredMap &predMap() const { return *_pred;}
812 808

	
813 809
    ///Checks if the given node is reached from the root(s).
814 810

	
815 811
    ///Returns \c true if \c v is reached from the root(s).
816 812
    ///
817 813
    ///\pre Either \ref run(Node) "run()" or \ref init()
818 814
    ///must be called before using this function.
819 815
    bool reached(Node v) const { return (*_reached)[v]; }
820 816

	
821 817
    ///@}
822 818
  };
823 819

	
824 820
  ///Default traits class of bfs() function.
825 821

	
826 822
  ///Default traits class of bfs() function.
827 823
  ///\tparam GR Digraph type.
828 824
  template<class GR>
829 825
  struct BfsWizardDefaultTraits
830 826
  {
831 827
    ///The type of the digraph the algorithm runs on.
832 828
    typedef GR Digraph;
833 829

	
834 830
    ///\brief The type of the map that stores the predecessor
835 831
    ///arcs of the shortest paths.
836 832
    ///
837 833
    ///The type of the map that stores the predecessor
838 834
    ///arcs of the shortest paths.
839 835
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
840 836
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
841 837
    ///Instantiates a PredMap.
842 838

	
843 839
    ///This function instantiates a PredMap.
844 840
    ///\param g is the digraph, to which we would like to define the
845 841
    ///PredMap.
846 842
    static PredMap *createPredMap(const Digraph &g)
847 843
    {
848 844
      return new PredMap(g);
849 845
    }
850 846

	
851 847
    ///The type of the map that indicates which nodes are processed.
852 848

	
853 849
    ///The type of the map that indicates which nodes are processed.
854 850
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
855 851
    ///By default it is a NullMap.
856 852
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
857 853
    ///Instantiates a ProcessedMap.
858 854

	
859 855
    ///This function instantiates a ProcessedMap.
860 856
    ///\param g is the digraph, to which
861 857
    ///we would like to define the ProcessedMap.
862 858
#ifdef DOXYGEN
863 859
    static ProcessedMap *createProcessedMap(const Digraph &g)
864 860
#else
865 861
    static ProcessedMap *createProcessedMap(const Digraph &)
866 862
#endif
867 863
    {
868 864
      return new ProcessedMap();
869 865
    }
870 866

	
871 867
    ///The type of the map that indicates which nodes are reached.
872 868

	
873 869
    ///The type of the map that indicates which nodes are reached.
874 870
    ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
875 871
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
876 872
    ///Instantiates a ReachedMap.
877 873

	
878 874
    ///This function instantiates a ReachedMap.
879 875
    ///\param g is the digraph, to which
880 876
    ///we would like to define the ReachedMap.
881 877
    static ReachedMap *createReachedMap(const Digraph &g)
882 878
    {
883 879
      return new ReachedMap(g);
884 880
    }
885 881

	
886 882
    ///The type of the map that stores the distances of the nodes.
887 883

	
888 884
    ///The type of the map that stores the distances of the nodes.
889 885
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
890 886
    typedef typename Digraph::template NodeMap<int> DistMap;
891 887
    ///Instantiates a DistMap.
892 888

	
893 889
    ///This function instantiates a DistMap.
894 890
    ///\param g is the digraph, to which we would like to define
895 891
    ///the DistMap
896 892
    static DistMap *createDistMap(const Digraph &g)
897 893
    {
898 894
      return new DistMap(g);
899 895
    }
900 896

	
901 897
    ///The type of the shortest paths.
902 898

	
903 899
    ///The type of the shortest paths.
904 900
    ///It must conform to the \ref concepts::Path "Path" concept.
905 901
    typedef lemon::Path<Digraph> Path;
906 902
  };
907 903

	
908 904
  /// Default traits class used by BfsWizard
909 905

	
910 906
  /// Default traits class used by BfsWizard.
911 907
  /// \tparam GR The type of the digraph.
912 908
  template<class GR>
913 909
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
914 910
  {
915 911

	
916 912
    typedef BfsWizardDefaultTraits<GR> Base;
917 913
  protected:
918 914
    //The type of the nodes in the digraph.
919 915
    typedef typename Base::Digraph::Node Node;
920 916

	
921 917
    //Pointer to the digraph the algorithm runs on.
922 918
    void *_g;
923 919
    //Pointer to the map of reached nodes.
924 920
    void *_reached;
925 921
    //Pointer to the map of processed nodes.
926 922
    void *_processed;
927 923
    //Pointer to the map of predecessors arcs.
928 924
    void *_pred;
929 925
    //Pointer to the map of distances.
930 926
    void *_dist;
931 927
    //Pointer to the shortest path to the target node.
932 928
    void *_path;
933 929
    //Pointer to the distance of the target node.
934 930
    int *_di;
935 931

	
936 932
    public:
937 933
    /// Constructor.
938 934

	
939 935
    /// This constructor does not require parameters, it initiates
940 936
    /// all of the attributes to \c 0.
941 937
    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
942 938
                      _dist(0), _path(0), _di(0) {}
943 939

	
944 940
    /// Constructor.
945 941

	
946 942
    /// This constructor requires one parameter,
947 943
    /// others are initiated to \c 0.
948 944
    /// \param g The digraph the algorithm runs on.
949 945
    BfsWizardBase(const GR &g) :
950 946
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
951 947
      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
952 948

	
953 949
  };
954 950

	
955 951
  /// Auxiliary class for the function-type interface of BFS algorithm.
956 952

	
957 953
  /// This auxiliary class is created to implement the
958 954
  /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
959 955
  /// It does not have own \ref run(Node) "run()" method, it uses the
960 956
  /// functions and features of the plain \ref Bfs.
961 957
  ///
962 958
  /// This class should only be used through the \ref bfs() function,
963 959
  /// which makes it easier to use the algorithm.
964 960
  template<class TR>
965 961
  class BfsWizard : public TR
966 962
  {
967 963
    typedef TR Base;
968 964

	
969 965
    typedef typename TR::Digraph Digraph;
970 966

	
971 967
    typedef typename Digraph::Node Node;
972 968
    typedef typename Digraph::NodeIt NodeIt;
973 969
    typedef typename Digraph::Arc Arc;
974 970
    typedef typename Digraph::OutArcIt OutArcIt;
975 971

	
976 972
    typedef typename TR::PredMap PredMap;
977 973
    typedef typename TR::DistMap DistMap;
978 974
    typedef typename TR::ReachedMap ReachedMap;
979 975
    typedef typename TR::ProcessedMap ProcessedMap;
980 976
    typedef typename TR::Path Path;
981 977

	
982 978
  public:
983 979

	
984 980
    /// Constructor.
985 981
    BfsWizard() : TR() {}
986 982

	
987 983
    /// Constructor that requires parameters.
988 984

	
989 985
    /// Constructor that requires parameters.
990 986
    /// These parameters will be the default values for the traits class.
991 987
    /// \param g The digraph the algorithm runs on.
992 988
    BfsWizard(const Digraph &g) :
993 989
      TR(g) {}
994 990

	
995 991
    ///Copy constructor
996 992
    BfsWizard(const TR &b) : TR(b) {}
997 993

	
998 994
    ~BfsWizard() {}
999 995

	
1000 996
    ///Runs BFS algorithm from the given source node.
1001 997

	
1002 998
    ///This method runs BFS algorithm from node \c s
1003 999
    ///in order to compute the shortest path to each node.
1004 1000
    void run(Node s)
1005 1001
    {
1006 1002
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1007 1003
      if (Base::_pred)
1008 1004
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1009 1005
      if (Base::_dist)
1010 1006
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1011 1007
      if (Base::_reached)
1012 1008
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1013 1009
      if (Base::_processed)
1014 1010
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1015 1011
      if (s!=INVALID)
1016 1012
        alg.run(s);
1017 1013
      else
1018 1014
        alg.run();
1019 1015
    }
1020 1016

	
1021 1017
    ///Finds the shortest path between \c s and \c t.
1022 1018

	
1023 1019
    ///This method runs BFS algorithm from node \c s
1024 1020
    ///in order to compute the shortest path to node \c t
1025 1021
    ///(it stops searching when \c t is processed).
1026 1022
    ///
1027 1023
    ///\return \c true if \c t is reachable form \c s.
1028 1024
    bool run(Node s, Node t)
1029 1025
    {
1030 1026
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1031 1027
      if (Base::_pred)
1032 1028
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1033 1029
      if (Base::_dist)
1034 1030
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1035 1031
      if (Base::_reached)
1036 1032
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1037 1033
      if (Base::_processed)
1038 1034
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1039 1035
      alg.run(s,t);
1040 1036
      if (Base::_path)
1041 1037
        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1042 1038
      if (Base::_di)
1043 1039
        *Base::_di = alg.dist(t);
1044 1040
      return alg.reached(t);
1045 1041
    }
1046 1042

	
1047 1043
    ///Runs BFS algorithm to visit all nodes in the digraph.
1048 1044

	
1049
    ///This method runs BFS algorithm in order to compute
1050
    ///the shortest path to each node.
1045
    ///This method runs BFS algorithm in order to visit all nodes
1046
    ///in the digraph.
1051 1047
    void run()
1052 1048
    {
1053 1049
      run(INVALID);
1054 1050
    }
1055 1051

	
1056 1052
    template<class T>
1057 1053
    struct SetPredMapBase : public Base {
1058 1054
      typedef T PredMap;
1059 1055
      static PredMap *createPredMap(const Digraph &) { return 0; };
1060 1056
      SetPredMapBase(const TR &b) : TR(b) {}
1061 1057
    };
1062 1058

	
1063 1059
    ///\brief \ref named-templ-param "Named parameter" for setting
1064 1060
    ///the predecessor map.
1065 1061
    ///
1066 1062
    ///\ref named-templ-param "Named parameter" function for setting
1067 1063
    ///the map that stores the predecessor arcs of the nodes.
1068 1064
    template<class T>
1069 1065
    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1070 1066
    {
1071 1067
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1072 1068
      return BfsWizard<SetPredMapBase<T> >(*this);
1073 1069
    }
1074 1070

	
1075 1071
    template<class T>
1076 1072
    struct SetReachedMapBase : public Base {
1077 1073
      typedef T ReachedMap;
1078 1074
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1079 1075
      SetReachedMapBase(const TR &b) : TR(b) {}
1080 1076
    };
1081 1077

	
1082 1078
    ///\brief \ref named-templ-param "Named parameter" for setting
1083 1079
    ///the reached map.
1084 1080
    ///
1085 1081
    ///\ref named-templ-param "Named parameter" function for setting
1086 1082
    ///the map that indicates which nodes are reached.
1087 1083
    template<class T>
1088 1084
    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1089 1085
    {
1090 1086
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1091 1087
      return BfsWizard<SetReachedMapBase<T> >(*this);
1092 1088
    }
1093 1089

	
1094 1090
    template<class T>
1095 1091
    struct SetDistMapBase : public Base {
1096 1092
      typedef T DistMap;
1097 1093
      static DistMap *createDistMap(const Digraph &) { return 0; };
1098 1094
      SetDistMapBase(const TR &b) : TR(b) {}
1099 1095
    };
1100 1096

	
1101 1097
    ///\brief \ref named-templ-param "Named parameter" for setting
1102 1098
    ///the distance map.
1103 1099
    ///
1104 1100
    ///\ref named-templ-param "Named parameter" function for setting
1105 1101
    ///the map that stores the distances of the nodes calculated
1106 1102
    ///by the algorithm.
1107 1103
    template<class T>
1108 1104
    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1109 1105
    {
1110 1106
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1111 1107
      return BfsWizard<SetDistMapBase<T> >(*this);
1112 1108
    }
1113 1109

	
1114 1110
    template<class T>
1115 1111
    struct SetProcessedMapBase : public Base {
1116 1112
      typedef T ProcessedMap;
1117 1113
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1118 1114
      SetProcessedMapBase(const TR &b) : TR(b) {}
1119 1115
    };
1120 1116

	
1121 1117
    ///\brief \ref named-func-param "Named parameter" for setting
1122 1118
    ///the processed map.
1123 1119
    ///
1124 1120
    ///\ref named-templ-param "Named parameter" function for setting
1125 1121
    ///the map that indicates which nodes are processed.
1126 1122
    template<class T>
1127 1123
    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1128 1124
    {
1129 1125
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1130 1126
      return BfsWizard<SetProcessedMapBase<T> >(*this);
1131 1127
    }
1132 1128

	
1133 1129
    template<class T>
1134 1130
    struct SetPathBase : public Base {
1135 1131
      typedef T Path;
1136 1132
      SetPathBase(const TR &b) : TR(b) {}
1137 1133
    };
1138 1134
    ///\brief \ref named-func-param "Named parameter"
1139 1135
    ///for getting the shortest path to the target node.
1140 1136
    ///
1141 1137
    ///\ref named-func-param "Named parameter"
1142 1138
    ///for getting the shortest path to the target node.
1143 1139
    template<class T>
1144 1140
    BfsWizard<SetPathBase<T> > path(const T &t)
1145 1141
    {
1146 1142
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1147 1143
      return BfsWizard<SetPathBase<T> >(*this);
1148 1144
    }
1149 1145

	
1150 1146
    ///\brief \ref named-func-param "Named parameter"
1151 1147
    ///for getting the distance of the target node.
1152 1148
    ///
1153 1149
    ///\ref named-func-param "Named parameter"
1154 1150
    ///for getting the distance of the target node.
1155 1151
    BfsWizard dist(const int &d)
1156 1152
    {
1157 1153
      Base::_di=const_cast<int*>(&d);
1158 1154
      return *this;
1159 1155
    }
1160 1156

	
1161 1157
  };
1162 1158

	
1163 1159
  ///Function-type interface for BFS algorithm.
1164 1160

	
1165 1161
  /// \ingroup search
1166 1162
  ///Function-type interface for BFS algorithm.
1167 1163
  ///
1168 1164
  ///This function also has several \ref named-func-param "named parameters",
1169 1165
  ///they are declared as the members of class \ref BfsWizard.
1170 1166
  ///The following examples show how to use these parameters.
1171 1167
  ///\code
1172 1168
  ///  // Compute shortest path from node s to each node
1173 1169
  ///  bfs(g).predMap(preds).distMap(dists).run(s);
1174 1170
  ///
1175 1171
  ///  // Compute shortest path from s to t
1176 1172
  ///  bool reached = bfs(g).path(p).dist(d).run(s,t);
1177 1173
  ///\endcode
1178 1174
  ///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
1179 1175
  ///to the end of the parameter list.
1180 1176
  ///\sa BfsWizard
1181 1177
  ///\sa Bfs
1182 1178
  template<class GR>
1183 1179
  BfsWizard<BfsWizardBase<GR> >
1184 1180
  bfs(const GR &digraph)
1185 1181
  {
1186 1182
    return BfsWizard<BfsWizardBase<GR> >(digraph);
1187 1183
  }
1188 1184

	
1189 1185
#ifdef DOXYGEN
1190 1186
  /// \brief Visitor class for BFS.
1191 1187
  ///
1192 1188
  /// This class defines the interface of the BfsVisit events, and
1193 1189
  /// it could be the base of a real visitor class.
1194 1190
  template <typename GR>
1195 1191
  struct BfsVisitor {
1196 1192
    typedef GR Digraph;
1197 1193
    typedef typename Digraph::Arc Arc;
1198 1194
    typedef typename Digraph::Node Node;
1199 1195
    /// \brief Called for the source node(s) of the BFS.
1200 1196
    ///
1201 1197
    /// This function is called for the source node(s) of the BFS.
1202 1198
    void start(const Node& node) {}
1203 1199
    /// \brief Called when a node is reached first time.
1204 1200
    ///
1205 1201
    /// This function is called when a node is reached first time.
1206 1202
    void reach(const Node& node) {}
1207 1203
    /// \brief Called when a node is processed.
1208 1204
    ///
1209 1205
    /// This function is called when a node is processed.
1210 1206
    void process(const Node& node) {}
1211 1207
    /// \brief Called when an arc reaches a new node.
1212 1208
    ///
1213 1209
    /// This function is called when the BFS finds an arc whose target node
1214 1210
    /// is not reached yet.
1215 1211
    void discover(const Arc& arc) {}
1216 1212
    /// \brief Called when an arc is examined but its target node is
1217 1213
    /// already discovered.
1218 1214
    ///
1219 1215
    /// This function is called when an arc is examined but its target node is
1220 1216
    /// already discovered.
1221 1217
    void examine(const Arc& arc) {}
1222 1218
  };
1223 1219
#else
1224 1220
  template <typename GR>
1225 1221
  struct BfsVisitor {
1226 1222
    typedef GR Digraph;
1227 1223
    typedef typename Digraph::Arc Arc;
1228 1224
    typedef typename Digraph::Node Node;
1229 1225
    void start(const Node&) {}
1230 1226
    void reach(const Node&) {}
1231 1227
    void process(const Node&) {}
1232 1228
    void discover(const Arc&) {}
1233 1229
    void examine(const Arc&) {}
1234 1230

	
1235 1231
    template <typename _Visitor>
1236 1232
    struct Constraints {
1237 1233
      void constraints() {
1238 1234
        Arc arc;
1239 1235
        Node node;
1240 1236
        visitor.start(node);
1241 1237
        visitor.reach(node);
1242 1238
        visitor.process(node);
1243 1239
        visitor.discover(arc);
1244 1240
        visitor.examine(arc);
1245 1241
      }
1246 1242
      _Visitor& visitor;
1247 1243
    };
1248 1244
  };
1249 1245
#endif
1250 1246

	
1251 1247
  /// \brief Default traits class of BfsVisit class.
1252 1248
  ///
1253 1249
  /// Default traits class of BfsVisit class.
1254 1250
  /// \tparam GR The type of the digraph the algorithm runs on.
1255 1251
  template<class GR>
1256 1252
  struct BfsVisitDefaultTraits {
1257 1253

	
1258 1254
    /// \brief The type of the digraph the algorithm runs on.
1259 1255
    typedef GR Digraph;
1260 1256

	
1261 1257
    /// \brief The type of the map that indicates which nodes are reached.
1262 1258
    ///
1263 1259
    /// The type of the map that indicates which nodes are reached.
1264 1260
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1265 1261
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1266 1262

	
1267 1263
    /// \brief Instantiates a ReachedMap.
1268 1264
    ///
1269 1265
    /// This function instantiates a ReachedMap.
1270 1266
    /// \param digraph is the digraph, to which
1271 1267
    /// we would like to define the ReachedMap.
1272 1268
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1273 1269
      return new ReachedMap(digraph);
1274 1270
    }
1275 1271

	
1276 1272
  };
1277 1273

	
1278 1274
  /// \ingroup search
1279 1275
  ///
1280 1276
  /// \brief BFS algorithm class with visitor interface.
1281 1277
  ///
1282 1278
  /// This class provides an efficient implementation of the BFS algorithm
1283 1279
  /// with visitor interface.
1284 1280
  ///
1285 1281
  /// The BfsVisit class provides an alternative interface to the Bfs
1286 1282
  /// class. It works with callback mechanism, the BfsVisit object calls
1287 1283
  /// the member functions of the \c Visitor class on every BFS event.
1288 1284
  ///
1289 1285
  /// This interface of the BFS algorithm should be used in special cases
1290 1286
  /// when extra actions have to be performed in connection with certain
1291 1287
  /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1292 1288
  /// instead.
1293 1289
  ///
1294 1290
  /// \tparam GR The type of the digraph the algorithm runs on.
1295 1291
  /// The default type is \ref ListDigraph.
1296 1292
  /// The value of GR is not used directly by \ref BfsVisit,
1297 1293
  /// it is only passed to \ref BfsVisitDefaultTraits.
1298 1294
  /// \tparam VS The Visitor type that is used by the algorithm.
1299 1295
  /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
1300 1296
  /// does not observe the BFS events. If you want to observe the BFS
1301 1297
  /// events, you should implement your own visitor class.
1302 1298
  /// \tparam TR Traits class to set various data types used by the
1303 1299
  /// algorithm. The default traits class is
1304 1300
  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<GR>".
1305 1301
  /// See \ref BfsVisitDefaultTraits for the documentation of
1306 1302
  /// a BFS visit traits class.
1307 1303
#ifdef DOXYGEN
1308 1304
  template <typename GR, typename VS, typename TR>
1309 1305
#else
1310 1306
  template <typename GR = ListDigraph,
1311 1307
            typename VS = BfsVisitor<GR>,
1312 1308
            typename TR = BfsVisitDefaultTraits<GR> >
1313 1309
#endif
1314 1310
  class BfsVisit {
1315 1311
  public:
1316 1312

	
1317 1313
    ///The traits class.
1318 1314
    typedef TR Traits;
1319 1315

	
1320 1316
    ///The type of the digraph the algorithm runs on.
1321 1317
    typedef typename Traits::Digraph Digraph;
1322 1318

	
1323 1319
    ///The visitor type used by the algorithm.
1324 1320
    typedef VS Visitor;
1325 1321

	
1326 1322
    ///The type of the map that indicates which nodes are reached.
1327 1323
    typedef typename Traits::ReachedMap ReachedMap;
1328 1324

	
1329 1325
  private:
1330 1326

	
1331 1327
    typedef typename Digraph::Node Node;
1332 1328
    typedef typename Digraph::NodeIt NodeIt;
1333 1329
    typedef typename Digraph::Arc Arc;
1334 1330
    typedef typename Digraph::OutArcIt OutArcIt;
1335 1331

	
1336 1332
    //Pointer to the underlying digraph.
1337 1333
    const Digraph *_digraph;
1338 1334
    //Pointer to the visitor object.
1339 1335
    Visitor *_visitor;
1340 1336
    //Pointer to the map of reached status of the nodes.
1341 1337
    ReachedMap *_reached;
1342 1338
    //Indicates if _reached is locally allocated (true) or not.
1343 1339
    bool local_reached;
1344 1340

	
1345 1341
    std::vector<typename Digraph::Node> _list;
1346 1342
    int _list_front, _list_back;
1347 1343

	
1348 1344
    //Creates the maps if necessary.
1349 1345
    void create_maps() {
1350 1346
      if(!_reached) {
1351 1347
        local_reached = true;
1352 1348
        _reached = Traits::createReachedMap(*_digraph);
1353 1349
      }
1354 1350
    }
1355 1351

	
1356 1352
  protected:
1357 1353

	
1358 1354
    BfsVisit() {}
1359 1355

	
1360 1356
  public:
1361 1357

	
1362 1358
    typedef BfsVisit Create;
1363 1359

	
1364 1360
    /// \name Named Template Parameters
1365 1361

	
1366 1362
    ///@{
1367 1363
    template <class T>
1368 1364
    struct SetReachedMapTraits : public Traits {
1369 1365
      typedef T ReachedMap;
1370 1366
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1371 1367
        LEMON_ASSERT(false, "ReachedMap is not initialized");
1372 1368
        return 0; // ignore warnings
1373 1369
      }
1374 1370
    };
1375 1371
    /// \brief \ref named-templ-param "Named parameter" for setting
1376 1372
    /// ReachedMap type.
1377 1373
    ///
1378 1374
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1379 1375
    template <class T>
1380 1376
    struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1381 1377
                                            SetReachedMapTraits<T> > {
1382 1378
      typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1383 1379
    };
1384 1380
    ///@}
1385 1381

	
1386 1382
  public:
1387 1383

	
1388 1384
    /// \brief Constructor.
1389 1385
    ///
1390 1386
    /// Constructor.
1391 1387
    ///
1392 1388
    /// \param digraph The digraph the algorithm runs on.
1393 1389
    /// \param visitor The visitor object of the algorithm.
1394 1390
    BfsVisit(const Digraph& digraph, Visitor& visitor)
1395 1391
      : _digraph(&digraph), _visitor(&visitor),
1396 1392
        _reached(0), local_reached(false) {}
1397 1393

	
1398 1394
    /// \brief Destructor.
1399 1395
    ~BfsVisit() {
1400 1396
      if(local_reached) delete _reached;
1401 1397
    }
1402 1398

	
1403 1399
    /// \brief Sets the map that indicates which nodes are reached.
1404 1400
    ///
1405 1401
    /// Sets the map that indicates which nodes are reached.
1406 1402
    /// If you don't use this function before calling \ref run(Node) "run()"
1407 1403
    /// or \ref init(), an instance will be allocated automatically.
1408 1404
    /// The destructor deallocates this automatically allocated map,
1409 1405
    /// of course.
1410 1406
    /// \return <tt> (*this) </tt>
1411 1407
    BfsVisit &reachedMap(ReachedMap &m) {
1412 1408
      if(local_reached) {
1413 1409
        delete _reached;
1414 1410
        local_reached = false;
1415 1411
      }
1416 1412
      _reached = &m;
1417 1413
      return *this;
1418 1414
    }
1419 1415

	
1420 1416
  public:
1421 1417

	
1422 1418
    /// \name Execution Control
1423 1419
    /// The simplest way to execute the BFS algorithm is to use one of the
1424 1420
    /// member functions called \ref run(Node) "run()".\n
1425 1421
    /// If you need better control on the execution, you have to call
1426 1422
    /// \ref init() first, then you can add several source nodes with
1427 1423
    /// \ref addSource(). Finally the actual path computation can be
1428 1424
    /// performed with one of the \ref start() functions.
1429 1425

	
1430 1426
    /// @{
1431 1427

	
1432 1428
    /// \brief Initializes the internal data structures.
1433 1429
    ///
1434 1430
    /// Initializes the internal data structures.
1435 1431
    void init() {
1436 1432
      create_maps();
1437 1433
      _list.resize(countNodes(*_digraph));
1438 1434
      _list_front = _list_back = -1;
1439 1435
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1440 1436
        _reached->set(u, false);
1441 1437
      }
1442 1438
    }
1443 1439

	
1444 1440
    /// \brief Adds a new source node.
1445 1441
    ///
1446 1442
    /// Adds a new source node to the set of nodes to be processed.
1447 1443
    void addSource(Node s) {
1448 1444
      if(!(*_reached)[s]) {
1449 1445
          _reached->set(s,true);
1450 1446
          _visitor->start(s);
1451 1447
          _visitor->reach(s);
1452 1448
          _list[++_list_back] = s;
1453 1449
        }
1454 1450
    }
1455 1451

	
1456 1452
    /// \brief Processes the next node.
1457 1453
    ///
1458 1454
    /// Processes the next node.
1459 1455
    ///
1460 1456
    /// \return The processed node.
1461 1457
    ///
1462 1458
    /// \pre The queue must not be empty.
1463 1459
    Node processNextNode() {
1464 1460
      Node n = _list[++_list_front];
1465 1461
      _visitor->process(n);
1466 1462
      Arc e;
1467 1463
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1468 1464
        Node m = _digraph->target(e);
1469 1465
        if (!(*_reached)[m]) {
1470 1466
          _visitor->discover(e);
1471 1467
          _visitor->reach(m);
1472 1468
          _reached->set(m, true);
1473 1469
          _list[++_list_back] = m;
1474 1470
        } else {
1475 1471
          _visitor->examine(e);
1476 1472
        }
1477 1473
      }
1478 1474
      return n;
1479 1475
    }
1480 1476

	
1481 1477
    /// \brief Processes the next node.
1482 1478
    ///
1483 1479
    /// Processes the next node and checks if the given target node
1484 1480
    /// is reached. If the target node is reachable from the processed
1485 1481
    /// node, then the \c reach parameter will be set to \c true.
1486 1482
    ///
1487 1483
    /// \param target The target node.
1488 1484
    /// \retval reach Indicates if the target node is reached.
1489 1485
    /// It should be initially \c false.
1490 1486
    ///
1491 1487
    /// \return The processed node.
1492 1488
    ///
1493 1489
    /// \pre The queue must not be empty.
1494 1490
    Node processNextNode(Node target, bool& reach) {
1495 1491
      Node n = _list[++_list_front];
1496 1492
      _visitor->process(n);
1497 1493
      Arc e;
1498 1494
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1499 1495
        Node m = _digraph->target(e);
1500 1496
        if (!(*_reached)[m]) {
1501 1497
          _visitor->discover(e);
1502 1498
          _visitor->reach(m);
1503 1499
          _reached->set(m, true);
1504 1500
          _list[++_list_back] = m;
1505 1501
          reach = reach || (target == m);
1506 1502
        } else {
1507 1503
          _visitor->examine(e);
1508 1504
        }
1509 1505
      }
1510 1506
      return n;
1511 1507
    }
1512 1508

	
1513 1509
    /// \brief Processes the next node.
1514 1510
    ///
1515 1511
    /// Processes the next node and checks if at least one of reached
1516 1512
    /// nodes has \c true value in the \c nm node map. If one node
1517 1513
    /// with \c true value is reachable from the processed node, then the
1518 1514
    /// \c rnode parameter will be set to the first of such nodes.
1519 1515
    ///
1520 1516
    /// \param nm A \c bool (or convertible) node map that indicates the
1521 1517
    /// possible targets.
1522 1518
    /// \retval rnode The reached target node.
1523 1519
    /// It should be initially \c INVALID.
1524 1520
    ///
1525 1521
    /// \return The processed node.
1526 1522
    ///
1527 1523
    /// \pre The queue must not be empty.
1528 1524
    template <typename NM>
1529 1525
    Node processNextNode(const NM& nm, Node& rnode) {
1530 1526
      Node n = _list[++_list_front];
1531 1527
      _visitor->process(n);
1532 1528
      Arc e;
1533 1529
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1534 1530
        Node m = _digraph->target(e);
1535 1531
        if (!(*_reached)[m]) {
1536 1532
          _visitor->discover(e);
1537 1533
          _visitor->reach(m);
1538 1534
          _reached->set(m, true);
1539 1535
          _list[++_list_back] = m;
1540 1536
          if (nm[m] && rnode == INVALID) rnode = m;
1541 1537
        } else {
1542 1538
          _visitor->examine(e);
1543 1539
        }
1544 1540
      }
1545 1541
      return n;
1546 1542
    }
1547 1543

	
1548 1544
    /// \brief The next node to be processed.
1549 1545
    ///
1550 1546
    /// Returns the next node to be processed or \c INVALID if the queue
1551 1547
    /// is empty.
1552 1548
    Node nextNode() const {
1553 1549
      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1554 1550
    }
1555 1551

	
1556 1552
    /// \brief Returns \c false if there are nodes
1557 1553
    /// to be processed.
1558 1554
    ///
1559 1555
    /// Returns \c false if there are nodes
1560 1556
    /// to be processed in the queue.
1561 1557
    bool emptyQueue() const { return _list_front == _list_back; }
1562 1558

	
1563 1559
    /// \brief Returns the number of the nodes to be processed.
1564 1560
    ///
1565 1561
    /// Returns the number of the nodes to be processed in the queue.
1566 1562
    int queueSize() const { return _list_back - _list_front; }
1567 1563

	
1568 1564
    /// \brief Executes the algorithm.
1569 1565
    ///
1570 1566
    /// Executes the algorithm.
1571 1567
    ///
1572 1568
    /// This method runs the %BFS algorithm from the root node(s)
1573 1569
    /// in order to compute the shortest path to each node.
1574 1570
    ///
1575 1571
    /// The algorithm computes
1576 1572
    /// - the shortest path tree (forest),
1577 1573
    /// - the distance of each node from the root(s).
1578 1574
    ///
1579 1575
    /// \pre init() must be called and at least one root node should be added
1580 1576
    /// with addSource() before using this function.
1581 1577
    ///
1582 1578
    /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1583 1579
    /// \code
1584 1580
    ///   while ( !b.emptyQueue() ) {
1585 1581
    ///     b.processNextNode();
1586 1582
    ///   }
1587 1583
    /// \endcode
1588 1584
    void start() {
1589 1585
      while ( !emptyQueue() ) processNextNode();
1590 1586
    }
1591 1587

	
1592 1588
    /// \brief Executes the algorithm until the given target node is reached.
1593 1589
    ///
1594 1590
    /// Executes the algorithm until the given target node is reached.
1595 1591
    ///
1596 1592
    /// This method runs the %BFS algorithm from the root node(s)
1597 1593
    /// in order to compute the shortest path to \c t.
1598 1594
    ///
1599 1595
    /// The algorithm computes
1600 1596
    /// - the shortest path to \c t,
1601 1597
    /// - the distance of \c t from the root(s).
1602 1598
    ///
1603 1599
    /// \pre init() must be called and at least one root node should be
1604 1600
    /// added with addSource() before using this function.
1605 1601
    ///
1606 1602
    /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1607 1603
    /// \code
1608 1604
    ///   bool reach = false;
1609 1605
    ///   while ( !b.emptyQueue() && !reach ) {
1610 1606
    ///     b.processNextNode(t, reach);
1611 1607
    ///   }
1612 1608
    /// \endcode
1613 1609
    void start(Node t) {
1614 1610
      bool reach = false;
1615 1611
      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1616 1612
    }
1617 1613

	
1618 1614
    /// \brief Executes the algorithm until a condition is met.
1619 1615
    ///
1620 1616
    /// Executes the algorithm until a condition is met.
1621 1617
    ///
1622 1618
    /// This method runs the %BFS algorithm from the root node(s) in
1623 1619
    /// order to compute the shortest path to a node \c v with
1624 1620
    /// <tt>nm[v]</tt> true, if such a node can be found.
1625 1621
    ///
1626 1622
    /// \param nm must be a bool (or convertible) node map. The
1627 1623
    /// algorithm will stop when it reaches a node \c v with
1628 1624
    /// <tt>nm[v]</tt> true.
1629 1625
    ///
1630 1626
    /// \return The reached node \c v with <tt>nm[v]</tt> true or
1631 1627
    /// \c INVALID if no such node was found.
1632 1628
    ///
1633 1629
    /// \pre init() must be called and at least one root node should be
1634 1630
    /// added with addSource() before using this function.
1635 1631
    ///
1636 1632
    /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1637 1633
    /// \code
1638 1634
    ///   Node rnode = INVALID;
1639 1635
    ///   while ( !b.emptyQueue() && rnode == INVALID ) {
1640 1636
    ///     b.processNextNode(nm, rnode);
1641 1637
    ///   }
1642 1638
    ///   return rnode;
1643 1639
    /// \endcode
1644 1640
    template <typename NM>
1645 1641
    Node start(const NM &nm) {
1646 1642
      Node rnode = INVALID;
1647 1643
      while ( !emptyQueue() && rnode == INVALID ) {
1648 1644
        processNextNode(nm, rnode);
1649 1645
      }
1650 1646
      return rnode;
1651 1647
    }
1652 1648

	
1653 1649
    /// \brief Runs the algorithm from the given source node.
1654 1650
    ///
1655 1651
    /// This method runs the %BFS algorithm from node \c s
1656 1652
    /// in order to compute the shortest path to each node.
1657 1653
    ///
1658 1654
    /// The algorithm computes
1659 1655
    /// - the shortest path tree,
1660 1656
    /// - the distance of each node from the root.
1661 1657
    ///
1662 1658
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1663 1659
    ///\code
1664 1660
    ///   b.init();
1665 1661
    ///   b.addSource(s);
1666 1662
    ///   b.start();
1667 1663
    ///\endcode
1668 1664
    void run(Node s) {
1669 1665
      init();
1670 1666
      addSource(s);
1671 1667
      start();
1672 1668
    }
1673 1669

	
1674 1670
    /// \brief Finds the shortest path between \c s and \c t.
1675 1671
    ///
1676 1672
    /// This method runs the %BFS algorithm from node \c s
1677 1673
    /// in order to compute the shortest path to node \c t
1678 1674
    /// (it stops searching when \c t is processed).
1679 1675
    ///
1680 1676
    /// \return \c true if \c t is reachable form \c s.
1681 1677
    ///
1682 1678
    /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1683 1679
    /// shortcut of the following code.
1684 1680
    ///\code
1685 1681
    ///   b.init();
1686 1682
    ///   b.addSource(s);
1687 1683
    ///   b.start(t);
1688 1684
    ///\endcode
1689 1685
    bool run(Node s,Node t) {
1690 1686
      init();
1691 1687
      addSource(s);
1692 1688
      start(t);
1693 1689
      return reached(t);
1694 1690
    }
1695 1691

	
1696 1692
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1697 1693
    ///
1698
    /// This method runs the %BFS algorithm in order to
1699
    /// compute the shortest path to each node.
1700
    ///
1701
    /// The algorithm computes
1702
    /// - the shortest path tree (forest),
1703
    /// - the distance of each node from the root(s).
1694
    /// This method runs the %BFS algorithm in order to visit all nodes
1695
    /// in the digraph.
1704 1696
    ///
1705 1697
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1706 1698
    ///\code
1707 1699
    ///  b.init();
1708 1700
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
1709 1701
    ///    if (!b.reached(n)) {
1710 1702
    ///      b.addSource(n);
1711 1703
    ///      b.start();
1712 1704
    ///    }
1713 1705
    ///  }
1714 1706
    ///\endcode
1715 1707
    void run() {
1716 1708
      init();
1717 1709
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1718 1710
        if (!reached(it)) {
1719 1711
          addSource(it);
1720 1712
          start();
1721 1713
        }
1722 1714
      }
1723 1715
    }
1724 1716

	
1725 1717
    ///@}
1726 1718

	
1727 1719
    /// \name Query Functions
1728 1720
    /// The results of the BFS algorithm can be obtained using these
1729 1721
    /// functions.\n
1730 1722
    /// Either \ref run(Node) "run()" or \ref start() should be called
1731 1723
    /// before using them.
1732 1724

	
1733 1725
    ///@{
1734 1726

	
1735 1727
    /// \brief Checks if the given node is reached from the root(s).
1736 1728
    ///
1737 1729
    /// Returns \c true if \c v is reached from the root(s).
1738 1730
    ///
1739 1731
    /// \pre Either \ref run(Node) "run()" or \ref init()
1740 1732
    /// must be called before using this function.
1741 1733
    bool reached(Node v) const { return (*_reached)[v]; }
1742 1734

	
1743 1735
    ///@}
1744 1736

	
1745 1737
  };
1746 1738

	
1747 1739
} //END OF NAMESPACE LEMON
1748 1740

	
1749 1741
#endif
Ignore white space 6 line context
... ...
@@ -252,1381 +252,1373 @@
252 252
    };
253 253

	
254 254
    template <class T>
255 255
    struct SetReachedMapTraits : public Traits {
256 256
      typedef T ReachedMap;
257 257
      static ReachedMap *createReachedMap(const Digraph &)
258 258
      {
259 259
        LEMON_ASSERT(false, "ReachedMap is not initialized");
260 260
        return 0; // ignore warnings
261 261
      }
262 262
    };
263 263
    ///\brief \ref named-templ-param "Named parameter" for setting
264 264
    ///\c ReachedMap type.
265 265
    ///
266 266
    ///\ref named-templ-param "Named parameter" for setting
267 267
    ///\c ReachedMap type.
268 268
    ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
269 269
    template <class T>
270 270
    struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > {
271 271
      typedef Dfs< Digraph, SetReachedMapTraits<T> > Create;
272 272
    };
273 273

	
274 274
    template <class T>
275 275
    struct SetProcessedMapTraits : public Traits {
276 276
      typedef T ProcessedMap;
277 277
      static ProcessedMap *createProcessedMap(const Digraph &)
278 278
      {
279 279
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
280 280
        return 0; // ignore warnings
281 281
      }
282 282
    };
283 283
    ///\brief \ref named-templ-param "Named parameter" for setting
284 284
    ///\c ProcessedMap type.
285 285
    ///
286 286
    ///\ref named-templ-param "Named parameter" for setting
287 287
    ///\c ProcessedMap type.
288 288
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
289 289
    template <class T>
290 290
    struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > {
291 291
      typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create;
292 292
    };
293 293

	
294 294
    struct SetStandardProcessedMapTraits : public Traits {
295 295
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
296 296
      static ProcessedMap *createProcessedMap(const Digraph &g)
297 297
      {
298 298
        return new ProcessedMap(g);
299 299
      }
300 300
    };
301 301
    ///\brief \ref named-templ-param "Named parameter" for setting
302 302
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
303 303
    ///
304 304
    ///\ref named-templ-param "Named parameter" for setting
305 305
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
306 306
    ///If you don't set it explicitly, it will be automatically allocated.
307 307
    struct SetStandardProcessedMap :
308 308
      public Dfs< Digraph, SetStandardProcessedMapTraits > {
309 309
      typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create;
310 310
    };
311 311

	
312 312
    ///@}
313 313

	
314 314
  public:
315 315

	
316 316
    ///Constructor.
317 317

	
318 318
    ///Constructor.
319 319
    ///\param g The digraph the algorithm runs on.
320 320
    Dfs(const Digraph &g) :
321 321
      G(&g),
322 322
      _pred(NULL), local_pred(false),
323 323
      _dist(NULL), local_dist(false),
324 324
      _reached(NULL), local_reached(false),
325 325
      _processed(NULL), local_processed(false)
326 326
    { }
327 327

	
328 328
    ///Destructor.
329 329
    ~Dfs()
330 330
    {
331 331
      if(local_pred) delete _pred;
332 332
      if(local_dist) delete _dist;
333 333
      if(local_reached) delete _reached;
334 334
      if(local_processed) delete _processed;
335 335
    }
336 336

	
337 337
    ///Sets the map that stores the predecessor arcs.
338 338

	
339 339
    ///Sets the map that stores the predecessor arcs.
340 340
    ///If you don't use this function before calling \ref run(Node) "run()"
341 341
    ///or \ref init(), an instance will be allocated automatically.
342 342
    ///The destructor deallocates this automatically allocated map,
343 343
    ///of course.
344 344
    ///\return <tt> (*this) </tt>
345 345
    Dfs &predMap(PredMap &m)
346 346
    {
347 347
      if(local_pred) {
348 348
        delete _pred;
349 349
        local_pred=false;
350 350
      }
351 351
      _pred = &m;
352 352
      return *this;
353 353
    }
354 354

	
355 355
    ///Sets the map that indicates which nodes are reached.
356 356

	
357 357
    ///Sets the map that indicates which nodes are reached.
358 358
    ///If you don't use this function before calling \ref run(Node) "run()"
359 359
    ///or \ref init(), an instance will be allocated automatically.
360 360
    ///The destructor deallocates this automatically allocated map,
361 361
    ///of course.
362 362
    ///\return <tt> (*this) </tt>
363 363
    Dfs &reachedMap(ReachedMap &m)
364 364
    {
365 365
      if(local_reached) {
366 366
        delete _reached;
367 367
        local_reached=false;
368 368
      }
369 369
      _reached = &m;
370 370
      return *this;
371 371
    }
372 372

	
373 373
    ///Sets the map that indicates which nodes are processed.
374 374

	
375 375
    ///Sets the map that indicates which nodes are processed.
376 376
    ///If you don't use this function before calling \ref run(Node) "run()"
377 377
    ///or \ref init(), an instance will be allocated automatically.
378 378
    ///The destructor deallocates this automatically allocated map,
379 379
    ///of course.
380 380
    ///\return <tt> (*this) </tt>
381 381
    Dfs &processedMap(ProcessedMap &m)
382 382
    {
383 383
      if(local_processed) {
384 384
        delete _processed;
385 385
        local_processed=false;
386 386
      }
387 387
      _processed = &m;
388 388
      return *this;
389 389
    }
390 390

	
391 391
    ///Sets the map that stores the distances of the nodes.
392 392

	
393 393
    ///Sets the map that stores the distances of the nodes calculated by
394 394
    ///the algorithm.
395 395
    ///If you don't use this function before calling \ref run(Node) "run()"
396 396
    ///or \ref init(), an instance will be allocated automatically.
397 397
    ///The destructor deallocates this automatically allocated map,
398 398
    ///of course.
399 399
    ///\return <tt> (*this) </tt>
400 400
    Dfs &distMap(DistMap &m)
401 401
    {
402 402
      if(local_dist) {
403 403
        delete _dist;
404 404
        local_dist=false;
405 405
      }
406 406
      _dist = &m;
407 407
      return *this;
408 408
    }
409 409

	
410 410
  public:
411 411

	
412 412
    ///\name Execution Control
413 413
    ///The simplest way to execute the DFS algorithm is to use one of the
414 414
    ///member functions called \ref run(Node) "run()".\n
415 415
    ///If you need better control on the execution, you have to call
416 416
    ///\ref init() first, then you can add a source node with \ref addSource()
417 417
    ///and perform the actual computation with \ref start().
418 418
    ///This procedure can be repeated if there are nodes that have not
419 419
    ///been reached.
420 420

	
421 421
    ///@{
422 422

	
423 423
    ///\brief Initializes the internal data structures.
424 424
    ///
425 425
    ///Initializes the internal data structures.
426 426
    void init()
427 427
    {
428 428
      create_maps();
429 429
      _stack.resize(countNodes(*G));
430 430
      _stack_head=-1;
431 431
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
432 432
        _pred->set(u,INVALID);
433 433
        _reached->set(u,false);
434 434
        _processed->set(u,false);
435 435
      }
436 436
    }
437 437

	
438 438
    ///Adds a new source node.
439 439

	
440 440
    ///Adds a new source node to the set of nodes to be processed.
441 441
    ///
442 442
    ///\pre The stack must be empty. Otherwise the algorithm gives
443 443
    ///wrong results. (One of the outgoing arcs of all the source nodes
444 444
    ///except for the last one will not be visited and distances will
445 445
    ///also be wrong.)
446 446
    void addSource(Node s)
447 447
    {
448 448
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
449 449
      if(!(*_reached)[s])
450 450
        {
451 451
          _reached->set(s,true);
452 452
          _pred->set(s,INVALID);
453 453
          OutArcIt e(*G,s);
454 454
          if(e!=INVALID) {
455 455
            _stack[++_stack_head]=e;
456 456
            _dist->set(s,_stack_head);
457 457
          }
458 458
          else {
459 459
            _processed->set(s,true);
460 460
            _dist->set(s,0);
461 461
          }
462 462
        }
463 463
    }
464 464

	
465 465
    ///Processes the next arc.
466 466

	
467 467
    ///Processes the next arc.
468 468
    ///
469 469
    ///\return The processed arc.
470 470
    ///
471 471
    ///\pre The stack must not be empty.
472 472
    Arc processNextArc()
473 473
    {
474 474
      Node m;
475 475
      Arc e=_stack[_stack_head];
476 476
      if(!(*_reached)[m=G->target(e)]) {
477 477
        _pred->set(m,e);
478 478
        _reached->set(m,true);
479 479
        ++_stack_head;
480 480
        _stack[_stack_head] = OutArcIt(*G, m);
481 481
        _dist->set(m,_stack_head);
482 482
      }
483 483
      else {
484 484
        m=G->source(e);
485 485
        ++_stack[_stack_head];
486 486
      }
487 487
      while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
488 488
        _processed->set(m,true);
489 489
        --_stack_head;
490 490
        if(_stack_head>=0) {
491 491
          m=G->source(_stack[_stack_head]);
492 492
          ++_stack[_stack_head];
493 493
        }
494 494
      }
495 495
      return e;
496 496
    }
497 497

	
498 498
    ///Next arc to be processed.
499 499

	
500 500
    ///Next arc to be processed.
501 501
    ///
502 502
    ///\return The next arc to be processed or \c INVALID if the stack
503 503
    ///is empty.
504 504
    OutArcIt nextArc() const
505 505
    {
506 506
      return _stack_head>=0?_stack[_stack_head]:INVALID;
507 507
    }
508 508

	
509 509
    ///Returns \c false if there are nodes to be processed.
510 510

	
511 511
    ///Returns \c false if there are nodes to be processed
512 512
    ///in the queue (stack).
513 513
    bool emptyQueue() const { return _stack_head<0; }
514 514

	
515 515
    ///Returns the number of the nodes to be processed.
516 516

	
517 517
    ///Returns the number of the nodes to be processed
518 518
    ///in the queue (stack).
519 519
    int queueSize() const { return _stack_head+1; }
520 520

	
521 521
    ///Executes the algorithm.
522 522

	
523 523
    ///Executes the algorithm.
524 524
    ///
525 525
    ///This method runs the %DFS algorithm from the root node
526 526
    ///in order to compute the DFS path to each node.
527 527
    ///
528 528
    /// The algorithm computes
529 529
    ///- the %DFS tree,
530 530
    ///- the distance of each node from the root in the %DFS tree.
531 531
    ///
532 532
    ///\pre init() must be called and a root node should be
533 533
    ///added with addSource() before using this function.
534 534
    ///
535 535
    ///\note <tt>d.start()</tt> is just a shortcut of the following code.
536 536
    ///\code
537 537
    ///  while ( !d.emptyQueue() ) {
538 538
    ///    d.processNextArc();
539 539
    ///  }
540 540
    ///\endcode
541 541
    void start()
542 542
    {
543 543
      while ( !emptyQueue() ) processNextArc();
544 544
    }
545 545

	
546 546
    ///Executes the algorithm until the given target node is reached.
547 547

	
548 548
    ///Executes the algorithm until the given target node is reached.
549 549
    ///
550 550
    ///This method runs the %DFS algorithm from the root node
551 551
    ///in order to compute the DFS path to \c t.
552 552
    ///
553 553
    ///The algorithm computes
554 554
    ///- the %DFS path to \c t,
555 555
    ///- the distance of \c t from the root in the %DFS tree.
556 556
    ///
557 557
    ///\pre init() must be called and a root node should be
558 558
    ///added with addSource() before using this function.
559 559
    void start(Node t)
560 560
    {
561 561
      while ( !emptyQueue() && G->target(_stack[_stack_head])!=t )
562 562
        processNextArc();
563 563
    }
564 564

	
565 565
    ///Executes the algorithm until a condition is met.
566 566

	
567 567
    ///Executes the algorithm until a condition is met.
568 568
    ///
569 569
    ///This method runs the %DFS algorithm from the root node
570 570
    ///until an arc \c a with <tt>am[a]</tt> true is found.
571 571
    ///
572 572
    ///\param am A \c bool (or convertible) arc map. The algorithm
573 573
    ///will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
574 574
    ///
575 575
    ///\return The reached arc \c a with <tt>am[a]</tt> true or
576 576
    ///\c INVALID if no such arc was found.
577 577
    ///
578 578
    ///\pre init() must be called and a root node should be
579 579
    ///added with addSource() before using this function.
580 580
    ///
581 581
    ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
582 582
    ///not a node map.
583 583
    template<class ArcBoolMap>
584 584
    Arc start(const ArcBoolMap &am)
585 585
    {
586 586
      while ( !emptyQueue() && !am[_stack[_stack_head]] )
587 587
        processNextArc();
588 588
      return emptyQueue() ? INVALID : _stack[_stack_head];
589 589
    }
590 590

	
591 591
    ///Runs the algorithm from the given source node.
592 592

	
593 593
    ///This method runs the %DFS algorithm from node \c s
594 594
    ///in order to compute the DFS path to each node.
595 595
    ///
596 596
    ///The algorithm computes
597 597
    ///- the %DFS tree,
598 598
    ///- the distance of each node from the root in the %DFS tree.
599 599
    ///
600 600
    ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
601 601
    ///\code
602 602
    ///  d.init();
603 603
    ///  d.addSource(s);
604 604
    ///  d.start();
605 605
    ///\endcode
606 606
    void run(Node s) {
607 607
      init();
608 608
      addSource(s);
609 609
      start();
610 610
    }
611 611

	
612 612
    ///Finds the %DFS path between \c s and \c t.
613 613

	
614 614
    ///This method runs the %DFS algorithm from node \c s
615 615
    ///in order to compute the DFS path to node \c t
616 616
    ///(it stops searching when \c t is processed)
617 617
    ///
618 618
    ///\return \c true if \c t is reachable form \c s.
619 619
    ///
620 620
    ///\note Apart from the return value, <tt>d.run(s,t)</tt> is
621 621
    ///just a shortcut of the following code.
622 622
    ///\code
623 623
    ///  d.init();
624 624
    ///  d.addSource(s);
625 625
    ///  d.start(t);
626 626
    ///\endcode
627 627
    bool run(Node s,Node t) {
628 628
      init();
629 629
      addSource(s);
630 630
      start(t);
631 631
      return reached(t);
632 632
    }
633 633

	
634 634
    ///Runs the algorithm to visit all nodes in the digraph.
635 635

	
636
    ///This method runs the %DFS algorithm in order to compute the
637
    ///%DFS path to each node.
638
    ///
639
    ///The algorithm computes
640
    ///- the %DFS tree (forest),
641
    ///- the distance of each node from the root(s) in the %DFS tree.
636
    ///This method runs the %DFS algorithm in order to visit all nodes
637
    ///in the digraph.
642 638
    ///
643 639
    ///\note <tt>d.run()</tt> is just a shortcut of the following code.
644 640
    ///\code
645 641
    ///  d.init();
646 642
    ///  for (NodeIt n(digraph); n != INVALID; ++n) {
647 643
    ///    if (!d.reached(n)) {
648 644
    ///      d.addSource(n);
649 645
    ///      d.start();
650 646
    ///    }
651 647
    ///  }
652 648
    ///\endcode
653 649
    void run() {
654 650
      init();
655 651
      for (NodeIt it(*G); it != INVALID; ++it) {
656 652
        if (!reached(it)) {
657 653
          addSource(it);
658 654
          start();
659 655
        }
660 656
      }
661 657
    }
662 658

	
663 659
    ///@}
664 660

	
665 661
    ///\name Query Functions
666 662
    ///The results of the DFS algorithm can be obtained using these
667 663
    ///functions.\n
668 664
    ///Either \ref run(Node) "run()" or \ref start() should be called
669 665
    ///before using them.
670 666

	
671 667
    ///@{
672 668

	
673 669
    ///The DFS path to the given node.
674 670

	
675 671
    ///Returns the DFS path to the given node from the root(s).
676 672
    ///
677 673
    ///\warning \c t should be reached from the root(s).
678 674
    ///
679 675
    ///\pre Either \ref run(Node) "run()" or \ref init()
680 676
    ///must be called before using this function.
681 677
    Path path(Node t) const { return Path(*G, *_pred, t); }
682 678

	
683 679
    ///The distance of the given node from the root(s).
684 680

	
685 681
    ///Returns the distance of the given node from the root(s).
686 682
    ///
687 683
    ///\warning If node \c v is not reached from the root(s), then
688 684
    ///the return value of this function is undefined.
689 685
    ///
690 686
    ///\pre Either \ref run(Node) "run()" or \ref init()
691 687
    ///must be called before using this function.
692 688
    int dist(Node v) const { return (*_dist)[v]; }
693 689

	
694 690
    ///Returns the 'previous arc' of the %DFS tree for the given node.
695 691

	
696 692
    ///This function returns the 'previous arc' of the %DFS tree for the
697 693
    ///node \c v, i.e. it returns the last arc of a %DFS path from a
698 694
    ///root to \c v. It is \c INVALID if \c v is not reached from the
699 695
    ///root(s) or if \c v is a root.
700 696
    ///
701 697
    ///The %DFS tree used here is equal to the %DFS tree used in
702 698
    ///\ref predNode() and \ref predMap().
703 699
    ///
704 700
    ///\pre Either \ref run(Node) "run()" or \ref init()
705 701
    ///must be called before using this function.
706 702
    Arc predArc(Node v) const { return (*_pred)[v];}
707 703

	
708 704
    ///Returns the 'previous node' of the %DFS tree for the given node.
709 705

	
710 706
    ///This function returns the 'previous node' of the %DFS
711 707
    ///tree for the node \c v, i.e. it returns the last but one node
712 708
    ///of a %DFS path from a root to \c v. It is \c INVALID
713 709
    ///if \c v is not reached from the root(s) or if \c v is a root.
714 710
    ///
715 711
    ///The %DFS tree used here is equal to the %DFS tree used in
716 712
    ///\ref predArc() and \ref predMap().
717 713
    ///
718 714
    ///\pre Either \ref run(Node) "run()" or \ref init()
719 715
    ///must be called before using this function.
720 716
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
721 717
                                  G->source((*_pred)[v]); }
722 718

	
723 719
    ///\brief Returns a const reference to the node map that stores the
724 720
    ///distances of the nodes.
725 721
    ///
726 722
    ///Returns a const reference to the node map that stores the
727 723
    ///distances of the nodes calculated by the algorithm.
728 724
    ///
729 725
    ///\pre Either \ref run(Node) "run()" or \ref init()
730 726
    ///must be called before using this function.
731 727
    const DistMap &distMap() const { return *_dist;}
732 728

	
733 729
    ///\brief Returns a const reference to the node map that stores the
734 730
    ///predecessor arcs.
735 731
    ///
736 732
    ///Returns a const reference to the node map that stores the predecessor
737 733
    ///arcs, which form the DFS tree (forest).
738 734
    ///
739 735
    ///\pre Either \ref run(Node) "run()" or \ref init()
740 736
    ///must be called before using this function.
741 737
    const PredMap &predMap() const { return *_pred;}
742 738

	
743 739
    ///Checks if the given node. node is reached from the root(s).
744 740

	
745 741
    ///Returns \c true if \c v is reached from the root(s).
746 742
    ///
747 743
    ///\pre Either \ref run(Node) "run()" or \ref init()
748 744
    ///must be called before using this function.
749 745
    bool reached(Node v) const { return (*_reached)[v]; }
750 746

	
751 747
    ///@}
752 748
  };
753 749

	
754 750
  ///Default traits class of dfs() function.
755 751

	
756 752
  ///Default traits class of dfs() function.
757 753
  ///\tparam GR Digraph type.
758 754
  template<class GR>
759 755
  struct DfsWizardDefaultTraits
760 756
  {
761 757
    ///The type of the digraph the algorithm runs on.
762 758
    typedef GR Digraph;
763 759

	
764 760
    ///\brief The type of the map that stores the predecessor
765 761
    ///arcs of the %DFS paths.
766 762
    ///
767 763
    ///The type of the map that stores the predecessor
768 764
    ///arcs of the %DFS paths.
769 765
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
770 766
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
771 767
    ///Instantiates a PredMap.
772 768

	
773 769
    ///This function instantiates a PredMap.
774 770
    ///\param g is the digraph, to which we would like to define the
775 771
    ///PredMap.
776 772
    static PredMap *createPredMap(const Digraph &g)
777 773
    {
778 774
      return new PredMap(g);
779 775
    }
780 776

	
781 777
    ///The type of the map that indicates which nodes are processed.
782 778

	
783 779
    ///The type of the map that indicates which nodes are processed.
784 780
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
785 781
    ///By default it is a NullMap.
786 782
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
787 783
    ///Instantiates a ProcessedMap.
788 784

	
789 785
    ///This function instantiates a ProcessedMap.
790 786
    ///\param g is the digraph, to which
791 787
    ///we would like to define the ProcessedMap.
792 788
#ifdef DOXYGEN
793 789
    static ProcessedMap *createProcessedMap(const Digraph &g)
794 790
#else
795 791
    static ProcessedMap *createProcessedMap(const Digraph &)
796 792
#endif
797 793
    {
798 794
      return new ProcessedMap();
799 795
    }
800 796

	
801 797
    ///The type of the map that indicates which nodes are reached.
802 798

	
803 799
    ///The type of the map that indicates which nodes are reached.
804 800
    ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
805 801
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
806 802
    ///Instantiates a ReachedMap.
807 803

	
808 804
    ///This function instantiates a ReachedMap.
809 805
    ///\param g is the digraph, to which
810 806
    ///we would like to define the ReachedMap.
811 807
    static ReachedMap *createReachedMap(const Digraph &g)
812 808
    {
813 809
      return new ReachedMap(g);
814 810
    }
815 811

	
816 812
    ///The type of the map that stores the distances of the nodes.
817 813

	
818 814
    ///The type of the map that stores the distances of the nodes.
819 815
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
820 816
    typedef typename Digraph::template NodeMap<int> DistMap;
821 817
    ///Instantiates a DistMap.
822 818

	
823 819
    ///This function instantiates a DistMap.
824 820
    ///\param g is the digraph, to which we would like to define
825 821
    ///the DistMap
826 822
    static DistMap *createDistMap(const Digraph &g)
827 823
    {
828 824
      return new DistMap(g);
829 825
    }
830 826

	
831 827
    ///The type of the DFS paths.
832 828

	
833 829
    ///The type of the DFS paths.
834 830
    ///It must conform to the \ref concepts::Path "Path" concept.
835 831
    typedef lemon::Path<Digraph> Path;
836 832
  };
837 833

	
838 834
  /// Default traits class used by DfsWizard
839 835

	
840 836
  /// Default traits class used by DfsWizard.
841 837
  /// \tparam GR The type of the digraph.
842 838
  template<class GR>
843 839
  class DfsWizardBase : public DfsWizardDefaultTraits<GR>
844 840
  {
845 841

	
846 842
    typedef DfsWizardDefaultTraits<GR> Base;
847 843
  protected:
848 844
    //The type of the nodes in the digraph.
849 845
    typedef typename Base::Digraph::Node Node;
850 846

	
851 847
    //Pointer to the digraph the algorithm runs on.
852 848
    void *_g;
853 849
    //Pointer to the map of reached nodes.
854 850
    void *_reached;
855 851
    //Pointer to the map of processed nodes.
856 852
    void *_processed;
857 853
    //Pointer to the map of predecessors arcs.
858 854
    void *_pred;
859 855
    //Pointer to the map of distances.
860 856
    void *_dist;
861 857
    //Pointer to the DFS path to the target node.
862 858
    void *_path;
863 859
    //Pointer to the distance of the target node.
864 860
    int *_di;
865 861

	
866 862
    public:
867 863
    /// Constructor.
868 864

	
869 865
    /// This constructor does not require parameters, it initiates
870 866
    /// all of the attributes to \c 0.
871 867
    DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
872 868
                      _dist(0), _path(0), _di(0) {}
873 869

	
874 870
    /// Constructor.
875 871

	
876 872
    /// This constructor requires one parameter,
877 873
    /// others are initiated to \c 0.
878 874
    /// \param g The digraph the algorithm runs on.
879 875
    DfsWizardBase(const GR &g) :
880 876
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
881 877
      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
882 878

	
883 879
  };
884 880

	
885 881
  /// Auxiliary class for the function-type interface of DFS algorithm.
886 882

	
887 883
  /// This auxiliary class is created to implement the
888 884
  /// \ref dfs() "function-type interface" of \ref Dfs algorithm.
889 885
  /// It does not have own \ref run(Node) "run()" method, it uses the
890 886
  /// functions and features of the plain \ref Dfs.
891 887
  ///
892 888
  /// This class should only be used through the \ref dfs() function,
893 889
  /// which makes it easier to use the algorithm.
894 890
  template<class TR>
895 891
  class DfsWizard : public TR
896 892
  {
897 893
    typedef TR Base;
898 894

	
899 895
    typedef typename TR::Digraph Digraph;
900 896

	
901 897
    typedef typename Digraph::Node Node;
902 898
    typedef typename Digraph::NodeIt NodeIt;
903 899
    typedef typename Digraph::Arc Arc;
904 900
    typedef typename Digraph::OutArcIt OutArcIt;
905 901

	
906 902
    typedef typename TR::PredMap PredMap;
907 903
    typedef typename TR::DistMap DistMap;
908 904
    typedef typename TR::ReachedMap ReachedMap;
909 905
    typedef typename TR::ProcessedMap ProcessedMap;
910 906
    typedef typename TR::Path Path;
911 907

	
912 908
  public:
913 909

	
914 910
    /// Constructor.
915 911
    DfsWizard() : TR() {}
916 912

	
917 913
    /// Constructor that requires parameters.
918 914

	
919 915
    /// Constructor that requires parameters.
920 916
    /// These parameters will be the default values for the traits class.
921 917
    /// \param g The digraph the algorithm runs on.
922 918
    DfsWizard(const Digraph &g) :
923 919
      TR(g) {}
924 920

	
925 921
    ///Copy constructor
926 922
    DfsWizard(const TR &b) : TR(b) {}
927 923

	
928 924
    ~DfsWizard() {}
929 925

	
930 926
    ///Runs DFS algorithm from the given source node.
931 927

	
932 928
    ///This method runs DFS algorithm from node \c s
933 929
    ///in order to compute the DFS path to each node.
934 930
    void run(Node s)
935 931
    {
936 932
      Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
937 933
      if (Base::_pred)
938 934
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
939 935
      if (Base::_dist)
940 936
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
941 937
      if (Base::_reached)
942 938
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
943 939
      if (Base::_processed)
944 940
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
945 941
      if (s!=INVALID)
946 942
        alg.run(s);
947 943
      else
948 944
        alg.run();
949 945
    }
950 946

	
951 947
    ///Finds the DFS path between \c s and \c t.
952 948

	
953 949
    ///This method runs DFS algorithm from node \c s
954 950
    ///in order to compute the DFS path to node \c t
955 951
    ///(it stops searching when \c t is processed).
956 952
    ///
957 953
    ///\return \c true if \c t is reachable form \c s.
958 954
    bool run(Node s, Node t)
959 955
    {
960 956
      Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
961 957
      if (Base::_pred)
962 958
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
963 959
      if (Base::_dist)
964 960
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
965 961
      if (Base::_reached)
966 962
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
967 963
      if (Base::_processed)
968 964
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
969 965
      alg.run(s,t);
970 966
      if (Base::_path)
971 967
        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
972 968
      if (Base::_di)
973 969
        *Base::_di = alg.dist(t);
974 970
      return alg.reached(t);
975 971
      }
976 972

	
977 973
    ///Runs DFS algorithm to visit all nodes in the digraph.
978 974

	
979
    ///This method runs DFS algorithm in order to compute
980
    ///the DFS path to each node.
975
    ///This method runs DFS algorithm in order to visit all nodes
976
    ///in the digraph.
981 977
    void run()
982 978
    {
983 979
      run(INVALID);
984 980
    }
985 981

	
986 982
    template<class T>
987 983
    struct SetPredMapBase : public Base {
988 984
      typedef T PredMap;
989 985
      static PredMap *createPredMap(const Digraph &) { return 0; };
990 986
      SetPredMapBase(const TR &b) : TR(b) {}
991 987
    };
992 988

	
993 989
    ///\brief \ref named-templ-param "Named parameter" for setting
994 990
    ///the predecessor map.
995 991
    ///
996 992
    ///\ref named-templ-param "Named parameter" function for setting
997 993
    ///the map that stores the predecessor arcs of the nodes.
998 994
    template<class T>
999 995
    DfsWizard<SetPredMapBase<T> > predMap(const T &t)
1000 996
    {
1001 997
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1002 998
      return DfsWizard<SetPredMapBase<T> >(*this);
1003 999
    }
1004 1000

	
1005 1001
    template<class T>
1006 1002
    struct SetReachedMapBase : public Base {
1007 1003
      typedef T ReachedMap;
1008 1004
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1009 1005
      SetReachedMapBase(const TR &b) : TR(b) {}
1010 1006
    };
1011 1007

	
1012 1008
    ///\brief \ref named-templ-param "Named parameter" for setting
1013 1009
    ///the reached map.
1014 1010
    ///
1015 1011
    ///\ref named-templ-param "Named parameter" function for setting
1016 1012
    ///the map that indicates which nodes are reached.
1017 1013
    template<class T>
1018 1014
    DfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1019 1015
    {
1020 1016
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1021 1017
      return DfsWizard<SetReachedMapBase<T> >(*this);
1022 1018
    }
1023 1019

	
1024 1020
    template<class T>
1025 1021
    struct SetDistMapBase : public Base {
1026 1022
      typedef T DistMap;
1027 1023
      static DistMap *createDistMap(const Digraph &) { return 0; };
1028 1024
      SetDistMapBase(const TR &b) : TR(b) {}
1029 1025
    };
1030 1026

	
1031 1027
    ///\brief \ref named-templ-param "Named parameter" for setting
1032 1028
    ///the distance map.
1033 1029
    ///
1034 1030
    ///\ref named-templ-param "Named parameter" function for setting
1035 1031
    ///the map that stores the distances of the nodes calculated
1036 1032
    ///by the algorithm.
1037 1033
    template<class T>
1038 1034
    DfsWizard<SetDistMapBase<T> > distMap(const T &t)
1039 1035
    {
1040 1036
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1041 1037
      return DfsWizard<SetDistMapBase<T> >(*this);
1042 1038
    }
1043 1039

	
1044 1040
    template<class T>
1045 1041
    struct SetProcessedMapBase : public Base {
1046 1042
      typedef T ProcessedMap;
1047 1043
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1048 1044
      SetProcessedMapBase(const TR &b) : TR(b) {}
1049 1045
    };
1050 1046

	
1051 1047
    ///\brief \ref named-func-param "Named parameter" for setting
1052 1048
    ///the processed map.
1053 1049
    ///
1054 1050
    ///\ref named-templ-param "Named parameter" function for setting
1055 1051
    ///the map that indicates which nodes are processed.
1056 1052
    template<class T>
1057 1053
    DfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1058 1054
    {
1059 1055
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1060 1056
      return DfsWizard<SetProcessedMapBase<T> >(*this);
1061 1057
    }
1062 1058

	
1063 1059
    template<class T>
1064 1060
    struct SetPathBase : public Base {
1065 1061
      typedef T Path;
1066 1062
      SetPathBase(const TR &b) : TR(b) {}
1067 1063
    };
1068 1064
    ///\brief \ref named-func-param "Named parameter"
1069 1065
    ///for getting the DFS path to the target node.
1070 1066
    ///
1071 1067
    ///\ref named-func-param "Named parameter"
1072 1068
    ///for getting the DFS path to the target node.
1073 1069
    template<class T>
1074 1070
    DfsWizard<SetPathBase<T> > path(const T &t)
1075 1071
    {
1076 1072
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1077 1073
      return DfsWizard<SetPathBase<T> >(*this);
1078 1074
    }
1079 1075

	
1080 1076
    ///\brief \ref named-func-param "Named parameter"
1081 1077
    ///for getting the distance of the target node.
1082 1078
    ///
1083 1079
    ///\ref named-func-param "Named parameter"
1084 1080
    ///for getting the distance of the target node.
1085 1081
    DfsWizard dist(const int &d)
1086 1082
    {
1087 1083
      Base::_di=const_cast<int*>(&d);
1088 1084
      return *this;
1089 1085
    }
1090 1086

	
1091 1087
  };
1092 1088

	
1093 1089
  ///Function-type interface for DFS algorithm.
1094 1090

	
1095 1091
  ///\ingroup search
1096 1092
  ///Function-type interface for DFS algorithm.
1097 1093
  ///
1098 1094
  ///This function also has several \ref named-func-param "named parameters",
1099 1095
  ///they are declared as the members of class \ref DfsWizard.
1100 1096
  ///The following examples show how to use these parameters.
1101 1097
  ///\code
1102 1098
  ///  // Compute the DFS tree
1103 1099
  ///  dfs(g).predMap(preds).distMap(dists).run(s);
1104 1100
  ///
1105 1101
  ///  // Compute the DFS path from s to t
1106 1102
  ///  bool reached = dfs(g).path(p).dist(d).run(s,t);
1107 1103
  ///\endcode
1108 1104
  ///\warning Don't forget to put the \ref DfsWizard::run(Node) "run()"
1109 1105
  ///to the end of the parameter list.
1110 1106
  ///\sa DfsWizard
1111 1107
  ///\sa Dfs
1112 1108
  template<class GR>
1113 1109
  DfsWizard<DfsWizardBase<GR> >
1114 1110
  dfs(const GR &digraph)
1115 1111
  {
1116 1112
    return DfsWizard<DfsWizardBase<GR> >(digraph);
1117 1113
  }
1118 1114

	
1119 1115
#ifdef DOXYGEN
1120 1116
  /// \brief Visitor class for DFS.
1121 1117
  ///
1122 1118
  /// This class defines the interface of the DfsVisit events, and
1123 1119
  /// it could be the base of a real visitor class.
1124 1120
  template <typename GR>
1125 1121
  struct DfsVisitor {
1126 1122
    typedef GR Digraph;
1127 1123
    typedef typename Digraph::Arc Arc;
1128 1124
    typedef typename Digraph::Node Node;
1129 1125
    /// \brief Called for the source node of the DFS.
1130 1126
    ///
1131 1127
    /// This function is called for the source node of the DFS.
1132 1128
    void start(const Node& node) {}
1133 1129
    /// \brief Called when the source node is leaved.
1134 1130
    ///
1135 1131
    /// This function is called when the source node is leaved.
1136 1132
    void stop(const Node& node) {}
1137 1133
    /// \brief Called when a node is reached first time.
1138 1134
    ///
1139 1135
    /// This function is called when a node is reached first time.
1140 1136
    void reach(const Node& node) {}
1141 1137
    /// \brief Called when an arc reaches a new node.
1142 1138
    ///
1143 1139
    /// This function is called when the DFS finds an arc whose target node
1144 1140
    /// is not reached yet.
1145 1141
    void discover(const Arc& arc) {}
1146 1142
    /// \brief Called when an arc is examined but its target node is
1147 1143
    /// already discovered.
1148 1144
    ///
1149 1145
    /// This function is called when an arc is examined but its target node is
1150 1146
    /// already discovered.
1151 1147
    void examine(const Arc& arc) {}
1152 1148
    /// \brief Called when the DFS steps back from a node.
1153 1149
    ///
1154 1150
    /// This function is called when the DFS steps back from a node.
1155 1151
    void leave(const Node& node) {}
1156 1152
    /// \brief Called when the DFS steps back on an arc.
1157 1153
    ///
1158 1154
    /// This function is called when the DFS steps back on an arc.
1159 1155
    void backtrack(const Arc& arc) {}
1160 1156
  };
1161 1157
#else
1162 1158
  template <typename GR>
1163 1159
  struct DfsVisitor {
1164 1160
    typedef GR Digraph;
1165 1161
    typedef typename Digraph::Arc Arc;
1166 1162
    typedef typename Digraph::Node Node;
1167 1163
    void start(const Node&) {}
1168 1164
    void stop(const Node&) {}
1169 1165
    void reach(const Node&) {}
1170 1166
    void discover(const Arc&) {}
1171 1167
    void examine(const Arc&) {}
1172 1168
    void leave(const Node&) {}
1173 1169
    void backtrack(const Arc&) {}
1174 1170

	
1175 1171
    template <typename _Visitor>
1176 1172
    struct Constraints {
1177 1173
      void constraints() {
1178 1174
        Arc arc;
1179 1175
        Node node;
1180 1176
        visitor.start(node);
1181 1177
        visitor.stop(arc);
1182 1178
        visitor.reach(node);
1183 1179
        visitor.discover(arc);
1184 1180
        visitor.examine(arc);
1185 1181
        visitor.leave(node);
1186 1182
        visitor.backtrack(arc);
1187 1183
      }
1188 1184
      _Visitor& visitor;
1189 1185
    };
1190 1186
  };
1191 1187
#endif
1192 1188

	
1193 1189
  /// \brief Default traits class of DfsVisit class.
1194 1190
  ///
1195 1191
  /// Default traits class of DfsVisit class.
1196 1192
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1197 1193
  template<class GR>
1198 1194
  struct DfsVisitDefaultTraits {
1199 1195

	
1200 1196
    /// \brief The type of the digraph the algorithm runs on.
1201 1197
    typedef GR Digraph;
1202 1198

	
1203 1199
    /// \brief The type of the map that indicates which nodes are reached.
1204 1200
    ///
1205 1201
    /// The type of the map that indicates which nodes are reached.
1206 1202
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1207 1203
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1208 1204

	
1209 1205
    /// \brief Instantiates a ReachedMap.
1210 1206
    ///
1211 1207
    /// This function instantiates a ReachedMap.
1212 1208
    /// \param digraph is the digraph, to which
1213 1209
    /// we would like to define the ReachedMap.
1214 1210
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1215 1211
      return new ReachedMap(digraph);
1216 1212
    }
1217 1213

	
1218 1214
  };
1219 1215

	
1220 1216
  /// \ingroup search
1221 1217
  ///
1222 1218
  /// \brief DFS algorithm class with visitor interface.
1223 1219
  ///
1224 1220
  /// This class provides an efficient implementation of the DFS algorithm
1225 1221
  /// with visitor interface.
1226 1222
  ///
1227 1223
  /// The DfsVisit class provides an alternative interface to the Dfs
1228 1224
  /// class. It works with callback mechanism, the DfsVisit object calls
1229 1225
  /// the member functions of the \c Visitor class on every DFS event.
1230 1226
  ///
1231 1227
  /// This interface of the DFS algorithm should be used in special cases
1232 1228
  /// when extra actions have to be performed in connection with certain
1233 1229
  /// events of the DFS algorithm. Otherwise consider to use Dfs or dfs()
1234 1230
  /// instead.
1235 1231
  ///
1236 1232
  /// \tparam GR The type of the digraph the algorithm runs on.
1237 1233
  /// The default type is \ref ListDigraph.
1238 1234
  /// The value of GR is not used directly by \ref DfsVisit,
1239 1235
  /// it is only passed to \ref DfsVisitDefaultTraits.
1240 1236
  /// \tparam VS The Visitor type that is used by the algorithm.
1241 1237
  /// \ref DfsVisitor "DfsVisitor<GR>" is an empty visitor, which
1242 1238
  /// does not observe the DFS events. If you want to observe the DFS
1243 1239
  /// events, you should implement your own visitor class.
1244 1240
  /// \tparam TR Traits class to set various data types used by the
1245 1241
  /// algorithm. The default traits class is
1246 1242
  /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<GR>".
1247 1243
  /// See \ref DfsVisitDefaultTraits for the documentation of
1248 1244
  /// a DFS visit traits class.
1249 1245
#ifdef DOXYGEN
1250 1246
  template <typename GR, typename VS, typename TR>
1251 1247
#else
1252 1248
  template <typename GR = ListDigraph,
1253 1249
            typename VS = DfsVisitor<GR>,
1254 1250
            typename TR = DfsVisitDefaultTraits<GR> >
1255 1251
#endif
1256 1252
  class DfsVisit {
1257 1253
  public:
1258 1254

	
1259 1255
    ///The traits class.
1260 1256
    typedef TR Traits;
1261 1257

	
1262 1258
    ///The type of the digraph the algorithm runs on.
1263 1259
    typedef typename Traits::Digraph Digraph;
1264 1260

	
1265 1261
    ///The visitor type used by the algorithm.
1266 1262
    typedef VS Visitor;
1267 1263

	
1268 1264
    ///The type of the map that indicates which nodes are reached.
1269 1265
    typedef typename Traits::ReachedMap ReachedMap;
1270 1266

	
1271 1267
  private:
1272 1268

	
1273 1269
    typedef typename Digraph::Node Node;
1274 1270
    typedef typename Digraph::NodeIt NodeIt;
1275 1271
    typedef typename Digraph::Arc Arc;
1276 1272
    typedef typename Digraph::OutArcIt OutArcIt;
1277 1273

	
1278 1274
    //Pointer to the underlying digraph.
1279 1275
    const Digraph *_digraph;
1280 1276
    //Pointer to the visitor object.
1281 1277
    Visitor *_visitor;
1282 1278
    //Pointer to the map of reached status of the nodes.
1283 1279
    ReachedMap *_reached;
1284 1280
    //Indicates if _reached is locally allocated (true) or not.
1285 1281
    bool local_reached;
1286 1282

	
1287 1283
    std::vector<typename Digraph::Arc> _stack;
1288 1284
    int _stack_head;
1289 1285

	
1290 1286
    //Creates the maps if necessary.
1291 1287
    void create_maps() {
1292 1288
      if(!_reached) {
1293 1289
        local_reached = true;
1294 1290
        _reached = Traits::createReachedMap(*_digraph);
1295 1291
      }
1296 1292
    }
1297 1293

	
1298 1294
  protected:
1299 1295

	
1300 1296
    DfsVisit() {}
1301 1297

	
1302 1298
  public:
1303 1299

	
1304 1300
    typedef DfsVisit Create;
1305 1301

	
1306 1302
    /// \name Named Template Parameters
1307 1303

	
1308 1304
    ///@{
1309 1305
    template <class T>
1310 1306
    struct SetReachedMapTraits : public Traits {
1311 1307
      typedef T ReachedMap;
1312 1308
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1313 1309
        LEMON_ASSERT(false, "ReachedMap is not initialized");
1314 1310
        return 0; // ignore warnings
1315 1311
      }
1316 1312
    };
1317 1313
    /// \brief \ref named-templ-param "Named parameter" for setting
1318 1314
    /// ReachedMap type.
1319 1315
    ///
1320 1316
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1321 1317
    template <class T>
1322 1318
    struct SetReachedMap : public DfsVisit< Digraph, Visitor,
1323 1319
                                            SetReachedMapTraits<T> > {
1324 1320
      typedef DfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1325 1321
    };
1326 1322
    ///@}
1327 1323

	
1328 1324
  public:
1329 1325

	
1330 1326
    /// \brief Constructor.
1331 1327
    ///
1332 1328
    /// Constructor.
1333 1329
    ///
1334 1330
    /// \param digraph The digraph the algorithm runs on.
1335 1331
    /// \param visitor The visitor object of the algorithm.
1336 1332
    DfsVisit(const Digraph& digraph, Visitor& visitor)
1337 1333
      : _digraph(&digraph), _visitor(&visitor),
1338 1334
        _reached(0), local_reached(false) {}
1339 1335

	
1340 1336
    /// \brief Destructor.
1341 1337
    ~DfsVisit() {
1342 1338
      if(local_reached) delete _reached;
1343 1339
    }
1344 1340

	
1345 1341
    /// \brief Sets the map that indicates which nodes are reached.
1346 1342
    ///
1347 1343
    /// Sets the map that indicates which nodes are reached.
1348 1344
    /// If you don't use this function before calling \ref run(Node) "run()"
1349 1345
    /// or \ref init(), an instance will be allocated automatically.
1350 1346
    /// The destructor deallocates this automatically allocated map,
1351 1347
    /// of course.
1352 1348
    /// \return <tt> (*this) </tt>
1353 1349
    DfsVisit &reachedMap(ReachedMap &m) {
1354 1350
      if(local_reached) {
1355 1351
        delete _reached;
1356 1352
        local_reached=false;
1357 1353
      }
1358 1354
      _reached = &m;
1359 1355
      return *this;
1360 1356
    }
1361 1357

	
1362 1358
  public:
1363 1359

	
1364 1360
    /// \name Execution Control
1365 1361
    /// The simplest way to execute the DFS algorithm is to use one of the
1366 1362
    /// member functions called \ref run(Node) "run()".\n
1367 1363
    /// If you need better control on the execution, you have to call
1368 1364
    /// \ref init() first, then you can add a source node with \ref addSource()
1369 1365
    /// and perform the actual computation with \ref start().
1370 1366
    /// This procedure can be repeated if there are nodes that have not
1371 1367
    /// been reached.
1372 1368

	
1373 1369
    /// @{
1374 1370

	
1375 1371
    /// \brief Initializes the internal data structures.
1376 1372
    ///
1377 1373
    /// Initializes the internal data structures.
1378 1374
    void init() {
1379 1375
      create_maps();
1380 1376
      _stack.resize(countNodes(*_digraph));
1381 1377
      _stack_head = -1;
1382 1378
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1383 1379
        _reached->set(u, false);
1384 1380
      }
1385 1381
    }
1386 1382

	
1387 1383
    /// \brief Adds a new source node.
1388 1384
    ///
1389 1385
    /// Adds a new source node to the set of nodes to be processed.
1390 1386
    ///
1391 1387
    /// \pre The stack must be empty. Otherwise the algorithm gives
1392 1388
    /// wrong results. (One of the outgoing arcs of all the source nodes
1393 1389
    /// except for the last one will not be visited and distances will
1394 1390
    /// also be wrong.)
1395 1391
    void addSource(Node s)
1396 1392
    {
1397 1393
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1398 1394
      if(!(*_reached)[s]) {
1399 1395
          _reached->set(s,true);
1400 1396
          _visitor->start(s);
1401 1397
          _visitor->reach(s);
1402 1398
          Arc e;
1403 1399
          _digraph->firstOut(e, s);
1404 1400
          if (e != INVALID) {
1405 1401
            _stack[++_stack_head] = e;
1406 1402
          } else {
1407 1403
            _visitor->leave(s);
1408 1404
            _visitor->stop(s);
1409 1405
          }
1410 1406
        }
1411 1407
    }
1412 1408

	
1413 1409
    /// \brief Processes the next arc.
1414 1410
    ///
1415 1411
    /// Processes the next arc.
1416 1412
    ///
1417 1413
    /// \return The processed arc.
1418 1414
    ///
1419 1415
    /// \pre The stack must not be empty.
1420 1416
    Arc processNextArc() {
1421 1417
      Arc e = _stack[_stack_head];
1422 1418
      Node m = _digraph->target(e);
1423 1419
      if(!(*_reached)[m]) {
1424 1420
        _visitor->discover(e);
1425 1421
        _visitor->reach(m);
1426 1422
        _reached->set(m, true);
1427 1423
        _digraph->firstOut(_stack[++_stack_head], m);
1428 1424
      } else {
1429 1425
        _visitor->examine(e);
1430 1426
        m = _digraph->source(e);
1431 1427
        _digraph->nextOut(_stack[_stack_head]);
1432 1428
      }
1433 1429
      while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1434 1430
        _visitor->leave(m);
1435 1431
        --_stack_head;
1436 1432
        if (_stack_head >= 0) {
1437 1433
          _visitor->backtrack(_stack[_stack_head]);
1438 1434
          m = _digraph->source(_stack[_stack_head]);
1439 1435
          _digraph->nextOut(_stack[_stack_head]);
1440 1436
        } else {
1441 1437
          _visitor->stop(m);
1442 1438
        }
1443 1439
      }
1444 1440
      return e;
1445 1441
    }
1446 1442

	
1447 1443
    /// \brief Next arc to be processed.
1448 1444
    ///
1449 1445
    /// Next arc to be processed.
1450 1446
    ///
1451 1447
    /// \return The next arc to be processed or INVALID if the stack is
1452 1448
    /// empty.
1453 1449
    Arc nextArc() const {
1454 1450
      return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1455 1451
    }
1456 1452

	
1457 1453
    /// \brief Returns \c false if there are nodes
1458 1454
    /// to be processed.
1459 1455
    ///
1460 1456
    /// Returns \c false if there are nodes
1461 1457
    /// to be processed in the queue (stack).
1462 1458
    bool emptyQueue() const { return _stack_head < 0; }
1463 1459

	
1464 1460
    /// \brief Returns the number of the nodes to be processed.
1465 1461
    ///
1466 1462
    /// Returns the number of the nodes to be processed in the queue (stack).
1467 1463
    int queueSize() const { return _stack_head + 1; }
1468 1464

	
1469 1465
    /// \brief Executes the algorithm.
1470 1466
    ///
1471 1467
    /// Executes the algorithm.
1472 1468
    ///
1473 1469
    /// This method runs the %DFS algorithm from the root node
1474 1470
    /// in order to compute the %DFS path to each node.
1475 1471
    ///
1476 1472
    /// The algorithm computes
1477 1473
    /// - the %DFS tree,
1478 1474
    /// - the distance of each node from the root in the %DFS tree.
1479 1475
    ///
1480 1476
    /// \pre init() must be called and a root node should be
1481 1477
    /// added with addSource() before using this function.
1482 1478
    ///
1483 1479
    /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1484 1480
    /// \code
1485 1481
    ///   while ( !d.emptyQueue() ) {
1486 1482
    ///     d.processNextArc();
1487 1483
    ///   }
1488 1484
    /// \endcode
1489 1485
    void start() {
1490 1486
      while ( !emptyQueue() ) processNextArc();
1491 1487
    }
1492 1488

	
1493 1489
    /// \brief Executes the algorithm until the given target node is reached.
1494 1490
    ///
1495 1491
    /// Executes the algorithm until the given target node is reached.
1496 1492
    ///
1497 1493
    /// This method runs the %DFS algorithm from the root node
1498 1494
    /// in order to compute the DFS path to \c t.
1499 1495
    ///
1500 1496
    /// The algorithm computes
1501 1497
    /// - the %DFS path to \c t,
1502 1498
    /// - the distance of \c t from the root in the %DFS tree.
1503 1499
    ///
1504 1500
    /// \pre init() must be called and a root node should be added
1505 1501
    /// with addSource() before using this function.
1506 1502
    void start(Node t) {
1507 1503
      while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != t )
1508 1504
        processNextArc();
1509 1505
    }
1510 1506

	
1511 1507
    /// \brief Executes the algorithm until a condition is met.
1512 1508
    ///
1513 1509
    /// Executes the algorithm until a condition is met.
1514 1510
    ///
1515 1511
    /// This method runs the %DFS algorithm from the root node
1516 1512
    /// until an arc \c a with <tt>am[a]</tt> true is found.
1517 1513
    ///
1518 1514
    /// \param am A \c bool (or convertible) arc map. The algorithm
1519 1515
    /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1520 1516
    ///
1521 1517
    /// \return The reached arc \c a with <tt>am[a]</tt> true or
1522 1518
    /// \c INVALID if no such arc was found.
1523 1519
    ///
1524 1520
    /// \pre init() must be called and a root node should be added
1525 1521
    /// with addSource() before using this function.
1526 1522
    ///
1527 1523
    /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1528 1524
    /// not a node map.
1529 1525
    template <typename AM>
1530 1526
    Arc start(const AM &am) {
1531 1527
      while ( !emptyQueue() && !am[_stack[_stack_head]] )
1532 1528
        processNextArc();
1533 1529
      return emptyQueue() ? INVALID : _stack[_stack_head];
1534 1530
    }
1535 1531

	
1536 1532
    /// \brief Runs the algorithm from the given source node.
1537 1533
    ///
1538 1534
    /// This method runs the %DFS algorithm from node \c s.
1539 1535
    /// in order to compute the DFS path to each node.
1540 1536
    ///
1541 1537
    /// The algorithm computes
1542 1538
    /// - the %DFS tree,
1543 1539
    /// - the distance of each node from the root in the %DFS tree.
1544 1540
    ///
1545 1541
    /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1546 1542
    ///\code
1547 1543
    ///   d.init();
1548 1544
    ///   d.addSource(s);
1549 1545
    ///   d.start();
1550 1546
    ///\endcode
1551 1547
    void run(Node s) {
1552 1548
      init();
1553 1549
      addSource(s);
1554 1550
      start();
1555 1551
    }
1556 1552

	
1557 1553
    /// \brief Finds the %DFS path between \c s and \c t.
1558 1554

	
1559 1555
    /// This method runs the %DFS algorithm from node \c s
1560 1556
    /// in order to compute the DFS path to node \c t
1561 1557
    /// (it stops searching when \c t is processed).
1562 1558
    ///
1563 1559
    /// \return \c true if \c t is reachable form \c s.
1564 1560
    ///
1565 1561
    /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1566 1562
    /// just a shortcut of the following code.
1567 1563
    ///\code
1568 1564
    ///   d.init();
1569 1565
    ///   d.addSource(s);
1570 1566
    ///   d.start(t);
1571 1567
    ///\endcode
1572 1568
    bool run(Node s,Node t) {
1573 1569
      init();
1574 1570
      addSource(s);
1575 1571
      start(t);
1576 1572
      return reached(t);
1577 1573
    }
1578 1574

	
1579 1575
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1580 1576

	
1581
    /// This method runs the %DFS algorithm in order to
1582
    /// compute the %DFS path to each node.
1583
    ///
1584
    /// The algorithm computes
1585
    /// - the %DFS tree (forest),
1586
    /// - the distance of each node from the root(s) in the %DFS tree.
1577
    /// This method runs the %DFS algorithm in order to visit all nodes
1578
    /// in the digraph.
1587 1579
    ///
1588 1580
    /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1589 1581
    ///\code
1590 1582
    ///   d.init();
1591 1583
    ///   for (NodeIt n(digraph); n != INVALID; ++n) {
1592 1584
    ///     if (!d.reached(n)) {
1593 1585
    ///       d.addSource(n);
1594 1586
    ///       d.start();
1595 1587
    ///     }
1596 1588
    ///   }
1597 1589
    ///\endcode
1598 1590
    void run() {
1599 1591
      init();
1600 1592
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1601 1593
        if (!reached(it)) {
1602 1594
          addSource(it);
1603 1595
          start();
1604 1596
        }
1605 1597
      }
1606 1598
    }
1607 1599

	
1608 1600
    ///@}
1609 1601

	
1610 1602
    /// \name Query Functions
1611 1603
    /// The results of the DFS algorithm can be obtained using these
1612 1604
    /// functions.\n
1613 1605
    /// Either \ref run(Node) "run()" or \ref start() should be called
1614 1606
    /// before using them.
1615 1607

	
1616 1608
    ///@{
1617 1609

	
1618 1610
    /// \brief Checks if the given node is reached from the root(s).
1619 1611
    ///
1620 1612
    /// Returns \c true if \c v is reached from the root(s).
1621 1613
    ///
1622 1614
    /// \pre Either \ref run(Node) "run()" or \ref init()
1623 1615
    /// must be called before using this function.
1624 1616
    bool reached(Node v) const { return (*_reached)[v]; }
1625 1617

	
1626 1618
    ///@}
1627 1619

	
1628 1620
  };
1629 1621

	
1630 1622
} //END OF NAMESPACE LEMON
1631 1623

	
1632 1624
#endif
Ignore white space 768 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_DIJKSTRA_H
20 20
#define LEMON_DIJKSTRA_H
21 21

	
22 22
///\ingroup shortest_path
23 23
///\file
24 24
///\brief Dijkstra algorithm.
25 25

	
26 26
#include <limits>
27 27
#include <lemon/list_graph.h>
28 28
#include <lemon/bin_heap.h>
29 29
#include <lemon/bits/path_dump.h>
30 30
#include <lemon/core.h>
31 31
#include <lemon/error.h>
32 32
#include <lemon/maps.h>
33 33
#include <lemon/path.h>
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  /// \brief Default operation traits for the Dijkstra algorithm class.
38 38
  ///
39 39
  /// This operation traits class defines all computational operations and
40 40
  /// constants which are used in the Dijkstra algorithm.
41 41
  template <typename V>
42 42
  struct DijkstraDefaultOperationTraits {
43 43
    /// \e
44 44
    typedef V Value;
45 45
    /// \brief Gives back the zero value of the type.
46 46
    static Value zero() {
47 47
      return static_cast<Value>(0);
48 48
    }
49 49
    /// \brief Gives back the sum of the given two elements.
50 50
    static Value plus(const Value& left, const Value& right) {
51 51
      return left + right;
52 52
    }
53 53
    /// \brief Gives back true only if the first value is less than the second.
54 54
    static bool less(const Value& left, const Value& right) {
55 55
      return left < right;
56 56
    }
57 57
  };
58 58

	
59 59
  ///Default traits class of Dijkstra class.
60 60

	
61 61
  ///Default traits class of Dijkstra class.
62 62
  ///\tparam GR The type of the digraph.
63 63
  ///\tparam LEN The type of the length map.
64 64
  template<typename GR, typename LEN>
65 65
  struct DijkstraDefaultTraits
66 66
  {
67 67
    ///The type of the digraph the algorithm runs on.
68 68
    typedef GR Digraph;
69 69

	
70 70
    ///The type of the map that stores the arc lengths.
71 71

	
72 72
    ///The type of the map that stores the arc lengths.
73 73
    ///It must conform to the \ref concepts::ReadMap "ReadMap" concept.
74 74
    typedef LEN LengthMap;
75 75
    ///The type of the arc lengths.
76 76
    typedef typename LEN::Value Value;
77 77

	
78 78
    /// Operation traits for %Dijkstra algorithm.
79 79

	
80 80
    /// This class defines the operations that are used in the algorithm.
81 81
    /// \see DijkstraDefaultOperationTraits
82 82
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
83 83

	
84 84
    /// The cross reference type used by the heap.
85 85

	
86 86
    /// The cross reference type used by the heap.
87 87
    /// Usually it is \c Digraph::NodeMap<int>.
88 88
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
89 89
    ///Instantiates a \c HeapCrossRef.
90 90

	
91 91
    ///This function instantiates a \ref HeapCrossRef.
92 92
    /// \param g is the digraph, to which we would like to define the
93 93
    /// \ref HeapCrossRef.
94 94
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
95 95
    {
96 96
      return new HeapCrossRef(g);
97 97
    }
98 98

	
99 99
    ///The heap type used by the %Dijkstra algorithm.
100 100

	
101 101
    ///The heap type used by the Dijkstra algorithm.
102 102
    ///
103 103
    ///\sa BinHeap
104 104
    ///\sa Dijkstra
105 105
    typedef BinHeap<typename LEN::Value, HeapCrossRef, std::less<Value> > Heap;
106 106
    ///Instantiates a \c Heap.
107 107

	
108 108
    ///This function instantiates a \ref Heap.
109 109
    static Heap *createHeap(HeapCrossRef& r)
110 110
    {
111 111
      return new Heap(r);
112 112
    }
113 113

	
114 114
    ///\brief The type of the map that stores the predecessor
115 115
    ///arcs of the shortest paths.
116 116
    ///
117 117
    ///The type of the map that stores the predecessor
118 118
    ///arcs of the shortest paths.
119 119
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
120 120
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
121 121
    ///Instantiates a \c PredMap.
122 122

	
123 123
    ///This function instantiates a \ref PredMap.
124 124
    ///\param g is the digraph, to which we would like to define the
125 125
    ///\ref PredMap.
126 126
    static PredMap *createPredMap(const Digraph &g)
127 127
    {
128 128
      return new PredMap(g);
129 129
    }
130 130

	
131 131
    ///The type of the map that indicates which nodes are processed.
132 132

	
133 133
    ///The type of the map that indicates which nodes are processed.
134 134
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
135 135
    ///By default it is a NullMap.
136 136
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
137 137
    ///Instantiates a \c ProcessedMap.
138 138

	
139 139
    ///This function instantiates a \ref ProcessedMap.
140 140
    ///\param g is the digraph, to which
141 141
    ///we would like to define the \ref ProcessedMap.
142 142
#ifdef DOXYGEN
143 143
    static ProcessedMap *createProcessedMap(const Digraph &g)
144 144
#else
145 145
    static ProcessedMap *createProcessedMap(const Digraph &)
146 146
#endif
147 147
    {
148 148
      return new ProcessedMap();
149 149
    }
150 150

	
151 151
    ///The type of the map that stores the distances of the nodes.
152 152

	
153 153
    ///The type of the map that stores the distances of the nodes.
154 154
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
155 155
    typedef typename Digraph::template NodeMap<typename LEN::Value> DistMap;
156 156
    ///Instantiates a \c DistMap.
157 157

	
158 158
    ///This function instantiates a \ref DistMap.
159 159
    ///\param g is the digraph, to which we would like to define
160 160
    ///the \ref DistMap.
161 161
    static DistMap *createDistMap(const Digraph &g)
162 162
    {
163 163
      return new DistMap(g);
164 164
    }
165 165
  };
166 166

	
167 167
  ///%Dijkstra algorithm class.
168 168

	
169 169
  /// \ingroup shortest_path
170 170
  ///This class provides an efficient implementation of the %Dijkstra algorithm.
171 171
  ///
172 172
  ///The %Dijkstra algorithm solves the single-source shortest path problem
173 173
  ///when all arc lengths are non-negative. If there are negative lengths,
174 174
  ///the BellmanFord algorithm should be used instead.
175 175
  ///
176 176
  ///The arc lengths are passed to the algorithm using a
177 177
  ///\ref concepts::ReadMap "ReadMap",
178 178
  ///so it is easy to change it to any kind of length.
179 179
  ///The type of the length is determined by the
180 180
  ///\ref concepts::ReadMap::Value "Value" of the length map.
181 181
  ///It is also possible to change the underlying priority heap.
182 182
  ///
183 183
  ///There is also a \ref dijkstra() "function-type interface" for the
184 184
  ///%Dijkstra algorithm, which is convenient in the simplier cases and
185 185
  ///it can be used easier.
186 186
  ///
187 187
  ///\tparam GR The type of the digraph the algorithm runs on.
188 188
  ///The default type is \ref ListDigraph.
189 189
  ///\tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
190 190
  ///the lengths of the arcs.
191 191
  ///It is read once for each arc, so the map may involve in
192 192
  ///relatively time consuming process to compute the arc lengths if
193 193
  ///it is necessary. The default map type is \ref
194 194
  ///concepts::Digraph::ArcMap "GR::ArcMap<int>".
195 195
#ifdef DOXYGEN
196 196
  template <typename GR, typename LEN, typename TR>
197 197
#else
198 198
  template <typename GR=ListDigraph,
199 199
            typename LEN=typename GR::template ArcMap<int>,
200 200
            typename TR=DijkstraDefaultTraits<GR,LEN> >
201 201
#endif
202 202
  class Dijkstra {
203 203
  public:
204 204

	
205 205
    ///The type of the digraph the algorithm runs on.
206 206
    typedef typename TR::Digraph Digraph;
207 207

	
208 208
    ///The type of the arc lengths.
209
    typedef typename TR::LengthMap::Value Value;
209
    typedef typename TR::Value Value;
210 210
    ///The type of the map that stores the arc lengths.
211 211
    typedef typename TR::LengthMap LengthMap;
212 212
    ///\brief The type of the map that stores the predecessor arcs of the
213 213
    ///shortest paths.
214 214
    typedef typename TR::PredMap PredMap;
215 215
    ///The type of the map that stores the distances of the nodes.
216 216
    typedef typename TR::DistMap DistMap;
217 217
    ///The type of the map that indicates which nodes are processed.
218 218
    typedef typename TR::ProcessedMap ProcessedMap;
219 219
    ///The type of the paths.
220 220
    typedef PredMapPath<Digraph, PredMap> Path;
221 221
    ///The cross reference type used for the current heap.
222 222
    typedef typename TR::HeapCrossRef HeapCrossRef;
223 223
    ///The heap type used by the algorithm.
224 224
    typedef typename TR::Heap Heap;
225 225
    ///\brief The \ref DijkstraDefaultOperationTraits "operation traits class"
226 226
    ///of the algorithm.
227 227
    typedef typename TR::OperationTraits OperationTraits;
228 228

	
229 229
    ///The \ref DijkstraDefaultTraits "traits class" of the algorithm.
230 230
    typedef TR Traits;
231 231

	
232 232
  private:
233 233

	
234 234
    typedef typename Digraph::Node Node;
235 235
    typedef typename Digraph::NodeIt NodeIt;
236 236
    typedef typename Digraph::Arc Arc;
237 237
    typedef typename Digraph::OutArcIt OutArcIt;
238 238

	
239 239
    //Pointer to the underlying digraph.
240 240
    const Digraph *G;
241 241
    //Pointer to the length map.
242 242
    const LengthMap *_length;
243 243
    //Pointer to the map of predecessors arcs.
244 244
    PredMap *_pred;
245 245
    //Indicates if _pred is locally allocated (true) or not.
246 246
    bool local_pred;
247 247
    //Pointer to the map of distances.
248 248
    DistMap *_dist;
249 249
    //Indicates if _dist is locally allocated (true) or not.
250 250
    bool local_dist;
251 251
    //Pointer to the map of processed status of the nodes.
252 252
    ProcessedMap *_processed;
253 253
    //Indicates if _processed is locally allocated (true) or not.
254 254
    bool local_processed;
255 255
    //Pointer to the heap cross references.
256 256
    HeapCrossRef *_heap_cross_ref;
257 257
    //Indicates if _heap_cross_ref is locally allocated (true) or not.
258 258
    bool local_heap_cross_ref;
259 259
    //Pointer to the heap.
260 260
    Heap *_heap;
261 261
    //Indicates if _heap is locally allocated (true) or not.
262 262
    bool local_heap;
263 263

	
264 264
    //Creates the maps if necessary.
265 265
    void create_maps()
266 266
    {
267 267
      if(!_pred) {
268 268
        local_pred = true;
269 269
        _pred = Traits::createPredMap(*G);
270 270
      }
271 271
      if(!_dist) {
272 272
        local_dist = true;
273 273
        _dist = Traits::createDistMap(*G);
274 274
      }
275 275
      if(!_processed) {
276 276
        local_processed = true;
277 277
        _processed = Traits::createProcessedMap(*G);
278 278
      }
279 279
      if (!_heap_cross_ref) {
280 280
        local_heap_cross_ref = true;
281 281
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
282 282
      }
283 283
      if (!_heap) {
284 284
        local_heap = true;
285 285
        _heap = Traits::createHeap(*_heap_cross_ref);
286 286
      }
287 287
    }
288 288

	
289 289
  public:
290 290

	
291 291
    typedef Dijkstra Create;
292 292

	
293 293
    ///\name Named Template Parameters
294 294

	
295 295
    ///@{
296 296

	
297 297
    template <class T>
298 298
    struct SetPredMapTraits : public Traits {
299 299
      typedef T PredMap;
300 300
      static PredMap *createPredMap(const Digraph &)
301 301
      {
302 302
        LEMON_ASSERT(false, "PredMap is not initialized");
303 303
        return 0; // ignore warnings
304 304
      }
305 305
    };
306 306
    ///\brief \ref named-templ-param "Named parameter" for setting
307 307
    ///\c PredMap type.
308 308
    ///
309 309
    ///\ref named-templ-param "Named parameter" for setting
310 310
    ///\c PredMap type.
311 311
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
312 312
    template <class T>
313 313
    struct SetPredMap
314 314
      : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
315 315
      typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
316 316
    };
317 317

	
318 318
    template <class T>
319 319
    struct SetDistMapTraits : public Traits {
320 320
      typedef T DistMap;
321 321
      static DistMap *createDistMap(const Digraph &)
322 322
      {
323 323
        LEMON_ASSERT(false, "DistMap is not initialized");
324 324
        return 0; // ignore warnings
325 325
      }
326 326
    };
327 327
    ///\brief \ref named-templ-param "Named parameter" for setting
328 328
    ///\c DistMap type.
329 329
    ///
330 330
    ///\ref named-templ-param "Named parameter" for setting
331 331
    ///\c DistMap type.
332 332
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
333 333
    template <class T>
334 334
    struct SetDistMap
335 335
      : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
336 336
      typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
337 337
    };
338 338

	
339 339
    template <class T>
340 340
    struct SetProcessedMapTraits : public Traits {
341 341
      typedef T ProcessedMap;
342 342
      static ProcessedMap *createProcessedMap(const Digraph &)
343 343
      {
344 344
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
345 345
        return 0; // ignore warnings
346 346
      }
347 347
    };
348 348
    ///\brief \ref named-templ-param "Named parameter" for setting
349 349
    ///\c ProcessedMap type.
350 350
    ///
351 351
    ///\ref named-templ-param "Named parameter" for setting
352 352
    ///\c ProcessedMap type.
353 353
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
354 354
    template <class T>
355 355
    struct SetProcessedMap
356 356
      : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
357 357
      typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
358 358
    };
359 359

	
360 360
    struct SetStandardProcessedMapTraits : public Traits {
361 361
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
362 362
      static ProcessedMap *createProcessedMap(const Digraph &g)
363 363
      {
364 364
        return new ProcessedMap(g);
365 365
      }
366 366
    };
367 367
    ///\brief \ref named-templ-param "Named parameter" for setting
368 368
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
369 369
    ///
370 370
    ///\ref named-templ-param "Named parameter" for setting
371 371
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
372 372
    ///If you don't set it explicitly, it will be automatically allocated.
373 373
    struct SetStandardProcessedMap
374 374
      : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
375 375
      typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
376 376
      Create;
377 377
    };
378 378

	
379 379
    template <class H, class CR>
380 380
    struct SetHeapTraits : public Traits {
381 381
      typedef CR HeapCrossRef;
382 382
      typedef H Heap;
383 383
      static HeapCrossRef *createHeapCrossRef(const Digraph &) {
384 384
        LEMON_ASSERT(false, "HeapCrossRef is not initialized");
385 385
        return 0; // ignore warnings
386 386
      }
387 387
      static Heap *createHeap(HeapCrossRef &)
388 388
      {
389 389
        LEMON_ASSERT(false, "Heap is not initialized");
390 390
        return 0; // ignore warnings
391 391
      }
392 392
    };
393 393
    ///\brief \ref named-templ-param "Named parameter" for setting
394 394
    ///heap and cross reference types
395 395
    ///
396 396
    ///\ref named-templ-param "Named parameter" for setting heap and cross
397 397
    ///reference types. If this named parameter is used, then external
398 398
    ///heap and cross reference objects must be passed to the algorithm
399 399
    ///using the \ref heap() function before calling \ref run(Node) "run()"
400 400
    ///or \ref init().
401 401
    ///\sa SetStandardHeap
402 402
    template <class H, class CR = typename Digraph::template NodeMap<int> >
403 403
    struct SetHeap
404 404
      : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
405 405
      typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
406 406
    };
407 407

	
408 408
    template <class H, class CR>
409 409
    struct SetStandardHeapTraits : public Traits {
410 410
      typedef CR HeapCrossRef;
411 411
      typedef H Heap;
412 412
      static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
413 413
        return new HeapCrossRef(G);
414 414
      }
415 415
      static Heap *createHeap(HeapCrossRef &R)
416 416
      {
417 417
        return new Heap(R);
418 418
      }
419 419
    };
420 420
    ///\brief \ref named-templ-param "Named parameter" for setting
421 421
    ///heap and cross reference types with automatic allocation
422 422
    ///
423 423
    ///\ref named-templ-param "Named parameter" for setting heap and cross
424 424
    ///reference types with automatic allocation.
425 425
    ///They should have standard constructor interfaces to be able to
426 426
    ///automatically created by the algorithm (i.e. the digraph should be
427 427
    ///passed to the constructor of the cross reference and the cross
428 428
    ///reference should be passed to the constructor of the heap).
429 429
    ///However external heap and cross reference objects could also be
430 430
    ///passed to the algorithm using the \ref heap() function before
431 431
    ///calling \ref run(Node) "run()" or \ref init().
432 432
    ///\sa SetHeap
433 433
    template <class H, class CR = typename Digraph::template NodeMap<int> >
434 434
    struct SetStandardHeap
435 435
      : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
436 436
      typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
437 437
      Create;
438 438
    };
439 439

	
440 440
    template <class T>
441 441
    struct SetOperationTraitsTraits : public Traits {
442 442
      typedef T OperationTraits;
443 443
    };
444 444

	
445 445
    /// \brief \ref named-templ-param "Named parameter" for setting
446 446
    ///\c OperationTraits type
447 447
    ///
448 448
    ///\ref named-templ-param "Named parameter" for setting
449 449
    ///\c OperationTraits type.
450 450
    /// For more information see \ref DijkstraDefaultOperationTraits.
451 451
    template <class T>
452 452
    struct SetOperationTraits
453 453
      : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
454 454
      typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
455 455
      Create;
456 456
    };
457 457

	
458 458
    ///@}
459 459

	
460 460
  protected:
461 461

	
462 462
    Dijkstra() {}
463 463

	
464 464
  public:
465 465

	
466 466
    ///Constructor.
467 467

	
468 468
    ///Constructor.
469 469
    ///\param g The digraph the algorithm runs on.
470 470
    ///\param length The length map used by the algorithm.
471 471
    Dijkstra(const Digraph& g, const LengthMap& length) :
472 472
      G(&g), _length(&length),
473 473
      _pred(NULL), local_pred(false),
474 474
      _dist(NULL), local_dist(false),
475 475
      _processed(NULL), local_processed(false),
476 476
      _heap_cross_ref(NULL), local_heap_cross_ref(false),
477 477
      _heap(NULL), local_heap(false)
478 478
    { }
479 479

	
480 480
    ///Destructor.
481 481
    ~Dijkstra()
482 482
    {
483 483
      if(local_pred) delete _pred;
484 484
      if(local_dist) delete _dist;
485 485
      if(local_processed) delete _processed;
486 486
      if(local_heap_cross_ref) delete _heap_cross_ref;
487 487
      if(local_heap) delete _heap;
488 488
    }
489 489

	
490 490
    ///Sets the length map.
491 491

	
492 492
    ///Sets the length map.
493 493
    ///\return <tt> (*this) </tt>
494 494
    Dijkstra &lengthMap(const LengthMap &m)
495 495
    {
496 496
      _length = &m;
497 497
      return *this;
498 498
    }
499 499

	
500 500
    ///Sets the map that stores the predecessor arcs.
501 501

	
502 502
    ///Sets the map that stores the predecessor arcs.
503 503
    ///If you don't use this function before calling \ref run(Node) "run()"
504 504
    ///or \ref init(), an instance will be allocated automatically.
505 505
    ///The destructor deallocates this automatically allocated map,
506 506
    ///of course.
507 507
    ///\return <tt> (*this) </tt>
508 508
    Dijkstra &predMap(PredMap &m)
509 509
    {
510 510
      if(local_pred) {
511 511
        delete _pred;
512 512
        local_pred=false;
513 513
      }
514 514
      _pred = &m;
515 515
      return *this;
516 516
    }
517 517

	
518 518
    ///Sets the map that indicates which nodes are processed.
519 519

	
520 520
    ///Sets the map that indicates which nodes are processed.
521 521
    ///If you don't use this function before calling \ref run(Node) "run()"
522 522
    ///or \ref init(), an instance will be allocated automatically.
523 523
    ///The destructor deallocates this automatically allocated map,
524 524
    ///of course.
525 525
    ///\return <tt> (*this) </tt>
526 526
    Dijkstra &processedMap(ProcessedMap &m)
527 527
    {
528 528
      if(local_processed) {
529 529
        delete _processed;
530 530
        local_processed=false;
531 531
      }
532 532
      _processed = &m;
533 533
      return *this;
534 534
    }
535 535

	
536 536
    ///Sets the map that stores the distances of the nodes.
537 537

	
538 538
    ///Sets the map that stores the distances of the nodes calculated by the
539 539
    ///algorithm.
540 540
    ///If you don't use this function before calling \ref run(Node) "run()"
541 541
    ///or \ref init(), an instance will be allocated automatically.
542 542
    ///The destructor deallocates this automatically allocated map,
543 543
    ///of course.
544 544
    ///\return <tt> (*this) </tt>
545 545
    Dijkstra &distMap(DistMap &m)
546 546
    {
547 547
      if(local_dist) {
548 548
        delete _dist;
549 549
        local_dist=false;
550 550
      }
551 551
      _dist = &m;
552 552
      return *this;
553 553
    }
554 554

	
555 555
    ///Sets the heap and the cross reference used by algorithm.
556 556

	
557 557
    ///Sets the heap and the cross reference used by algorithm.
558 558
    ///If you don't use this function before calling \ref run(Node) "run()"
559 559
    ///or \ref init(), heap and cross reference instances will be
560 560
    ///allocated automatically.
561 561
    ///The destructor deallocates these automatically allocated objects,
562 562
    ///of course.
563 563
    ///\return <tt> (*this) </tt>
564 564
    Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
565 565
    {
566 566
      if(local_heap_cross_ref) {
567 567
        delete _heap_cross_ref;
568 568
        local_heap_cross_ref=false;
569 569
      }
570 570
      _heap_cross_ref = &cr;
571 571
      if(local_heap) {
572 572
        delete _heap;
573 573
        local_heap=false;
574 574
      }
575 575
      _heap = &hp;
576 576
      return *this;
577 577
    }
578 578

	
579 579
  private:
580 580

	
581 581
    void finalizeNodeData(Node v,Value dst)
582 582
    {
583 583
      _processed->set(v,true);
584 584
      _dist->set(v, dst);
585 585
    }
586 586

	
587 587
  public:
588 588

	
589 589
    ///\name Execution Control
590 590
    ///The simplest way to execute the %Dijkstra algorithm is to use
591 591
    ///one of the member functions called \ref run(Node) "run()".\n
592 592
    ///If you need better control on the execution, you have to call
593 593
    ///\ref init() first, then you can add several source nodes with
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-2008
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_EDGE_SET_H
20 20
#define LEMON_EDGE_SET_H
21 21

	
22 22
#include <lemon/core.h>
23 23
#include <lemon/bits/edge_set_extender.h>
24 24

	
25 25
/// \ingroup graphs
26 26
/// \file
27 27
/// \brief ArcSet and EdgeSet classes.
28 28
///
29 29
/// Graphs which use another graph's node-set as own.
30 30
namespace lemon {
31 31

	
32 32
  template <typename GR>
33 33
  class ListArcSetBase {
34 34
  public:
35 35

	
36 36
    typedef typename GR::Node Node;
37 37
    typedef typename GR::NodeIt NodeIt;
38 38

	
39 39
  protected:
40 40

	
41 41
    struct NodeT {
42 42
      int first_out, first_in;
43 43
      NodeT() : first_out(-1), first_in(-1) {}
44 44
    };
45 45

	
46 46
    typedef typename ItemSetTraits<GR, Node>::
47 47
    template Map<NodeT>::Type NodesImplBase;
48 48

	
49 49
    NodesImplBase* _nodes;
50 50

	
51 51
    struct ArcT {
52 52
      Node source, target;
53 53
      int next_out, next_in;
54 54
      int prev_out, prev_in;
55 55
      ArcT() : prev_out(-1), prev_in(-1) {}
56 56
    };
57 57

	
58 58
    std::vector<ArcT> arcs;
59 59

	
60 60
    int first_arc;
61 61
    int first_free_arc;
62 62

	
63 63
    const GR* _graph;
64 64

	
65 65
    void initalize(const GR& graph, NodesImplBase& nodes) {
66 66
      _graph = &graph;
67 67
      _nodes = &nodes;
68 68
    }
69 69

	
70 70
  public:
71 71

	
72 72
    class Arc {
73 73
      friend class ListArcSetBase<GR>;
74 74
    protected:
75 75
      Arc(int _id) : id(_id) {}
76 76
      int id;
77 77
    public:
78 78
      Arc() {}
79 79
      Arc(Invalid) : id(-1) {}
80 80
      bool operator==(const Arc& arc) const { return id == arc.id; }
81 81
      bool operator!=(const Arc& arc) const { return id != arc.id; }
82 82
      bool operator<(const Arc& arc) const { return id < arc.id; }
83 83
    };
84 84

	
85 85
    ListArcSetBase() : first_arc(-1), first_free_arc(-1) {}
86 86

	
87 87
    Node addNode() {
88 88
      LEMON_ASSERT(false,
89 89
        "This graph structure does not support node insertion");
90 90
      return INVALID; // avoid warning
91 91
    }
92 92

	
93 93
    Arc addArc(const Node& u, const Node& v) {
94 94
      int n;
95 95
      if (first_free_arc == -1) {
96 96
        n = arcs.size();
97 97
        arcs.push_back(ArcT());
98 98
      } else {
99 99
        n = first_free_arc;
100 100
        first_free_arc = arcs[first_free_arc].next_in;
101 101
      }
102 102
      arcs[n].next_in = (*_nodes)[v].first_in;
103 103
      if ((*_nodes)[v].first_in != -1) {
104 104
        arcs[(*_nodes)[v].first_in].prev_in = n;
105 105
      }
106 106
      (*_nodes)[v].first_in = n;
107 107
      arcs[n].next_out = (*_nodes)[u].first_out;
108 108
      if ((*_nodes)[u].first_out != -1) {
109 109
        arcs[(*_nodes)[u].first_out].prev_out = n;
110 110
      }
111 111
      (*_nodes)[u].first_out = n;
112 112
      arcs[n].source = u;
113 113
      arcs[n].target = v;
114 114
      return Arc(n);
115 115
    }
116 116

	
117 117
    void erase(const Arc& arc) {
118 118
      int n = arc.id;
119 119
      if (arcs[n].prev_in != -1) {
120 120
        arcs[arcs[n].prev_in].next_in = arcs[n].next_in;
121 121
      } else {
122 122
        (*_nodes)[arcs[n].target].first_in = arcs[n].next_in;
123 123
      }
124 124
      if (arcs[n].next_in != -1) {
125 125
        arcs[arcs[n].next_in].prev_in = arcs[n].prev_in;
126 126
      }
127 127

	
128 128
      if (arcs[n].prev_out != -1) {
129 129
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
130 130
      } else {
131 131
        (*_nodes)[arcs[n].source].first_out = arcs[n].next_out;
132 132
      }
133 133
      if (arcs[n].next_out != -1) {
134 134
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
135 135
      }
136 136

	
137 137
    }
138 138

	
139 139
    void clear() {
140 140
      Node node;
141 141
      for (first(node); node != INVALID; next(node)) {
142 142
        (*_nodes)[node].first_in = -1;
143 143
        (*_nodes)[node].first_out = -1;
144 144
      }
145 145
      arcs.clear();
146 146
      first_arc = -1;
147 147
      first_free_arc = -1;
148 148
    }
149 149

	
150 150
    void first(Node& node) const {
151 151
      _graph->first(node);
152 152
    }
153 153

	
154 154
    void next(Node& node) const {
155 155
      _graph->next(node);
156 156
    }
157 157

	
158 158
    void first(Arc& arc) const {
159 159
      Node node;
160 160
      first(node);
161 161
      while (node != INVALID && (*_nodes)[node].first_in == -1) {
162 162
        next(node);
163 163
      }
164 164
      arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_in;
165 165
    }
166 166

	
167 167
    void next(Arc& arc) const {
168 168
      if (arcs[arc.id].next_in != -1) {
169 169
        arc.id = arcs[arc.id].next_in;
170 170
      } else {
171 171
        Node node = arcs[arc.id].target;
172 172
        next(node);
173 173
        while (node != INVALID && (*_nodes)[node].first_in == -1) {
174 174
          next(node);
175 175
        }
176 176
        arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_in;
177 177
      }
178 178
    }
179 179

	
180 180
    void firstOut(Arc& arc, const Node& node) const {
181 181
      arc.id = (*_nodes)[node].first_out;
182 182
    }
183 183

	
184 184
    void nextOut(Arc& arc) const {
185 185
      arc.id = arcs[arc.id].next_out;
186 186
    }
187 187

	
188 188
    void firstIn(Arc& arc, const Node& node) const {
189 189
      arc.id = (*_nodes)[node].first_in;
190 190
    }
191 191

	
192 192
    void nextIn(Arc& arc) const {
193 193
      arc.id = arcs[arc.id].next_in;
194 194
    }
195 195

	
196 196
    int id(const Node& node) const { return _graph->id(node); }
197 197
    int id(const Arc& arc) const { return arc.id; }
198 198

	
199 199
    Node nodeFromId(int ix) const { return _graph->nodeFromId(ix); }
200 200
    Arc arcFromId(int ix) const { return Arc(ix); }
201 201

	
202 202
    int maxNodeId() const { return _graph->maxNodeId(); };
203 203
    int maxArcId() const { return arcs.size() - 1; }
204 204

	
205 205
    Node source(const Arc& arc) const { return arcs[arc.id].source;}
206 206
    Node target(const Arc& arc) const { return arcs[arc.id].target;}
207 207

	
208 208
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
209 209

	
210 210
    NodeNotifier& notifier(Node) const {
211 211
      return _graph->notifier(Node());
212 212
    }
213 213

	
214 214
    template <typename V>
215 215
    class NodeMap : public GR::template NodeMap<V> {
216 216
      typedef typename GR::template NodeMap<V> Parent;
217 217

	
218 218
    public:
219 219

	
220 220
      explicit NodeMap(const ListArcSetBase<GR>& arcset)
221 221
        : Parent(*arcset._graph) {}
222 222

	
223 223
      NodeMap(const ListArcSetBase<GR>& arcset, const V& value)
224 224
        : Parent(*arcset._graph, value) {}
225 225

	
226 226
      NodeMap& operator=(const NodeMap& cmap) {
227 227
        return operator=<NodeMap>(cmap);
228 228
      }
229 229

	
230 230
      template <typename CMap>
231 231
      NodeMap& operator=(const CMap& cmap) {
232 232
        Parent::operator=(cmap);
233 233
        return *this;
234 234
      }
235 235
    };
236 236

	
237 237
  };
238 238

	
239 239
  /// \ingroup graphs
240 240
  ///
241 241
  /// \brief Digraph using a node set of another digraph or graph and
242 242
  /// an own arc set.
243 243
  ///
244 244
  /// This structure can be used to establish another directed graph
245 245
  /// over a node set of an existing one. This class uses the same
246 246
  /// Node type as the underlying graph, and each valid node of the
247 247
  /// original graph is valid in this arc set, therefore the node
248 248
  /// objects of the original graph can be used directly with this
249 249
  /// class. The node handling functions (id handling, observing, and
250 250
  /// iterators) works equivalently as in the original graph.
251 251
  ///
252 252
  /// This implementation is based on doubly-linked lists, from each
253 253
  /// node the outgoing and the incoming arcs make up lists, therefore
254 254
  /// one arc can be erased in constant time. It also makes possible,
255 255
  /// that node can be removed from the underlying graph, in this case
256 256
  /// all arcs incident to the given node is erased from the arc set.
257 257
  ///
258
  /// This class fully conforms to the \ref concepts::Digraph
259
  /// "Digraph" concept.
260
  /// It provides only linear time counting for nodes and arcs.
261
  ///
258 262
  /// \param GR The type of the graph which shares its node set with
259 263
  /// this class. Its interface must conform to the
260 264
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
261 265
  /// concept.
262
  ///
263
  /// This class fully conforms to the \ref concepts::Digraph
264
  /// "Digraph" concept.
265 266
  template <typename GR>
266 267
  class ListArcSet : public ArcSetExtender<ListArcSetBase<GR> > {
267 268
    typedef ArcSetExtender<ListArcSetBase<GR> > Parent;
268 269

	
269 270
  public:
270 271

	
271 272
    typedef typename Parent::Node Node;
272 273
    typedef typename Parent::Arc Arc;
273 274

	
274 275
    typedef typename Parent::NodesImplBase NodesImplBase;
275 276

	
276 277
    void eraseNode(const Node& node) {
277 278
      Arc arc;
278 279
      Parent::firstOut(arc, node);
279 280
      while (arc != INVALID ) {
280 281
        erase(arc);
281 282
        Parent::firstOut(arc, node);
282 283
      }
283 284

	
284 285
      Parent::firstIn(arc, node);
285 286
      while (arc != INVALID ) {
286 287
        erase(arc);
287 288
        Parent::firstIn(arc, node);
288 289
      }
289 290
    }
290 291

	
291 292
    void clearNodes() {
292 293
      Parent::clear();
293 294
    }
294 295

	
295 296
    class NodesImpl : public NodesImplBase {
296 297
      typedef NodesImplBase Parent;
297 298

	
298 299
    public:
299 300
      NodesImpl(const GR& graph, ListArcSet& arcset)
300 301
        : Parent(graph), _arcset(arcset) {}
301 302

	
302 303
      virtual ~NodesImpl() {}
303 304

	
304 305
    protected:
305 306

	
306 307
      virtual void erase(const Node& node) {
307 308
        _arcset.eraseNode(node);
308 309
        Parent::erase(node);
309 310
      }
310 311
      virtual void erase(const std::vector<Node>& nodes) {
311 312
        for (int i = 0; i < int(nodes.size()); ++i) {
312 313
          _arcset.eraseNode(nodes[i]);
313 314
        }
314 315
        Parent::erase(nodes);
315 316
      }
316 317
      virtual void clear() {
317 318
        _arcset.clearNodes();
318 319
        Parent::clear();
319 320
      }
320 321

	
321 322
    private:
322 323
      ListArcSet& _arcset;
323 324
    };
324 325

	
325 326
    NodesImpl _nodes;
326 327

	
327 328
  public:
328 329

	
329 330
    /// \brief Constructor of the ArcSet.
330 331
    ///
331 332
    /// Constructor of the ArcSet.
332 333
    ListArcSet(const GR& graph) : _nodes(graph, *this) {
333 334
      Parent::initalize(graph, _nodes);
334 335
    }
335 336

	
336 337
    /// \brief Add a new arc to the digraph.
337 338
    ///
338 339
    /// Add a new arc to the digraph with source node \c s
339 340
    /// and target node \c t.
340 341
    /// \return The new arc.
341 342
    Arc addArc(const Node& s, const Node& t) {
342 343
      return Parent::addArc(s, t);
343 344
    }
344 345

	
345 346
    /// \brief Erase an arc from the digraph.
346 347
    ///
347 348
    /// Erase an arc \c a from the digraph.
348 349
    void erase(const Arc& a) {
349 350
      return Parent::erase(a);
350 351
    }
351 352

	
352 353
  };
353 354

	
354 355
  template <typename GR>
355 356
  class ListEdgeSetBase {
356 357
  public:
357 358

	
358 359
    typedef typename GR::Node Node;
359 360
    typedef typename GR::NodeIt NodeIt;
360 361

	
361 362
  protected:
362 363

	
363 364
    struct NodeT {
364 365
      int first_out;
365 366
      NodeT() : first_out(-1) {}
366 367
    };
367 368

	
368 369
    typedef typename ItemSetTraits<GR, Node>::
369 370
    template Map<NodeT>::Type NodesImplBase;
370 371

	
371 372
    NodesImplBase* _nodes;
372 373

	
373 374
    struct ArcT {
374 375
      Node target;
375 376
      int prev_out, next_out;
376 377
      ArcT() : prev_out(-1), next_out(-1) {}
377 378
    };
378 379

	
379 380
    std::vector<ArcT> arcs;
380 381

	
381 382
    int first_arc;
382 383
    int first_free_arc;
383 384

	
384 385
    const GR* _graph;
385 386

	
386 387
    void initalize(const GR& graph, NodesImplBase& nodes) {
387 388
      _graph = &graph;
388 389
      _nodes = &nodes;
389 390
    }
390 391

	
391 392
  public:
392 393

	
393 394
    class Edge {
394 395
      friend class ListEdgeSetBase;
395 396
    protected:
396 397

	
397 398
      int id;
398 399
      explicit Edge(int _id) { id = _id;}
399 400

	
400 401
    public:
401 402
      Edge() {}
402 403
      Edge (Invalid) { id = -1; }
403 404
      bool operator==(const Edge& arc) const {return id == arc.id;}
404 405
      bool operator!=(const Edge& arc) const {return id != arc.id;}
405 406
      bool operator<(const Edge& arc) const {return id < arc.id;}
406 407
    };
407 408

	
408 409
    class Arc {
409 410
      friend class ListEdgeSetBase;
410 411
    protected:
411 412
      Arc(int _id) : id(_id) {}
412 413
      int id;
413 414
    public:
414 415
      operator Edge() const { return edgeFromId(id / 2); }
415 416

	
416 417
      Arc() {}
417 418
      Arc(Invalid) : id(-1) {}
418 419
      bool operator==(const Arc& arc) const { return id == arc.id; }
419 420
      bool operator!=(const Arc& arc) const { return id != arc.id; }
420 421
      bool operator<(const Arc& arc) const { return id < arc.id; }
421 422
    };
422 423

	
423 424
    ListEdgeSetBase() : first_arc(-1), first_free_arc(-1) {}
424 425

	
425 426
    Node addNode() {
426 427
      LEMON_ASSERT(false,
427 428
        "This graph structure does not support node insertion");
428 429
      return INVALID; // avoid warning
429 430
    }
430 431

	
431 432
    Edge addEdge(const Node& u, const Node& v) {
432 433
      int n;
433 434

	
434 435
      if (first_free_arc == -1) {
435 436
        n = arcs.size();
436 437
        arcs.push_back(ArcT());
437 438
        arcs.push_back(ArcT());
438 439
      } else {
439 440
        n = first_free_arc;
440 441
        first_free_arc = arcs[n].next_out;
441 442
      }
442 443

	
443 444
      arcs[n].target = u;
444 445
      arcs[n | 1].target = v;
445 446

	
446 447
      arcs[n].next_out = (*_nodes)[v].first_out;
447 448
      if ((*_nodes)[v].first_out != -1) {
448 449
        arcs[(*_nodes)[v].first_out].prev_out = n;
449 450
      }
450 451
      (*_nodes)[v].first_out = n;
451 452
      arcs[n].prev_out = -1;
452 453

	
453 454
      if ((*_nodes)[u].first_out != -1) {
454 455
        arcs[(*_nodes)[u].first_out].prev_out = (n | 1);
455 456
      }
456 457
      arcs[n | 1].next_out = (*_nodes)[u].first_out;
457 458
      (*_nodes)[u].first_out = (n | 1);
458 459
      arcs[n | 1].prev_out = -1;
459 460

	
460 461
      return Edge(n / 2);
461 462
    }
462 463

	
463 464
    void erase(const Edge& arc) {
464 465
      int n = arc.id * 2;
465 466

	
466 467
      if (arcs[n].next_out != -1) {
467 468
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
468 469
      }
469 470

	
470 471
      if (arcs[n].prev_out != -1) {
471 472
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
472 473
      } else {
473 474
        (*_nodes)[arcs[n | 1].target].first_out = arcs[n].next_out;
474 475
      }
475 476

	
476 477
      if (arcs[n | 1].next_out != -1) {
477 478
        arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out;
478 479
      }
479 480

	
480 481
      if (arcs[n | 1].prev_out != -1) {
481 482
        arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out;
482 483
      } else {
483 484
        (*_nodes)[arcs[n].target].first_out = arcs[n | 1].next_out;
484 485
      }
485 486

	
486 487
      arcs[n].next_out = first_free_arc;
487 488
      first_free_arc = n;
488 489

	
489 490
    }
490 491

	
491 492
    void clear() {
492 493
      Node node;
493 494
      for (first(node); node != INVALID; next(node)) {
494 495
        (*_nodes)[node].first_out = -1;
495 496
      }
496 497
      arcs.clear();
497 498
      first_arc = -1;
498 499
      first_free_arc = -1;
499 500
    }
500 501

	
501 502
    void first(Node& node) const {
502 503
      _graph->first(node);
503 504
    }
504 505

	
505 506
    void next(Node& node) const {
506 507
      _graph->next(node);
507 508
    }
508 509

	
509 510
    void first(Arc& arc) const {
510 511
      Node node;
511 512
      first(node);
512 513
      while (node != INVALID && (*_nodes)[node].first_out == -1) {
513 514
        next(node);
514 515
      }
515 516
      arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_out;
516 517
    }
517 518

	
518 519
    void next(Arc& arc) const {
519 520
      if (arcs[arc.id].next_out != -1) {
520 521
        arc.id = arcs[arc.id].next_out;
521 522
      } else {
522 523
        Node node = arcs[arc.id ^ 1].target;
523 524
        next(node);
524 525
        while(node != INVALID && (*_nodes)[node].first_out == -1) {
525 526
          next(node);
526 527
        }
527 528
        arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_out;
528 529
      }
529 530
    }
530 531

	
531 532
    void first(Edge& edge) const {
532 533
      Node node;
533 534
      first(node);
534 535
      while (node != INVALID) {
535 536
        edge.id = (*_nodes)[node].first_out;
536 537
        while ((edge.id & 1) != 1) {
537 538
          edge.id = arcs[edge.id].next_out;
538 539
        }
539 540
        if (edge.id != -1) {
540 541
          edge.id /= 2;
541 542
          return;
542 543
        }
543 544
        next(node);
544 545
      }
545 546
      edge.id = -1;
546 547
    }
547 548

	
548 549
    void next(Edge& edge) const {
549 550
      Node node = arcs[edge.id * 2].target;
550 551
      edge.id = arcs[(edge.id * 2) | 1].next_out;
551 552
      while ((edge.id & 1) != 1) {
552 553
        edge.id = arcs[edge.id].next_out;
553 554
      }
554 555
      if (edge.id != -1) {
555 556
        edge.id /= 2;
556 557
        return;
557 558
      }
558 559
      next(node);
559 560
      while (node != INVALID) {
560 561
        edge.id = (*_nodes)[node].first_out;
561 562
        while ((edge.id & 1) != 1) {
562 563
          edge.id = arcs[edge.id].next_out;
563 564
        }
564 565
        if (edge.id != -1) {
565 566
          edge.id /= 2;
566 567
          return;
567 568
        }
568 569
        next(node);
569 570
      }
570 571
      edge.id = -1;
571 572
    }
572 573

	
573 574
    void firstOut(Arc& arc, const Node& node) const {
574 575
      arc.id = (*_nodes)[node].first_out;
575 576
    }
576 577

	
577 578
    void nextOut(Arc& arc) const {
578 579
      arc.id = arcs[arc.id].next_out;
579 580
    }
580 581

	
581 582
    void firstIn(Arc& arc, const Node& node) const {
582 583
      arc.id = (((*_nodes)[node].first_out) ^ 1);
583 584
      if (arc.id == -2) arc.id = -1;
584 585
    }
585 586

	
586 587
    void nextIn(Arc& arc) const {
587 588
      arc.id = ((arcs[arc.id ^ 1].next_out) ^ 1);
588 589
      if (arc.id == -2) arc.id = -1;
589 590
    }
590 591

	
591 592
    void firstInc(Edge &arc, bool& dir, const Node& node) const {
592 593
      int de = (*_nodes)[node].first_out;
593 594
      if (de != -1 ) {
594 595
        arc.id = de / 2;
595 596
        dir = ((de & 1) == 1);
596 597
      } else {
597 598
        arc.id = -1;
598 599
        dir = true;
599 600
      }
600 601
    }
601 602
    void nextInc(Edge &arc, bool& dir) const {
602 603
      int de = (arcs[(arc.id * 2) | (dir ? 1 : 0)].next_out);
603 604
      if (de != -1 ) {
604 605
        arc.id = de / 2;
605 606
        dir = ((de & 1) == 1);
606 607
      } else {
607 608
        arc.id = -1;
608 609
        dir = true;
609 610
      }
610 611
    }
611 612

	
612 613
    static bool direction(Arc arc) {
613 614
      return (arc.id & 1) == 1;
614 615
    }
615 616

	
616 617
    static Arc direct(Edge edge, bool dir) {
617 618
      return Arc(edge.id * 2 + (dir ? 1 : 0));
618 619
    }
619 620

	
620 621
    int id(const Node& node) const { return _graph->id(node); }
621 622
    static int id(Arc e) { return e.id; }
622 623
    static int id(Edge e) { return e.id; }
623 624

	
624 625
    Node nodeFromId(int id) const { return _graph->nodeFromId(id); }
625 626
    static Arc arcFromId(int id) { return Arc(id);}
626 627
    static Edge edgeFromId(int id) { return Edge(id);}
627 628

	
628 629
    int maxNodeId() const { return _graph->maxNodeId(); };
629 630
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
630 631
    int maxArcId() const { return arcs.size()-1; }
631 632

	
632 633
    Node source(Arc e) const { return arcs[e.id ^ 1].target; }
633 634
    Node target(Arc e) const { return arcs[e.id].target; }
634 635

	
635 636
    Node u(Edge e) const { return arcs[2 * e.id].target; }
636 637
    Node v(Edge e) const { return arcs[2 * e.id + 1].target; }
637 638

	
638 639
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
639 640

	
640 641
    NodeNotifier& notifier(Node) const {
641 642
      return _graph->notifier(Node());
642 643
    }
643 644

	
644 645
    template <typename V>
645 646
    class NodeMap : public GR::template NodeMap<V> {
646 647
      typedef typename GR::template NodeMap<V> Parent;
647 648

	
648 649
    public:
649 650

	
650 651
      explicit NodeMap(const ListEdgeSetBase<GR>& arcset)
651 652
        : Parent(*arcset._graph) {}
652 653

	
653 654
      NodeMap(const ListEdgeSetBase<GR>& arcset, const V& value)
654 655
        : Parent(*arcset._graph, value) {}
655 656

	
656 657
      NodeMap& operator=(const NodeMap& cmap) {
657 658
        return operator=<NodeMap>(cmap);
658 659
      }
659 660

	
660 661
      template <typename CMap>
661 662
      NodeMap& operator=(const CMap& cmap) {
662 663
        Parent::operator=(cmap);
663 664
        return *this;
664 665
      }
665 666
    };
666 667

	
667 668
  };
668 669

	
669 670
  /// \ingroup graphs
670 671
  ///
671 672
  /// \brief Graph using a node set of another digraph or graph and an
672 673
  /// own edge set.
673 674
  ///
674 675
  /// This structure can be used to establish another graph over a
675 676
  /// node set of an existing one. This class uses the same Node type
676 677
  /// as the underlying graph, and each valid node of the original
677 678
  /// graph is valid in this arc set, therefore the node objects of
678 679
  /// the original graph can be used directly with this class. The
679 680
  /// node handling functions (id handling, observing, and iterators)
680 681
  /// works equivalently as in the original graph.
681 682
  ///
682 683
  /// This implementation is based on doubly-linked lists, from each
683 684
  /// node the incident edges make up lists, therefore one edge can be
684 685
  /// erased in constant time. It also makes possible, that node can
685 686
  /// be removed from the underlying graph, in this case all edges
686 687
  /// incident to the given node is erased from the arc set.
687 688
  ///
689
  /// This class fully conforms to the \ref concepts::Graph "Graph"
690
  /// concept.
691
  /// It provides only linear time counting for nodes, edges and arcs.
692
  ///
688 693
  /// \param GR The type of the graph which shares its node set
689 694
  /// with this class. Its interface must conform to the
690 695
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
691 696
  /// concept.
692
  ///
693
  /// This class fully conforms to the \ref concepts::Graph "Graph"
694
  /// concept.
695 697
  template <typename GR>
696 698
  class ListEdgeSet : public EdgeSetExtender<ListEdgeSetBase<GR> > {
697 699
    typedef EdgeSetExtender<ListEdgeSetBase<GR> > Parent;
698 700

	
699 701
  public:
700 702

	
701 703
    typedef typename Parent::Node Node;
702 704
    typedef typename Parent::Arc Arc;
703 705
    typedef typename Parent::Edge Edge;
704 706

	
705 707
    typedef typename Parent::NodesImplBase NodesImplBase;
706 708

	
707 709
    void eraseNode(const Node& node) {
708 710
      Arc arc;
709 711
      Parent::firstOut(arc, node);
710 712
      while (arc != INVALID ) {
711 713
        erase(arc);
712 714
        Parent::firstOut(arc, node);
713 715
      }
714 716

	
715 717
    }
716 718

	
717 719
    void clearNodes() {
718 720
      Parent::clear();
719 721
    }
720 722

	
721 723
    class NodesImpl : public NodesImplBase {
722 724
      typedef NodesImplBase Parent;
723 725

	
724 726
    public:
725 727
      NodesImpl(const GR& graph, ListEdgeSet& arcset)
726 728
        : Parent(graph), _arcset(arcset) {}
727 729

	
728 730
      virtual ~NodesImpl() {}
729 731

	
730 732
    protected:
731 733

	
732 734
      virtual void erase(const Node& node) {
733 735
        _arcset.eraseNode(node);
734 736
        Parent::erase(node);
735 737
      }
736 738
      virtual void erase(const std::vector<Node>& nodes) {
737 739
        for (int i = 0; i < int(nodes.size()); ++i) {
738 740
          _arcset.eraseNode(nodes[i]);
739 741
        }
740 742
        Parent::erase(nodes);
741 743
      }
742 744
      virtual void clear() {
743 745
        _arcset.clearNodes();
744 746
        Parent::clear();
745 747
      }
746 748

	
747 749
    private:
748 750
      ListEdgeSet& _arcset;
749 751
    };
750 752

	
751 753
    NodesImpl _nodes;
752 754

	
753 755
  public:
754 756

	
755 757
    /// \brief Constructor of the EdgeSet.
756 758
    ///
757 759
    /// Constructor of the EdgeSet.
758 760
    ListEdgeSet(const GR& graph) : _nodes(graph, *this) {
759 761
      Parent::initalize(graph, _nodes);
760 762
    }
761 763

	
762 764
    /// \brief Add a new edge to the graph.
763 765
    ///
764 766
    /// Add a new edge to the graph with node \c u
765 767
    /// and node \c v endpoints.
766 768
    /// \return The new edge.
767 769
    Edge addEdge(const Node& u, const Node& v) {
768 770
      return Parent::addEdge(u, v);
769 771
    }
770 772

	
771 773
    /// \brief Erase an edge from the graph.
772 774
    ///
773 775
    /// Erase the edge \c e from the graph.
774 776
    void erase(const Edge& e) {
775 777
      return Parent::erase(e);
776 778
    }
777 779

	
778 780
  };
779 781

	
780 782
  template <typename GR>
781 783
  class SmartArcSetBase {
782 784
  public:
783 785

	
784 786
    typedef typename GR::Node Node;
785 787
    typedef typename GR::NodeIt NodeIt;
786 788

	
787 789
  protected:
788 790

	
789 791
    struct NodeT {
790 792
      int first_out, first_in;
791 793
      NodeT() : first_out(-1), first_in(-1) {}
792 794
    };
793 795

	
794 796
    typedef typename ItemSetTraits<GR, Node>::
795 797
    template Map<NodeT>::Type NodesImplBase;
796 798

	
797 799
    NodesImplBase* _nodes;
798 800

	
799 801
    struct ArcT {
800 802
      Node source, target;
801 803
      int next_out, next_in;
802 804
      ArcT() {}
803 805
    };
804 806

	
805 807
    std::vector<ArcT> arcs;
806 808

	
807 809
    const GR* _graph;
808 810

	
809 811
    void initalize(const GR& graph, NodesImplBase& nodes) {
810 812
      _graph = &graph;
811 813
      _nodes = &nodes;
812 814
    }
813 815

	
814 816
  public:
815 817

	
816 818
    class Arc {
817 819
      friend class SmartArcSetBase<GR>;
818 820
    protected:
819 821
      Arc(int _id) : id(_id) {}
820 822
      int id;
821 823
    public:
822 824
      Arc() {}
823 825
      Arc(Invalid) : id(-1) {}
824 826
      bool operator==(const Arc& arc) const { return id == arc.id; }
825 827
      bool operator!=(const Arc& arc) const { return id != arc.id; }
826 828
      bool operator<(const Arc& arc) const { return id < arc.id; }
827 829
    };
828 830

	
829 831
    SmartArcSetBase() {}
830 832

	
831 833
    Node addNode() {
832 834
      LEMON_ASSERT(false,
833 835
        "This graph structure does not support node insertion");
834 836
      return INVALID; // avoid warning
835 837
    }
836 838

	
837 839
    Arc addArc(const Node& u, const Node& v) {
838 840
      int n = arcs.size();
839 841
      arcs.push_back(ArcT());
840 842
      arcs[n].next_in = (*_nodes)[v].first_in;
841 843
      (*_nodes)[v].first_in = n;
842 844
      arcs[n].next_out = (*_nodes)[u].first_out;
843 845
      (*_nodes)[u].first_out = n;
844 846
      arcs[n].source = u;
845 847
      arcs[n].target = v;
846 848
      return Arc(n);
847 849
    }
848 850

	
849 851
    void clear() {
850 852
      Node node;
851 853
      for (first(node); node != INVALID; next(node)) {
852 854
        (*_nodes)[node].first_in = -1;
853 855
        (*_nodes)[node].first_out = -1;
854 856
      }
855 857
      arcs.clear();
856 858
    }
857 859

	
858 860
    void first(Node& node) const {
859 861
      _graph->first(node);
860 862
    }
861 863

	
862 864
    void next(Node& node) const {
863 865
      _graph->next(node);
864 866
    }
865 867

	
866 868
    void first(Arc& arc) const {
867 869
      arc.id = arcs.size() - 1;
868 870
    }
869 871

	
870 872
    static void next(Arc& arc) {
871 873
      --arc.id;
872 874
    }
873 875

	
874 876
    void firstOut(Arc& arc, const Node& node) const {
875 877
      arc.id = (*_nodes)[node].first_out;
876 878
    }
877 879

	
878 880
    void nextOut(Arc& arc) const {
879 881
      arc.id = arcs[arc.id].next_out;
880 882
    }
881 883

	
882 884
    void firstIn(Arc& arc, const Node& node) const {
883 885
      arc.id = (*_nodes)[node].first_in;
884 886
    }
885 887

	
886 888
    void nextIn(Arc& arc) const {
887 889
      arc.id = arcs[arc.id].next_in;
888 890
    }
889 891

	
890 892
    int id(const Node& node) const { return _graph->id(node); }
891 893
    int id(const Arc& arc) const { return arc.id; }
892 894

	
893 895
    Node nodeFromId(int ix) const { return _graph->nodeFromId(ix); }
894 896
    Arc arcFromId(int ix) const { return Arc(ix); }
895 897

	
896 898
    int maxNodeId() const { return _graph->maxNodeId(); };
897 899
    int maxArcId() const { return arcs.size() - 1; }
898 900

	
899 901
    Node source(const Arc& arc) const { return arcs[arc.id].source;}
900 902
    Node target(const Arc& arc) const { return arcs[arc.id].target;}
901 903

	
902 904
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
903 905

	
904 906
    NodeNotifier& notifier(Node) const {
905 907
      return _graph->notifier(Node());
906 908
    }
907 909

	
908 910
    template <typename V>
909 911
    class NodeMap : public GR::template NodeMap<V> {
910 912
      typedef typename GR::template NodeMap<V> Parent;
911 913

	
912 914
    public:
913 915

	
914 916
      explicit NodeMap(const SmartArcSetBase<GR>& arcset)
915 917
        : Parent(*arcset._graph) { }
916 918

	
917 919
      NodeMap(const SmartArcSetBase<GR>& arcset, const V& value)
918 920
        : Parent(*arcset._graph, value) { }
919 921

	
920 922
      NodeMap& operator=(const NodeMap& cmap) {
921 923
        return operator=<NodeMap>(cmap);
922 924
      }
923 925

	
924 926
      template <typename CMap>
925 927
      NodeMap& operator=(const CMap& cmap) {
926 928
        Parent::operator=(cmap);
927 929
        return *this;
928 930
      }
929 931
    };
930 932

	
931 933
  };
932 934

	
933 935

	
934 936
  /// \ingroup graphs
935 937
  ///
936 938
  /// \brief Digraph using a node set of another digraph or graph and
937 939
  /// an own arc set.
938 940
  ///
939 941
  /// This structure can be used to establish another directed graph
940 942
  /// over a node set of an existing one. This class uses the same
941 943
  /// Node type as the underlying graph, and each valid node of the
942 944
  /// original graph is valid in this arc set, therefore the node
943 945
  /// objects of the original graph can be used directly with this
944 946
  /// class. The node handling functions (id handling, observing, and
945 947
  /// iterators) works equivalently as in the original graph.
946 948
  ///
947 949
  /// \param GR The type of the graph which shares its node set with
948 950
  /// this class. Its interface must conform to the
949 951
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
950 952
  /// concept.
951 953
  ///
952 954
  /// This implementation is slightly faster than the \c ListArcSet,
953 955
  /// because it uses continuous storage for arcs and it uses just
954 956
  /// single-linked lists for enumerate outgoing and incoming
955 957
  /// arcs. Therefore the arcs cannot be erased from the arc sets.
956 958
  ///
959
  /// This class fully conforms to the \ref concepts::Digraph "Digraph"
960
  /// concept.
961
  /// It provides only linear time counting for nodes and arcs.
962
  ///
957 963
  /// \warning If a node is erased from the underlying graph and this
958 964
  /// node is the source or target of one arc in the arc set, then
959 965
  /// the arc set is invalidated, and it cannot be used anymore. The
960 966
  /// validity can be checked with the \c valid() member function.
961
  ///
962
  /// This class fully conforms to the \ref concepts::Digraph
963
  /// "Digraph" concept.
964 967
  template <typename GR>
965 968
  class SmartArcSet : public ArcSetExtender<SmartArcSetBase<GR> > {
966 969
    typedef ArcSetExtender<SmartArcSetBase<GR> > Parent;
967 970

	
968 971
  public:
969 972

	
970 973
    typedef typename Parent::Node Node;
971 974
    typedef typename Parent::Arc Arc;
972 975

	
973 976
  protected:
974 977

	
975 978
    typedef typename Parent::NodesImplBase NodesImplBase;
976 979

	
977 980
    void eraseNode(const Node& node) {
978 981
      if (typename Parent::InArcIt(*this, node) == INVALID &&
979 982
          typename Parent::OutArcIt(*this, node) == INVALID) {
980 983
        return;
981 984
      }
982 985
      throw typename NodesImplBase::Notifier::ImmediateDetach();
983 986
    }
984 987

	
985 988
    void clearNodes() {
986 989
      Parent::clear();
987 990
    }
988 991

	
989 992
    class NodesImpl : public NodesImplBase {
990 993
      typedef NodesImplBase Parent;
991 994

	
992 995
    public:
993 996
      NodesImpl(const GR& graph, SmartArcSet& arcset)
994 997
        : Parent(graph), _arcset(arcset) {}
995 998

	
996 999
      virtual ~NodesImpl() {}
997 1000

	
998 1001
      bool attached() const {
999 1002
        return Parent::attached();
1000 1003
      }
1001 1004

	
1002 1005
    protected:
1003 1006

	
1004 1007
      virtual void erase(const Node& node) {
1005 1008
        try {
1006 1009
          _arcset.eraseNode(node);
1007 1010
          Parent::erase(node);
1008 1011
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1009 1012
          Parent::clear();
1010 1013
          throw;
1011 1014
        }
1012 1015
      }
1013 1016
      virtual void erase(const std::vector<Node>& nodes) {
1014 1017
        try {
1015 1018
          for (int i = 0; i < int(nodes.size()); ++i) {
1016 1019
            _arcset.eraseNode(nodes[i]);
1017 1020
          }
1018 1021
          Parent::erase(nodes);
1019 1022
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1020 1023
          Parent::clear();
1021 1024
          throw;
1022 1025
        }
1023 1026
      }
1024 1027
      virtual void clear() {
1025 1028
        _arcset.clearNodes();
1026 1029
        Parent::clear();
1027 1030
      }
1028 1031

	
1029 1032
    private:
1030 1033
      SmartArcSet& _arcset;
1031 1034
    };
1032 1035

	
1033 1036
    NodesImpl _nodes;
1034 1037

	
1035 1038
  public:
1036 1039

	
1037 1040
    /// \brief Constructor of the ArcSet.
1038 1041
    ///
1039 1042
    /// Constructor of the ArcSet.
1040 1043
    SmartArcSet(const GR& graph) : _nodes(graph, *this) {
1041 1044
      Parent::initalize(graph, _nodes);
1042 1045
    }
1043 1046

	
1044 1047
    /// \brief Add a new arc to the digraph.
1045 1048
    ///
1046 1049
    /// Add a new arc to the digraph with source node \c s
1047 1050
    /// and target node \c t.
1048 1051
    /// \return The new arc.
1049 1052
    Arc addArc(const Node& s, const Node& t) {
1050 1053
      return Parent::addArc(s, t);
1051 1054
    }
1052 1055

	
1053 1056
    /// \brief Validity check
1054 1057
    ///
1055 1058
    /// This functions gives back false if the ArcSet is
1056 1059
    /// invalidated. It occurs when a node in the underlying graph is
1057 1060
    /// erased and it is not isolated in the ArcSet.
1058 1061
    bool valid() const {
1059 1062
      return _nodes.attached();
1060 1063
    }
1061 1064

	
1062 1065
  };
1063 1066

	
1064 1067

	
1065 1068
  template <typename GR>
1066 1069
  class SmartEdgeSetBase {
1067 1070
  public:
1068 1071

	
1069 1072
    typedef typename GR::Node Node;
1070 1073
    typedef typename GR::NodeIt NodeIt;
1071 1074

	
1072 1075
  protected:
1073 1076

	
1074 1077
    struct NodeT {
1075 1078
      int first_out;
1076 1079
      NodeT() : first_out(-1) {}
1077 1080
    };
1078 1081

	
1079 1082
    typedef typename ItemSetTraits<GR, Node>::
1080 1083
    template Map<NodeT>::Type NodesImplBase;
1081 1084

	
1082 1085
    NodesImplBase* _nodes;
1083 1086

	
1084 1087
    struct ArcT {
1085 1088
      Node target;
1086 1089
      int next_out;
1087 1090
      ArcT() {}
1088 1091
    };
1089 1092

	
1090 1093
    std::vector<ArcT> arcs;
1091 1094

	
1092 1095
    const GR* _graph;
1093 1096

	
1094 1097
    void initalize(const GR& graph, NodesImplBase& nodes) {
1095 1098
      _graph = &graph;
1096 1099
      _nodes = &nodes;
1097 1100
    }
1098 1101

	
1099 1102
  public:
1100 1103

	
1101 1104
    class Edge {
1102 1105
      friend class SmartEdgeSetBase;
1103 1106
    protected:
1104 1107

	
1105 1108
      int id;
1106 1109
      explicit Edge(int _id) { id = _id;}
1107 1110

	
1108 1111
    public:
1109 1112
      Edge() {}
1110 1113
      Edge (Invalid) { id = -1; }
1111 1114
      bool operator==(const Edge& arc) const {return id == arc.id;}
1112 1115
      bool operator!=(const Edge& arc) const {return id != arc.id;}
1113 1116
      bool operator<(const Edge& arc) const {return id < arc.id;}
1114 1117
    };
1115 1118

	
1116 1119
    class Arc {
1117 1120
      friend class SmartEdgeSetBase;
1118 1121
    protected:
1119 1122
      Arc(int _id) : id(_id) {}
1120 1123
      int id;
1121 1124
    public:
1122 1125
      operator Edge() const { return edgeFromId(id / 2); }
1123 1126

	
1124 1127
      Arc() {}
1125 1128
      Arc(Invalid) : id(-1) {}
1126 1129
      bool operator==(const Arc& arc) const { return id == arc.id; }
1127 1130
      bool operator!=(const Arc& arc) const { return id != arc.id; }
1128 1131
      bool operator<(const Arc& arc) const { return id < arc.id; }
1129 1132
    };
1130 1133

	
1131 1134
    SmartEdgeSetBase() {}
1132 1135

	
1133 1136
    Node addNode() {
1134 1137
      LEMON_ASSERT(false,
1135 1138
        "This graph structure does not support node insertion");
1136 1139
      return INVALID; // avoid warning
1137 1140
    }
1138 1141

	
1139 1142
    Edge addEdge(const Node& u, const Node& v) {
1140 1143
      int n = arcs.size();
1141 1144
      arcs.push_back(ArcT());
1142 1145
      arcs.push_back(ArcT());
1143 1146

	
1144 1147
      arcs[n].target = u;
1145 1148
      arcs[n | 1].target = v;
1146 1149

	
1147 1150
      arcs[n].next_out = (*_nodes)[v].first_out;
1148 1151
      (*_nodes)[v].first_out = n;
1149 1152

	
1150 1153
      arcs[n | 1].next_out = (*_nodes)[u].first_out;
1151 1154
      (*_nodes)[u].first_out = (n | 1);
1152 1155

	
1153 1156
      return Edge(n / 2);
1154 1157
    }
1155 1158

	
1156 1159
    void clear() {
1157 1160
      Node node;
1158 1161
      for (first(node); node != INVALID; next(node)) {
1159 1162
        (*_nodes)[node].first_out = -1;
1160 1163
      }
1161 1164
      arcs.clear();
1162 1165
    }
1163 1166

	
1164 1167
    void first(Node& node) const {
1165 1168
      _graph->first(node);
1166 1169
    }
1167 1170

	
1168 1171
    void next(Node& node) const {
1169 1172
      _graph->next(node);
1170 1173
    }
1171 1174

	
1172 1175
    void first(Arc& arc) const {
1173 1176
      arc.id = arcs.size() - 1;
1174 1177
    }
1175 1178

	
1176 1179
    static void next(Arc& arc) {
1177 1180
      --arc.id;
1178 1181
    }
1179 1182

	
1180 1183
    void first(Edge& arc) const {
1181 1184
      arc.id = arcs.size() / 2 - 1;
1182 1185
    }
1183 1186

	
1184 1187
    static void next(Edge& arc) {
1185 1188
      --arc.id;
1186 1189
    }
1187 1190

	
1188 1191
    void firstOut(Arc& arc, const Node& node) const {
1189 1192
      arc.id = (*_nodes)[node].first_out;
1190 1193
    }
1191 1194

	
1192 1195
    void nextOut(Arc& arc) const {
1193 1196
      arc.id = arcs[arc.id].next_out;
1194 1197
    }
1195 1198

	
1196 1199
    void firstIn(Arc& arc, const Node& node) const {
1197 1200
      arc.id = (((*_nodes)[node].first_out) ^ 1);
1198 1201
      if (arc.id == -2) arc.id = -1;
1199 1202
    }
1200 1203

	
1201 1204
    void nextIn(Arc& arc) const {
1202 1205
      arc.id = ((arcs[arc.id ^ 1].next_out) ^ 1);
1203 1206
      if (arc.id == -2) arc.id = -1;
1204 1207
    }
1205 1208

	
1206 1209
    void firstInc(Edge &arc, bool& dir, const Node& node) const {
1207 1210
      int de = (*_nodes)[node].first_out;
1208 1211
      if (de != -1 ) {
1209 1212
        arc.id = de / 2;
1210 1213
        dir = ((de & 1) == 1);
1211 1214
      } else {
1212 1215
        arc.id = -1;
1213 1216
        dir = true;
1214 1217
      }
1215 1218
    }
1216 1219
    void nextInc(Edge &arc, bool& dir) const {
1217 1220
      int de = (arcs[(arc.id * 2) | (dir ? 1 : 0)].next_out);
1218 1221
      if (de != -1 ) {
1219 1222
        arc.id = de / 2;
1220 1223
        dir = ((de & 1) == 1);
1221 1224
      } else {
1222 1225
        arc.id = -1;
1223 1226
        dir = true;
1224 1227
      }
1225 1228
    }
1226 1229

	
1227 1230
    static bool direction(Arc arc) {
1228 1231
      return (arc.id & 1) == 1;
1229 1232
    }
1230 1233

	
1231 1234
    static Arc direct(Edge edge, bool dir) {
1232 1235
      return Arc(edge.id * 2 + (dir ? 1 : 0));
1233 1236
    }
1234 1237

	
1235 1238
    int id(Node node) const { return _graph->id(node); }
1236 1239
    static int id(Arc arc) { return arc.id; }
1237 1240
    static int id(Edge arc) { return arc.id; }
1238 1241

	
1239 1242
    Node nodeFromId(int id) const { return _graph->nodeFromId(id); }
1240 1243
    static Arc arcFromId(int id) { return Arc(id); }
1241 1244
    static Edge edgeFromId(int id) { return Edge(id);}
1242 1245

	
1243 1246
    int maxNodeId() const { return _graph->maxNodeId(); };
1244 1247
    int maxArcId() const { return arcs.size() - 1; }
1245 1248
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
1246 1249

	
1247 1250
    Node source(Arc e) const { return arcs[e.id ^ 1].target; }
1248 1251
    Node target(Arc e) const { return arcs[e.id].target; }
1249 1252

	
1250 1253
    Node u(Edge e) const { return arcs[2 * e.id].target; }
1251 1254
    Node v(Edge e) const { return arcs[2 * e.id + 1].target; }
1252 1255

	
1253 1256
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
1254 1257

	
1255 1258
    NodeNotifier& notifier(Node) const {
1256 1259
      return _graph->notifier(Node());
1257 1260
    }
1258 1261

	
1259 1262
    template <typename V>
1260 1263
    class NodeMap : public GR::template NodeMap<V> {
1261 1264
      typedef typename GR::template NodeMap<V> Parent;
1262 1265

	
1263 1266
    public:
1264 1267

	
1265 1268
      explicit NodeMap(const SmartEdgeSetBase<GR>& arcset)
1266 1269
        : Parent(*arcset._graph) { }
1267 1270

	
1268 1271
      NodeMap(const SmartEdgeSetBase<GR>& arcset, const V& value)
1269 1272
        : Parent(*arcset._graph, value) { }
1270 1273

	
1271 1274
      NodeMap& operator=(const NodeMap& cmap) {
1272 1275
        return operator=<NodeMap>(cmap);
1273 1276
      }
1274 1277

	
1275 1278
      template <typename CMap>
1276 1279
      NodeMap& operator=(const CMap& cmap) {
1277 1280
        Parent::operator=(cmap);
1278 1281
        return *this;
1279 1282
      }
1280 1283
    };
1281 1284

	
1282 1285
  };
1283 1286

	
1284 1287
  /// \ingroup graphs
1285 1288
  ///
1286 1289
  /// \brief Graph using a node set of another digraph or graph and an
1287 1290
  /// own edge set.
1288 1291
  ///
1289 1292
  /// This structure can be used to establish another graph over a
1290 1293
  /// node set of an existing one. This class uses the same Node type
1291 1294
  /// as the underlying graph, and each valid node of the original
1292 1295
  /// graph is valid in this arc set, therefore the node objects of
1293 1296
  /// the original graph can be used directly with this class. The
1294 1297
  /// node handling functions (id handling, observing, and iterators)
1295 1298
  /// works equivalently as in the original graph.
1296 1299
  ///
1297 1300
  /// \param GR The type of the graph which shares its node set
1298 1301
  /// with this class. Its interface must conform to the
1299 1302
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
1300 1303
  ///  concept.
1301 1304
  ///
1302 1305
  /// This implementation is slightly faster than the \c ListEdgeSet,
1303 1306
  /// because it uses continuous storage for edges and it uses just
1304 1307
  /// single-linked lists for enumerate incident edges. Therefore the
1305 1308
  /// edges cannot be erased from the edge sets.
1306 1309
  ///
1310
  /// This class fully conforms to the \ref concepts::Graph "Graph"
1311
  /// concept.
1312
  /// It provides only linear time counting for nodes, edges and arcs.
1313
  ///
1307 1314
  /// \warning If a node is erased from the underlying graph and this
1308 1315
  /// node is incident to one edge in the edge set, then the edge set
1309 1316
  /// is invalidated, and it cannot be used anymore. The validity can
1310 1317
  /// be checked with the \c valid() member function.
1311
  ///
1312
  /// This class fully conforms to the \ref concepts::Graph
1313
  /// "Graph" concept.
1314 1318
  template <typename GR>
1315 1319
  class SmartEdgeSet : public EdgeSetExtender<SmartEdgeSetBase<GR> > {
1316 1320
    typedef EdgeSetExtender<SmartEdgeSetBase<GR> > Parent;
1317 1321

	
1318 1322
  public:
1319 1323

	
1320 1324
    typedef typename Parent::Node Node;
1321 1325
    typedef typename Parent::Arc Arc;
1322 1326
    typedef typename Parent::Edge Edge;
1323 1327

	
1324 1328
  protected:
1325 1329

	
1326 1330
    typedef typename Parent::NodesImplBase NodesImplBase;
1327 1331

	
1328 1332
    void eraseNode(const Node& node) {
1329 1333
      if (typename Parent::IncEdgeIt(*this, node) == INVALID) {
1330 1334
        return;
1331 1335
      }
1332 1336
      throw typename NodesImplBase::Notifier::ImmediateDetach();
1333 1337
    }
1334 1338

	
1335 1339
    void clearNodes() {
1336 1340
      Parent::clear();
1337 1341
    }
1338 1342

	
1339 1343
    class NodesImpl : public NodesImplBase {
1340 1344
      typedef NodesImplBase Parent;
1341 1345

	
1342 1346
    public:
1343 1347
      NodesImpl(const GR& graph, SmartEdgeSet& arcset)
1344 1348
        : Parent(graph), _arcset(arcset) {}
1345 1349

	
1346 1350
      virtual ~NodesImpl() {}
1347 1351

	
1348 1352
      bool attached() const {
1349 1353
        return Parent::attached();
1350 1354
      }
1351 1355

	
1352 1356
    protected:
1353 1357

	
1354 1358
      virtual void erase(const Node& node) {
1355 1359
        try {
1356 1360
          _arcset.eraseNode(node);
1357 1361
          Parent::erase(node);
1358 1362
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1359 1363
          Parent::clear();
1360 1364
          throw;
1361 1365
        }
1362 1366
      }
1363 1367
      virtual void erase(const std::vector<Node>& nodes) {
1364 1368
        try {
1365 1369
          for (int i = 0; i < int(nodes.size()); ++i) {
1366 1370
            _arcset.eraseNode(nodes[i]);
1367 1371
          }
1368 1372
          Parent::erase(nodes);
1369 1373
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1370 1374
          Parent::clear();
1371 1375
          throw;
1372 1376
        }
1373 1377
      }
1374 1378
      virtual void clear() {
1375 1379
        _arcset.clearNodes();
1376 1380
        Parent::clear();
1377 1381
      }
1378 1382

	
1379 1383
    private:
1380 1384
      SmartEdgeSet& _arcset;
1381 1385
    };
1382 1386

	
1383 1387
    NodesImpl _nodes;
1384 1388

	
1385 1389
  public:
1386 1390

	
1387 1391
    /// \brief Constructor of the EdgeSet.
1388 1392
    ///
1389 1393
    /// Constructor of the EdgeSet.
1390 1394
    SmartEdgeSet(const GR& graph) : _nodes(graph, *this) {
1391 1395
      Parent::initalize(graph, _nodes);
1392 1396
    }
1393 1397

	
1394 1398
    /// \brief Add a new edge to the graph.
1395 1399
    ///
1396 1400
    /// Add a new edge to the graph with node \c u
1397 1401
    /// and node \c v endpoints.
1398 1402
    /// \return The new edge.
1399 1403
    Edge addEdge(const Node& u, const Node& v) {
1400 1404
      return Parent::addEdge(u, v);
1401 1405
    }
1402 1406

	
1403 1407
    /// \brief Validity check
1404 1408
    ///
1405 1409
    /// This functions gives back false if the EdgeSet is
1406 1410
    /// invalidated. It occurs when a node in the underlying graph is
1407 1411
    /// erased and it is not isolated in the EdgeSet.
1408 1412
    bool valid() const {
1409 1413
      return _nodes.attached();
1410 1414
    }
1411 1415

	
1412 1416
  };
1413 1417

	
1414 1418
}
1415 1419

	
1416 1420
#endif
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-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_FULL_GRAPH_H
20 20
#define LEMON_FULL_GRAPH_H
21 21

	
22 22
#include <lemon/core.h>
23 23
#include <lemon/bits/graph_extender.h>
24 24

	
25 25
///\ingroup graphs
26 26
///\file
27 27
///\brief FullDigraph and FullGraph classes.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  class FullDigraphBase {
32 32
  public:
33 33

	
34 34
    typedef FullDigraphBase Digraph;
35 35

	
36 36
    class Node;
37 37
    class Arc;
38 38

	
39 39
  protected:
40 40

	
41 41
    int _node_num;
42 42
    int _arc_num;
43 43

	
44 44
    FullDigraphBase() {}
45 45

	
46 46
    void construct(int n) { _node_num = n; _arc_num = n * n; }
47 47

	
48 48
  public:
49 49

	
50 50
    typedef True NodeNumTag;
51 51
    typedef True ArcNumTag;
52 52

	
53 53
    Node operator()(int ix) const { return Node(ix); }
54 54
    static int index(const Node& node) { return node._id; }
55 55

	
56 56
    Arc arc(const Node& s, const Node& t) const {
57 57
      return Arc(s._id * _node_num + t._id);
58 58
    }
59 59

	
60 60
    int nodeNum() const { return _node_num; }
61 61
    int arcNum() const { return _arc_num; }
62 62

	
63 63
    int maxNodeId() const { return _node_num - 1; }
64 64
    int maxArcId() const { return _arc_num - 1; }
65 65

	
66 66
    Node source(Arc arc) const { return arc._id / _node_num; }
67 67
    Node target(Arc arc) const { return arc._id % _node_num; }
68 68

	
69 69
    static int id(Node node) { return node._id; }
70 70
    static int id(Arc arc) { return arc._id; }
71 71

	
72 72
    static Node nodeFromId(int id) { return Node(id);}
73 73
    static Arc arcFromId(int id) { return Arc(id);}
74 74

	
75 75
    typedef True FindArcTag;
76 76

	
77 77
    Arc findArc(Node s, Node t, Arc prev = INVALID) const {
78 78
      return prev == INVALID ? arc(s, t) : INVALID;
79 79
    }
80 80

	
81 81
    class Node {
82 82
      friend class FullDigraphBase;
83 83

	
84 84
    protected:
85 85
      int _id;
86 86
      Node(int id) : _id(id) {}
87 87
    public:
88 88
      Node() {}
89 89
      Node (Invalid) : _id(-1) {}
90 90
      bool operator==(const Node node) const {return _id == node._id;}
91 91
      bool operator!=(const Node node) const {return _id != node._id;}
92 92
      bool operator<(const Node node) const {return _id < node._id;}
93 93
    };
94 94

	
95 95
    class Arc {
96 96
      friend class FullDigraphBase;
97 97

	
98 98
    protected:
99 99
      int _id;  // _node_num * source + target;
100 100

	
101 101
      Arc(int id) : _id(id) {}
102 102

	
103 103
    public:
104 104
      Arc() { }
105 105
      Arc (Invalid) { _id = -1; }
106 106
      bool operator==(const Arc arc) const {return _id == arc._id;}
107 107
      bool operator!=(const Arc arc) const {return _id != arc._id;}
108 108
      bool operator<(const Arc arc) const {return _id < arc._id;}
109 109
    };
110 110

	
111 111
    void first(Node& node) const {
112 112
      node._id = _node_num - 1;
113 113
    }
114 114

	
115 115
    static void next(Node& node) {
116 116
      --node._id;
117 117
    }
118 118

	
119 119
    void first(Arc& arc) const {
120 120
      arc._id = _arc_num - 1;
121 121
    }
122 122

	
123 123
    static void next(Arc& arc) {
124 124
      --arc._id;
125 125
    }
126 126

	
127 127
    void firstOut(Arc& arc, const Node& node) const {
128 128
      arc._id = (node._id + 1) * _node_num - 1;
129 129
    }
130 130

	
131 131
    void nextOut(Arc& arc) const {
132 132
      if (arc._id % _node_num == 0) arc._id = 0;
133 133
      --arc._id;
134 134
    }
135 135

	
136 136
    void firstIn(Arc& arc, const Node& node) const {
137 137
      arc._id = _arc_num + node._id - _node_num;
138 138
    }
139 139

	
140 140
    void nextIn(Arc& arc) const {
141 141
      arc._id -= _node_num;
142 142
      if (arc._id < 0) arc._id = -1;
143 143
    }
144 144

	
145 145
  };
146 146

	
147 147
  typedef DigraphExtender<FullDigraphBase> ExtendedFullDigraphBase;
148 148

	
149 149
  /// \ingroup graphs
150 150
  ///
151 151
  /// \brief A directed full graph class.
152 152
  ///
153 153
  /// FullDigraph is a simple and fast implmenetation of directed full
154 154
  /// (complete) graphs. It contains an arc from each node to each node
155 155
  /// (including a loop for each node), therefore the number of arcs
156 156
  /// is the square of the number of nodes.
157 157
  /// This class is completely static and it needs constant memory space.
158 158
  /// Thus you can neither add nor delete nodes or arcs, however
159 159
  /// the structure can be resized using resize().
160 160
  ///
161 161
  /// This type fully conforms to the \ref concepts::Digraph "Digraph concept".
162 162
  /// Most of its member functions and nested classes are documented
163 163
  /// only in the concept class.
164 164
  ///
165
  /// This class provides constant time counting for nodes and arcs.
166
  ///
165 167
  /// \note FullDigraph and FullGraph classes are very similar,
166 168
  /// but there are two differences. While this class conforms only
167 169
  /// to the \ref concepts::Digraph "Digraph" concept, FullGraph
168 170
  /// conforms to the \ref concepts::Graph "Graph" concept,
169 171
  /// moreover FullGraph does not contain a loop for each
170 172
  /// node as this class does.
171 173
  ///
172 174
  /// \sa FullGraph
173 175
  class FullDigraph : public ExtendedFullDigraphBase {
174 176
    typedef ExtendedFullDigraphBase Parent;
175 177

	
176 178
  public:
177 179

	
178 180
    /// \brief Default constructor.
179 181
    ///
180 182
    /// Default constructor. The number of nodes and arcs will be zero.
181 183
    FullDigraph() { construct(0); }
182 184

	
183 185
    /// \brief Constructor
184 186
    ///
185 187
    /// Constructor.
186 188
    /// \param n The number of the nodes.
187 189
    FullDigraph(int n) { construct(n); }
188 190

	
189 191
    /// \brief Resizes the digraph
190 192
    ///
191 193
    /// This function resizes the digraph. It fully destroys and
192 194
    /// rebuilds the structure, therefore the maps of the digraph will be
193 195
    /// reallocated automatically and the previous values will be lost.
194 196
    void resize(int n) {
195 197
      Parent::notifier(Arc()).clear();
196 198
      Parent::notifier(Node()).clear();
197 199
      construct(n);
198 200
      Parent::notifier(Node()).build();
199 201
      Parent::notifier(Arc()).build();
200 202
    }
201 203

	
202 204
    /// \brief Returns the node with the given index.
203 205
    ///
204 206
    /// Returns the node with the given index. Since this structure is 
205 207
    /// completely static, the nodes can be indexed with integers from
206 208
    /// the range <tt>[0..nodeNum()-1]</tt>.
209
    /// The index of a node is the same as its ID.
207 210
    /// \sa index()
208 211
    Node operator()(int ix) const { return Parent::operator()(ix); }
209 212

	
210 213
    /// \brief Returns the index of the given node.
211 214
    ///
212 215
    /// Returns the index of the given node. Since this structure is 
213 216
    /// completely static, the nodes can be indexed with integers from
214 217
    /// the range <tt>[0..nodeNum()-1]</tt>.
218
    /// The index of a node is the same as its ID.
215 219
    /// \sa operator()()
216 220
    static int index(const Node& node) { return Parent::index(node); }
217 221

	
218 222
    /// \brief Returns the arc connecting the given nodes.
219 223
    ///
220 224
    /// Returns the arc connecting the given nodes.
221 225
    Arc arc(Node u, Node v) const {
222 226
      return Parent::arc(u, v);
223 227
    }
224 228

	
225 229
    /// \brief Number of nodes.
226 230
    int nodeNum() const { return Parent::nodeNum(); }
227 231
    /// \brief Number of arcs.
228 232
    int arcNum() const { return Parent::arcNum(); }
229 233
  };
230 234

	
231 235

	
232 236
  class FullGraphBase {
233 237
  public:
234 238

	
235 239
    typedef FullGraphBase Graph;
236 240

	
237 241
    class Node;
238 242
    class Arc;
239 243
    class Edge;
240 244

	
241 245
  protected:
242 246

	
243 247
    int _node_num;
244 248
    int _edge_num;
245 249

	
246 250
    FullGraphBase() {}
247 251

	
248 252
    void construct(int n) { _node_num = n; _edge_num = n * (n - 1) / 2; }
249 253

	
250 254
    int _uid(int e) const {
251 255
      int u = e / _node_num;
252 256
      int v = e % _node_num;
253 257
      return u < v ? u : _node_num - 2 - u;
254 258
    }
255 259

	
256 260
    int _vid(int e) const {
257 261
      int u = e / _node_num;
258 262
      int v = e % _node_num;
259 263
      return u < v ? v : _node_num - 1 - v;
260 264
    }
261 265

	
262 266
    void _uvid(int e, int& u, int& v) const {
263 267
      u = e / _node_num;
264 268
      v = e % _node_num;
265 269
      if  (u >= v) {
266 270
        u = _node_num - 2 - u;
267 271
        v = _node_num - 1 - v;
268 272
      }
269 273
    }
270 274

	
271 275
    void _stid(int a, int& s, int& t) const {
272 276
      if ((a & 1) == 1) {
273 277
        _uvid(a >> 1, s, t);
274 278
      } else {
275 279
        _uvid(a >> 1, t, s);
276 280
      }
277 281
    }
278 282

	
279 283
    int _eid(int u, int v) const {
280 284
      if (u < (_node_num - 1) / 2) {
281 285
        return u * _node_num + v;
282 286
      } else {
283 287
        return (_node_num - 1 - u) * _node_num - v - 1;
284 288
      }
285 289
    }
286 290

	
287 291
  public:
288 292

	
289 293
    Node operator()(int ix) const { return Node(ix); }
290 294
    static int index(const Node& node) { return node._id; }
291 295

	
292 296
    Edge edge(const Node& u, const Node& v) const {
293 297
      if (u._id < v._id) {
294 298
        return Edge(_eid(u._id, v._id));
295 299
      } else if (u._id != v._id) {
296 300
        return Edge(_eid(v._id, u._id));
297 301
      } else {
298 302
        return INVALID;
299 303
      }
300 304
    }
301 305

	
302 306
    Arc arc(const Node& s, const Node& t) const {
303 307
      if (s._id < t._id) {
304 308
        return Arc((_eid(s._id, t._id) << 1) | 1);
305 309
      } else if (s._id != t._id) {
306 310
        return Arc(_eid(t._id, s._id) << 1);
307 311
      } else {
308 312
        return INVALID;
309 313
      }
310 314
    }
311 315

	
312 316
    typedef True NodeNumTag;
313 317
    typedef True ArcNumTag;
314 318
    typedef True EdgeNumTag;
315 319

	
316 320
    int nodeNum() const { return _node_num; }
317 321
    int arcNum() const { return 2 * _edge_num; }
318 322
    int edgeNum() const { return _edge_num; }
319 323

	
320 324
    static int id(Node node) { return node._id; }
321 325
    static int id(Arc arc) { return arc._id; }
322 326
    static int id(Edge edge) { return edge._id; }
323 327

	
324 328
    int maxNodeId() const { return _node_num-1; }
325 329
    int maxArcId() const { return 2 * _edge_num-1; }
326 330
    int maxEdgeId() const { return _edge_num-1; }
327 331

	
328 332
    static Node nodeFromId(int id) { return Node(id);}
329 333
    static Arc arcFromId(int id) { return Arc(id);}
330 334
    static Edge edgeFromId(int id) { return Edge(id);}
331 335

	
332 336
    Node u(Edge edge) const {
333 337
      return Node(_uid(edge._id));
334 338
    }
335 339

	
336 340
    Node v(Edge edge) const {
337 341
      return Node(_vid(edge._id));
338 342
    }
339 343

	
340 344
    Node source(Arc arc) const {
341 345
      return Node((arc._id & 1) == 1 ?
342 346
                  _uid(arc._id >> 1) : _vid(arc._id >> 1));
343 347
    }
344 348

	
345 349
    Node target(Arc arc) const {
346 350
      return Node((arc._id & 1) == 1 ?
347 351
                  _vid(arc._id >> 1) : _uid(arc._id >> 1));
348 352
    }
349 353

	
350 354
    typedef True FindEdgeTag;
351 355
    typedef True FindArcTag;
352 356

	
353 357
    Edge findEdge(Node u, Node v, Edge prev = INVALID) const {
354 358
      return prev != INVALID ? INVALID : edge(u, v);
355 359
    }
356 360

	
357 361
    Arc findArc(Node s, Node t, Arc prev = INVALID) const {
358 362
      return prev != INVALID ? INVALID : arc(s, t);
359 363
    }
360 364

	
361 365
    class Node {
362 366
      friend class FullGraphBase;
363 367

	
364 368
    protected:
365 369
      int _id;
366 370
      Node(int id) : _id(id) {}
367 371
    public:
368 372
      Node() {}
369 373
      Node (Invalid) { _id = -1; }
370 374
      bool operator==(const Node node) const {return _id == node._id;}
371 375
      bool operator!=(const Node node) const {return _id != node._id;}
372 376
      bool operator<(const Node node) const {return _id < node._id;}
373 377
    };
374 378

	
375 379
    class Edge {
376 380
      friend class FullGraphBase;
377 381
      friend class Arc;
378 382

	
379 383
    protected:
380 384
      int _id;
381 385

	
382 386
      Edge(int id) : _id(id) {}
383 387

	
384 388
    public:
385 389
      Edge() { }
386 390
      Edge (Invalid) { _id = -1; }
387 391

	
388 392
      bool operator==(const Edge edge) const {return _id == edge._id;}
389 393
      bool operator!=(const Edge edge) const {return _id != edge._id;}
390 394
      bool operator<(const Edge edge) const {return _id < edge._id;}
391 395
    };
392 396

	
393 397
    class Arc {
394 398
      friend class FullGraphBase;
395 399

	
396 400
    protected:
397 401
      int _id;
398 402

	
399 403
      Arc(int id) : _id(id) {}
400 404

	
401 405
    public:
402 406
      Arc() { }
403 407
      Arc (Invalid) { _id = -1; }
404 408

	
405 409
      operator Edge() const { return Edge(_id != -1 ? (_id >> 1) : -1); }
406 410

	
407 411
      bool operator==(const Arc arc) const {return _id == arc._id;}
408 412
      bool operator!=(const Arc arc) const {return _id != arc._id;}
409 413
      bool operator<(const Arc arc) const {return _id < arc._id;}
410 414
    };
411 415

	
412 416
    static bool direction(Arc arc) {
413 417
      return (arc._id & 1) == 1;
414 418
    }
415 419

	
416 420
    static Arc direct(Edge edge, bool dir) {
417 421
      return Arc((edge._id << 1) | (dir ? 1 : 0));
418 422
    }
419 423

	
420 424
    void first(Node& node) const {
421 425
      node._id = _node_num - 1;
422 426
    }
423 427

	
424 428
    static void next(Node& node) {
425 429
      --node._id;
426 430
    }
427 431

	
428 432
    void first(Arc& arc) const {
429 433
      arc._id = (_edge_num << 1) - 1;
430 434
    }
431 435

	
432 436
    static void next(Arc& arc) {
433 437
      --arc._id;
434 438
    }
435 439

	
436 440
    void first(Edge& edge) const {
437 441
      edge._id = _edge_num - 1;
438 442
    }
439 443

	
440 444
    static void next(Edge& edge) {
441 445
      --edge._id;
442 446
    }
443 447

	
444 448
    void firstOut(Arc& arc, const Node& node) const {
445 449
      int s = node._id, t = _node_num - 1;
446 450
      if (s < t) {
447 451
        arc._id = (_eid(s, t) << 1) | 1;
448 452
      } else {
449 453
        --t;
450 454
        arc._id = (t != -1 ? (_eid(t, s) << 1) : -1);
451 455
      }
452 456
    }
453 457

	
454 458
    void nextOut(Arc& arc) const {
455 459
      int s, t;
456 460
      _stid(arc._id, s, t);
457 461
      --t;
458 462
      if (s < t) {
459 463
        arc._id = (_eid(s, t) << 1) | 1;
460 464
      } else {
461 465
        if (s == t) --t;
462 466
        arc._id = (t != -1 ? (_eid(t, s) << 1) : -1);
463 467
      }
464 468
    }
465 469

	
466 470
    void firstIn(Arc& arc, const Node& node) const {
467 471
      int s = _node_num - 1, t = node._id;
468 472
      if (s > t) {
469 473
        arc._id = (_eid(t, s) << 1);
470 474
      } else {
471 475
        --s;
472 476
        arc._id = (s != -1 ? (_eid(s, t) << 1) | 1 : -1);
473 477
      }
474 478
    }
475 479

	
476 480
    void nextIn(Arc& arc) const {
477 481
      int s, t;
478 482
      _stid(arc._id, s, t);
479 483
      --s;
480 484
      if (s > t) {
481 485
        arc._id = (_eid(t, s) << 1);
482 486
      } else {
483 487
        if (s == t) --s;
484 488
        arc._id = (s != -1 ? (_eid(s, t) << 1) | 1 : -1);
485 489
      }
486 490
    }
487 491

	
488 492
    void firstInc(Edge& edge, bool& dir, const Node& node) const {
489 493
      int u = node._id, v = _node_num - 1;
490 494
      if (u < v) {
491 495
        edge._id = _eid(u, v);
492 496
        dir = true;
493 497
      } else {
494 498
        --v;
495 499
        edge._id = (v != -1 ? _eid(v, u) : -1);
496 500
        dir = false;
497 501
      }
498 502
    }
499 503

	
500 504
    void nextInc(Edge& edge, bool& dir) const {
501 505
      int u, v;
502 506
      if (dir) {
503 507
        _uvid(edge._id, u, v);
504 508
        --v;
505 509
        if (u < v) {
506 510
          edge._id = _eid(u, v);
507 511
        } else {
508 512
          --v;
509 513
          edge._id = (v != -1 ? _eid(v, u) : -1);
510 514
          dir = false;
511 515
        }
512 516
      } else {
513 517
        _uvid(edge._id, v, u);
514 518
        --v;
515 519
        edge._id = (v != -1 ? _eid(v, u) : -1);
516 520
      }
517 521
    }
518 522

	
519 523
  };
520 524

	
521 525
  typedef GraphExtender<FullGraphBase> ExtendedFullGraphBase;
522 526

	
523 527
  /// \ingroup graphs
524 528
  ///
525 529
  /// \brief An undirected full graph class.
526 530
  ///
527 531
  /// FullGraph is a simple and fast implmenetation of undirected full
528 532
  /// (complete) graphs. It contains an edge between every distinct pair
529 533
  /// of nodes, therefore the number of edges is <tt>n(n-1)/2</tt>.
530 534
  /// This class is completely static and it needs constant memory space.
531 535
  /// Thus you can neither add nor delete nodes or edges, however
532 536
  /// the structure can be resized using resize().
533 537
  ///
534 538
  /// This type fully conforms to the \ref concepts::Graph "Graph concept".
535 539
  /// Most of its member functions and nested classes are documented
536 540
  /// only in the concept class.
537 541
  ///
542
  /// This class provides constant time counting for nodes, edges and arcs.
543
  ///
538 544
  /// \note FullDigraph and FullGraph classes are very similar,
539 545
  /// but there are two differences. While FullDigraph
540 546
  /// conforms only to the \ref concepts::Digraph "Digraph" concept,
541 547
  /// this class conforms to the \ref concepts::Graph "Graph" concept,
542 548
  /// moreover this class does not contain a loop for each
543 549
  /// node as FullDigraph does.
544 550
  ///
545 551
  /// \sa FullDigraph
546 552
  class FullGraph : public ExtendedFullGraphBase {
547 553
    typedef ExtendedFullGraphBase Parent;
548 554

	
549 555
  public:
550 556

	
551 557
    /// \brief Default constructor.
552 558
    ///
553 559
    /// Default constructor. The number of nodes and edges will be zero.
554 560
    FullGraph() { construct(0); }
555 561

	
556 562
    /// \brief Constructor
557 563
    ///
558 564
    /// Constructor.
559 565
    /// \param n The number of the nodes.
560 566
    FullGraph(int n) { construct(n); }
561 567

	
562 568
    /// \brief Resizes the graph
563 569
    ///
564 570
    /// This function resizes the graph. It fully destroys and
565 571
    /// rebuilds the structure, therefore the maps of the graph will be
566 572
    /// reallocated automatically and the previous values will be lost.
567 573
    void resize(int n) {
568 574
      Parent::notifier(Arc()).clear();
569 575
      Parent::notifier(Edge()).clear();
570 576
      Parent::notifier(Node()).clear();
571 577
      construct(n);
572 578
      Parent::notifier(Node()).build();
573 579
      Parent::notifier(Edge()).build();
574 580
      Parent::notifier(Arc()).build();
575 581
    }
576 582

	
577 583
    /// \brief Returns the node with the given index.
578 584
    ///
579 585
    /// Returns the node with the given index. Since this structure is 
580 586
    /// completely static, the nodes can be indexed with integers from
581 587
    /// the range <tt>[0..nodeNum()-1]</tt>.
588
    /// The index of a node is the same as its ID.
582 589
    /// \sa index()
583 590
    Node operator()(int ix) const { return Parent::operator()(ix); }
584 591

	
585 592
    /// \brief Returns the index of the given node.
586 593
    ///
587 594
    /// Returns the index of the given node. Since this structure is 
588 595
    /// completely static, the nodes can be indexed with integers from
589 596
    /// the range <tt>[0..nodeNum()-1]</tt>.
597
    /// The index of a node is the same as its ID.
590 598
    /// \sa operator()()
591 599
    static int index(const Node& node) { return Parent::index(node); }
592 600

	
593 601
    /// \brief Returns the arc connecting the given nodes.
594 602
    ///
595 603
    /// Returns the arc connecting the given nodes.
596 604
    Arc arc(Node s, Node t) const {
597 605
      return Parent::arc(s, t);
598 606
    }
599 607

	
600 608
    /// \brief Returns the edge connecting the given nodes.
601 609
    ///
602 610
    /// Returns the edge connecting the given nodes.
603 611
    Edge edge(Node u, Node v) const {
604 612
      return Parent::edge(u, v);
605 613
    }
606 614

	
607 615
    /// \brief Number of nodes.
608 616
    int nodeNum() const { return Parent::nodeNum(); }
609 617
    /// \brief Number of arcs.
610 618
    int arcNum() const { return Parent::arcNum(); }
611 619
    /// \brief Number of edges.
612 620
    int edgeNum() const { return Parent::edgeNum(); }
613 621

	
614 622
  };
615 623

	
616 624

	
617 625
} //namespace lemon
618 626

	
619 627

	
620 628
#endif //LEMON_FULL_GRAPH_H
Ignore white space 6 line context
... ...
@@ -122,576 +122,578 @@
122 122
    int maxNodeId() const { return _node_num - 1; }
123 123
    int maxEdgeId() const { return _edge_num - 1; }
124 124
    int maxArcId() const { return 2 * _edge_num - 1; }
125 125

	
126 126
    static Node nodeFromId(int id) { return Node(id);}
127 127
    static Edge edgeFromId(int id) { return Edge(id);}
128 128
    static Arc arcFromId(int id) { return Arc(id);}
129 129

	
130 130
    typedef True FindEdgeTag;
131 131
    typedef True FindArcTag;
132 132

	
133 133
    Edge findEdge(Node u, Node v, Edge prev = INVALID) const {
134 134
      if (prev != INVALID) return INVALID;
135 135
      if (v._id > u._id) {
136 136
        if (v._id - u._id == _width)
137 137
          return Edge(u._id);
138 138
        if (v._id - u._id == 1 && u._id % _width < _width - 1) {
139 139
          return Edge(u._id / _width * (_width - 1) +
140 140
                      u._id % _width + _edge_limit);
141 141
        }
142 142
      } else {
143 143
        if (u._id - v._id == _width)
144 144
          return Edge(v._id);
145 145
        if (u._id - v._id == 1 && v._id % _width < _width - 1) {
146 146
          return Edge(v._id / _width * (_width - 1) +
147 147
                      v._id % _width + _edge_limit);
148 148
        }
149 149
      }
150 150
      return INVALID;
151 151
    }
152 152

	
153 153
    Arc findArc(Node u, Node v, Arc prev = INVALID) const {
154 154
      if (prev != INVALID) return INVALID;
155 155
      if (v._id > u._id) {
156 156
        if (v._id - u._id == _width)
157 157
          return Arc((u._id << 1) | 1);
158 158
        if (v._id - u._id == 1 && u._id % _width < _width - 1) {
159 159
          return Arc(((u._id / _width * (_width - 1) +
160 160
                       u._id % _width + _edge_limit) << 1) | 1);
161 161
        }
162 162
      } else {
163 163
        if (u._id - v._id == _width)
164 164
          return Arc(v._id << 1);
165 165
        if (u._id - v._id == 1 && v._id % _width < _width - 1) {
166 166
          return Arc((v._id / _width * (_width - 1) +
167 167
                       v._id % _width + _edge_limit) << 1);
168 168
        }
169 169
      }
170 170
      return INVALID;
171 171
    }
172 172

	
173 173
    class Node {
174 174
      friend class GridGraphBase;
175 175

	
176 176
    protected:
177 177
      int _id;
178 178
      Node(int id) : _id(id) {}
179 179
    public:
180 180
      Node() {}
181 181
      Node (Invalid) : _id(-1) {}
182 182
      bool operator==(const Node node) const {return _id == node._id;}
183 183
      bool operator!=(const Node node) const {return _id != node._id;}
184 184
      bool operator<(const Node node) const {return _id < node._id;}
185 185
    };
186 186

	
187 187
    class Edge {
188 188
      friend class GridGraphBase;
189 189
      friend class Arc;
190 190

	
191 191
    protected:
192 192
      int _id;
193 193

	
194 194
      Edge(int id) : _id(id) {}
195 195

	
196 196
    public:
197 197
      Edge() {}
198 198
      Edge (Invalid) : _id(-1) {}
199 199
      bool operator==(const Edge edge) const {return _id == edge._id;}
200 200
      bool operator!=(const Edge edge) const {return _id != edge._id;}
201 201
      bool operator<(const Edge edge) const {return _id < edge._id;}
202 202
    };
203 203

	
204 204
    class Arc {
205 205
      friend class GridGraphBase;
206 206

	
207 207
    protected:
208 208
      int _id;
209 209

	
210 210
      Arc(int id) : _id(id) {}
211 211

	
212 212
    public:
213 213
      Arc() {}
214 214
      Arc (Invalid) : _id(-1) {}
215 215
      operator Edge() const { return _id != -1 ? Edge(_id >> 1) : INVALID; }
216 216
      bool operator==(const Arc arc) const {return _id == arc._id;}
217 217
      bool operator!=(const Arc arc) const {return _id != arc._id;}
218 218
      bool operator<(const Arc arc) const {return _id < arc._id;}
219 219
    };
220 220

	
221 221
    static bool direction(Arc arc) {
222 222
      return (arc._id & 1) == 1;
223 223
    }
224 224

	
225 225
    static Arc direct(Edge edge, bool dir) {
226 226
      return Arc((edge._id << 1) | (dir ? 1 : 0));
227 227
    }
228 228

	
229 229
    void first(Node& node) const {
230 230
      node._id = _node_num - 1;
231 231
    }
232 232

	
233 233
    static void next(Node& node) {
234 234
      --node._id;
235 235
    }
236 236

	
237 237
    void first(Edge& edge) const {
238 238
      edge._id = _edge_num - 1;
239 239
    }
240 240

	
241 241
    static void next(Edge& edge) {
242 242
      --edge._id;
243 243
    }
244 244

	
245 245
    void first(Arc& arc) const {
246 246
      arc._id = 2 * _edge_num - 1;
247 247
    }
248 248

	
249 249
    static void next(Arc& arc) {
250 250
      --arc._id;
251 251
    }
252 252

	
253 253
    void firstOut(Arc& arc, const Node& node) const {
254 254
      if (node._id % _width < _width - 1) {
255 255
        arc._id = (_edge_limit + node._id % _width +
256 256
                   (node._id / _width) * (_width - 1)) << 1 | 1;
257 257
        return;
258 258
      }
259 259
      if (node._id < _node_num - _width) {
260 260
        arc._id = node._id << 1 | 1;
261 261
        return;
262 262
      }
263 263
      if (node._id % _width > 0) {
264 264
        arc._id = (_edge_limit + node._id % _width +
265 265
                   (node._id / _width) * (_width - 1) - 1) << 1;
266 266
        return;
267 267
      }
268 268
      if (node._id >= _width) {
269 269
        arc._id = (node._id - _width) << 1;
270 270
        return;
271 271
      }
272 272
      arc._id = -1;
273 273
    }
274 274

	
275 275
    void nextOut(Arc& arc) const {
276 276
      int nid = arc._id >> 1;
277 277
      if ((arc._id & 1) == 1) {
278 278
        if (nid >= _edge_limit) {
279 279
          nid = (nid - _edge_limit) % (_width - 1) +
280 280
            (nid - _edge_limit) / (_width - 1) * _width;
281 281
          if (nid < _node_num - _width) {
282 282
            arc._id = nid << 1 | 1;
283 283
            return;
284 284
          }
285 285
        }
286 286
        if (nid % _width > 0) {
287 287
          arc._id = (_edge_limit + nid % _width +
288 288
                     (nid / _width) * (_width - 1) - 1) << 1;
289 289
          return;
290 290
        }
291 291
        if (nid >= _width) {
292 292
          arc._id = (nid - _width) << 1;
293 293
          return;
294 294
        }
295 295
      } else {
296 296
        if (nid >= _edge_limit) {
297 297
          nid = (nid - _edge_limit) % (_width - 1) +
298 298
            (nid - _edge_limit) / (_width - 1) * _width + 1;
299 299
          if (nid >= _width) {
300 300
            arc._id = (nid - _width) << 1;
301 301
            return;
302 302
          }
303 303
        }
304 304
      }
305 305
      arc._id = -1;
306 306
    }
307 307

	
308 308
    void firstIn(Arc& arc, const Node& node) const {
309 309
      if (node._id % _width < _width - 1) {
310 310
        arc._id = (_edge_limit + node._id % _width +
311 311
                   (node._id / _width) * (_width - 1)) << 1;
312 312
        return;
313 313
      }
314 314
      if (node._id < _node_num - _width) {
315 315
        arc._id = node._id << 1;
316 316
        return;
317 317
      }
318 318
      if (node._id % _width > 0) {
319 319
        arc._id = (_edge_limit + node._id % _width +
320 320
                   (node._id / _width) * (_width - 1) - 1) << 1 | 1;
321 321
        return;
322 322
      }
323 323
      if (node._id >= _width) {
324 324
        arc._id = (node._id - _width) << 1 | 1;
325 325
        return;
326 326
      }
327 327
      arc._id = -1;
328 328
    }
329 329

	
330 330
    void nextIn(Arc& arc) const {
331 331
      int nid = arc._id >> 1;
332 332
      if ((arc._id & 1) == 0) {
333 333
        if (nid >= _edge_limit) {
334 334
          nid = (nid - _edge_limit) % (_width - 1) +
335 335
            (nid - _edge_limit) / (_width - 1) * _width;
336 336
          if (nid < _node_num - _width) {
337 337
            arc._id = nid << 1;
338 338
            return;
339 339
          }
340 340
        }
341 341
        if (nid % _width > 0) {
342 342
          arc._id = (_edge_limit + nid % _width +
343 343
                     (nid / _width) * (_width - 1) - 1) << 1 | 1;
344 344
          return;
345 345
        }
346 346
        if (nid >= _width) {
347 347
          arc._id = (nid - _width) << 1 | 1;
348 348
          return;
349 349
        }
350 350
      } else {
351 351
        if (nid >= _edge_limit) {
352 352
          nid = (nid - _edge_limit) % (_width - 1) +
353 353
            (nid - _edge_limit) / (_width - 1) * _width + 1;
354 354
          if (nid >= _width) {
355 355
            arc._id = (nid - _width) << 1 | 1;
356 356
            return;
357 357
          }
358 358
        }
359 359
      }
360 360
      arc._id = -1;
361 361
    }
362 362

	
363 363
    void firstInc(Edge& edge, bool& dir, const Node& node) const {
364 364
      if (node._id % _width < _width - 1) {
365 365
        edge._id = _edge_limit + node._id % _width +
366 366
          (node._id / _width) * (_width - 1);
367 367
        dir = true;
368 368
        return;
369 369
      }
370 370
      if (node._id < _node_num - _width) {
371 371
        edge._id = node._id;
372 372
        dir = true;
373 373
        return;
374 374
      }
375 375
      if (node._id % _width > 0) {
376 376
        edge._id = _edge_limit + node._id % _width +
377 377
          (node._id / _width) * (_width - 1) - 1;
378 378
        dir = false;
379 379
        return;
380 380
      }
381 381
      if (node._id >= _width) {
382 382
        edge._id = node._id - _width;
383 383
        dir = false;
384 384
        return;
385 385
      }
386 386
      edge._id = -1;
387 387
      dir = true;
388 388
    }
389 389

	
390 390
    void nextInc(Edge& edge, bool& dir) const {
391 391
      int nid = edge._id;
392 392
      if (dir) {
393 393
        if (nid >= _edge_limit) {
394 394
          nid = (nid - _edge_limit) % (_width - 1) +
395 395
            (nid - _edge_limit) / (_width - 1) * _width;
396 396
          if (nid < _node_num - _width) {
397 397
            edge._id = nid;
398 398
            return;
399 399
          }
400 400
        }
401 401
        if (nid % _width > 0) {
402 402
          edge._id = _edge_limit + nid % _width +
403 403
            (nid / _width) * (_width - 1) - 1;
404 404
          dir = false;
405 405
          return;
406 406
        }
407 407
        if (nid >= _width) {
408 408
          edge._id = nid - _width;
409 409
          dir = false;
410 410
          return;
411 411
        }
412 412
      } else {
413 413
        if (nid >= _edge_limit) {
414 414
          nid = (nid - _edge_limit) % (_width - 1) +
415 415
            (nid - _edge_limit) / (_width - 1) * _width + 1;
416 416
          if (nid >= _width) {
417 417
            edge._id = nid - _width;
418 418
            return;
419 419
          }
420 420
        }
421 421
      }
422 422
      edge._id = -1;
423 423
      dir = true;
424 424
    }
425 425

	
426 426
    Arc right(Node n) const {
427 427
      if (n._id % _width < _width - 1) {
428 428
        return Arc(((_edge_limit + n._id % _width +
429 429
                    (n._id / _width) * (_width - 1)) << 1) | 1);
430 430
      } else {
431 431
        return INVALID;
432 432
      }
433 433
    }
434 434

	
435 435
    Arc left(Node n) const {
436 436
      if (n._id % _width > 0) {
437 437
        return Arc((_edge_limit + n._id % _width +
438 438
                     (n._id / _width) * (_width - 1) - 1) << 1);
439 439
      } else {
440 440
        return INVALID;
441 441
      }
442 442
    }
443 443

	
444 444
    Arc up(Node n) const {
445 445
      if (n._id < _edge_limit) {
446 446
        return Arc((n._id << 1) | 1);
447 447
      } else {
448 448
        return INVALID;
449 449
      }
450 450
    }
451 451

	
452 452
    Arc down(Node n) const {
453 453
      if (n._id >= _width) {
454 454
        return Arc((n._id - _width) << 1);
455 455
      } else {
456 456
        return INVALID;
457 457
      }
458 458
    }
459 459

	
460 460
  private:
461 461
    int _width, _height;
462 462
    int _node_num, _edge_num;
463 463
    int _edge_limit;
464 464
  };
465 465

	
466 466

	
467 467
  typedef GraphExtender<GridGraphBase> ExtendedGridGraphBase;
468 468

	
469 469
  /// \ingroup graphs
470 470
  ///
471 471
  /// \brief Grid graph class
472 472
  ///
473 473
  /// GridGraph implements a special graph type. The nodes of the
474 474
  /// graph can be indexed by two integer values \c (i,j) where \c i is
475 475
  /// in the range <tt>[0..width()-1]</tt> and j is in the range
476 476
  /// <tt>[0..height()-1]</tt>. Two nodes are connected in the graph if
477 477
  /// the indices differ exactly on one position and the difference is
478 478
  /// also exactly one. The nodes of the graph can be obtained by position
479 479
  /// using the \c operator()() function and the indices of the nodes can
480 480
  /// be obtained using \c pos(), \c col() and \c row() members. The outgoing
481 481
  /// arcs can be retrieved with the \c right(), \c up(), \c left()
482 482
  /// and \c down() functions, where the bottom-left corner is the
483 483
  /// origin.
484 484
  ///
485 485
  /// This class is completely static and it needs constant memory space.
486 486
  /// Thus you can neither add nor delete nodes or edges, however
487 487
  /// the structure can be resized using resize().
488 488
  ///
489 489
  /// \image html grid_graph.png
490 490
  /// \image latex grid_graph.eps "Grid graph" width=\textwidth
491 491
  ///
492 492
  /// A short example about the basic usage:
493 493
  ///\code
494 494
  /// GridGraph graph(rows, cols);
495 495
  /// GridGraph::NodeMap<int> val(graph);
496 496
  /// for (int i = 0; i < graph.width(); ++i) {
497 497
  ///   for (int j = 0; j < graph.height(); ++j) {
498 498
  ///     val[graph(i, j)] = i + j;
499 499
  ///   }
500 500
  /// }
501 501
  ///\endcode
502 502
  ///
503 503
  /// This type fully conforms to the \ref concepts::Graph "Graph concept".
504 504
  /// Most of its member functions and nested classes are documented
505 505
  /// only in the concept class.
506
  ///
507
  /// This class provides constant time counting for nodes, edges and arcs.
506 508
  class GridGraph : public ExtendedGridGraphBase {
507 509
    typedef ExtendedGridGraphBase Parent;
508 510

	
509 511
  public:
510 512

	
511 513
    /// \brief Map to get the indices of the nodes as \ref dim2::Point
512 514
    /// "dim2::Point<int>".
513 515
    ///
514 516
    /// Map to get the indices of the nodes as \ref dim2::Point
515 517
    /// "dim2::Point<int>".
516 518
    class IndexMap {
517 519
    public:
518 520
      /// \brief The key type of the map
519 521
      typedef GridGraph::Node Key;
520 522
      /// \brief The value type of the map
521 523
      typedef dim2::Point<int> Value;
522 524

	
523 525
      /// \brief Constructor
524 526
      IndexMap(const GridGraph& graph) : _graph(graph) {}
525 527

	
526 528
      /// \brief The subscript operator
527 529
      Value operator[](Key key) const {
528 530
        return _graph.pos(key);
529 531
      }
530 532

	
531 533
    private:
532 534
      const GridGraph& _graph;
533 535
    };
534 536

	
535 537
    /// \brief Map to get the column of the nodes.
536 538
    ///
537 539
    /// Map to get the column of the nodes.
538 540
    class ColMap {
539 541
    public:
540 542
      /// \brief The key type of the map
541 543
      typedef GridGraph::Node Key;
542 544
      /// \brief The value type of the map
543 545
      typedef int Value;
544 546

	
545 547
      /// \brief Constructor
546 548
      ColMap(const GridGraph& graph) : _graph(graph) {}
547 549

	
548 550
      /// \brief The subscript operator
549 551
      Value operator[](Key key) const {
550 552
        return _graph.col(key);
551 553
      }
552 554

	
553 555
    private:
554 556
      const GridGraph& _graph;
555 557
    };
556 558

	
557 559
    /// \brief Map to get the row of the nodes.
558 560
    ///
559 561
    /// Map to get the row of the nodes.
560 562
    class RowMap {
561 563
    public:
562 564
      /// \brief The key type of the map
563 565
      typedef GridGraph::Node Key;
564 566
      /// \brief The value type of the map
565 567
      typedef int Value;
566 568

	
567 569
      /// \brief Constructor
568 570
      RowMap(const GridGraph& graph) : _graph(graph) {}
569 571

	
570 572
      /// \brief The subscript operator
571 573
      Value operator[](Key key) const {
572 574
        return _graph.row(key);
573 575
      }
574 576

	
575 577
    private:
576 578
      const GridGraph& _graph;
577 579
    };
578 580

	
579 581
    /// \brief Constructor
580 582
    ///
581 583
    /// Construct a grid graph with the given size.
582 584
    GridGraph(int width, int height) { construct(width, height); }
583 585

	
584 586
    /// \brief Resizes the graph
585 587
    ///
586 588
    /// This function resizes the graph. It fully destroys and
587 589
    /// rebuilds the structure, therefore the maps of the graph will be
588 590
    /// reallocated automatically and the previous values will be lost.
589 591
    void resize(int width, int height) {
590 592
      Parent::notifier(Arc()).clear();
591 593
      Parent::notifier(Edge()).clear();
592 594
      Parent::notifier(Node()).clear();
593 595
      construct(width, height);
594 596
      Parent::notifier(Node()).build();
595 597
      Parent::notifier(Edge()).build();
596 598
      Parent::notifier(Arc()).build();
597 599
    }
598 600

	
599 601
    /// \brief The node on the given position.
600 602
    ///
601 603
    /// Gives back the node on the given position.
602 604
    Node operator()(int i, int j) const {
603 605
      return Parent::operator()(i, j);
604 606
    }
605 607

	
606 608
    /// \brief The column index of the node.
607 609
    ///
608 610
    /// Gives back the column index of the node.
609 611
    int col(Node n) const {
610 612
      return Parent::col(n);
611 613
    }
612 614

	
613 615
    /// \brief The row index of the node.
614 616
    ///
615 617
    /// Gives back the row index of the node.
616 618
    int row(Node n) const {
617 619
      return Parent::row(n);
618 620
    }
619 621

	
620 622
    /// \brief The position of the node.
621 623
    ///
622 624
    /// Gives back the position of the node, ie. the <tt>(col,row)</tt> pair.
623 625
    dim2::Point<int> pos(Node n) const {
624 626
      return Parent::pos(n);
625 627
    }
626 628

	
627 629
    /// \brief The number of the columns.
628 630
    ///
629 631
    /// Gives back the number of the columns.
630 632
    int width() const {
631 633
      return Parent::width();
632 634
    }
633 635

	
634 636
    /// \brief The number of the rows.
635 637
    ///
636 638
    /// Gives back the number of the rows.
637 639
    int height() const {
638 640
      return Parent::height();
639 641
    }
640 642

	
641 643
    /// \brief The arc goes right from the node.
642 644
    ///
643 645
    /// Gives back the arc goes right from the node. If there is not
644 646
    /// outgoing arc then it gives back INVALID.
645 647
    Arc right(Node n) const {
646 648
      return Parent::right(n);
647 649
    }
648 650

	
649 651
    /// \brief The arc goes left from the node.
650 652
    ///
651 653
    /// Gives back the arc goes left from the node. If there is not
652 654
    /// outgoing arc then it gives back INVALID.
653 655
    Arc left(Node n) const {
654 656
      return Parent::left(n);
655 657
    }
656 658

	
657 659
    /// \brief The arc goes up from the node.
658 660
    ///
659 661
    /// Gives back the arc goes up from the node. If there is not
660 662
    /// outgoing arc then it gives back INVALID.
661 663
    Arc up(Node n) const {
662 664
      return Parent::up(n);
663 665
    }
664 666

	
665 667
    /// \brief The arc goes down from the node.
666 668
    ///
667 669
    /// Gives back the arc goes down from the node. If there is not
668 670
    /// outgoing arc then it gives back INVALID.
669 671
    Arc down(Node n) const {
670 672
      return Parent::down(n);
671 673
    }
672 674

	
673 675
    /// \brief Index map of the grid graph
674 676
    ///
675 677
    /// Just returns an IndexMap for the grid graph.
676 678
    IndexMap indexMap() const {
677 679
      return IndexMap(*this);
678 680
    }
679 681

	
680 682
    /// \brief Row map of the grid graph
681 683
    ///
682 684
    /// Just returns a RowMap for the grid graph.
683 685
    RowMap rowMap() const {
684 686
      return RowMap(*this);
685 687
    }
686 688

	
687 689
    /// \brief Column map of the grid graph
688 690
    ///
689 691
    /// Just returns a ColMap for the grid graph.
690 692
    ColMap colMap() const {
691 693
      return ColMap(*this);
692 694
    }
693 695

	
694 696
  };
695 697

	
696 698
}
697 699
#endif
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-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 HYPERCUBE_GRAPH_H
20 20
#define HYPERCUBE_GRAPH_H
21 21

	
22 22
#include <vector>
23 23
#include <lemon/core.h>
24 24
#include <lemon/assert.h>
25 25
#include <lemon/bits/graph_extender.h>
26 26

	
27 27
///\ingroup graphs
28 28
///\file
29 29
///\brief HypercubeGraph class.
30 30

	
31 31
namespace lemon {
32 32

	
33 33
  class HypercubeGraphBase {
34 34

	
35 35
  public:
36 36

	
37 37
    typedef HypercubeGraphBase Graph;
38 38

	
39 39
    class Node;
40 40
    class Edge;
41 41
    class Arc;
42 42

	
43 43
  public:
44 44

	
45 45
    HypercubeGraphBase() {}
46 46

	
47 47
  protected:
48 48

	
49 49
    void construct(int dim) {
50 50
      LEMON_ASSERT(dim >= 1, "The number of dimensions must be at least 1.");
51 51
      _dim = dim;
52 52
      _node_num = 1 << dim;
53 53
      _edge_num = dim * (1 << (dim-1));
54 54
    }
55 55

	
56 56
  public:
57 57

	
58 58
    typedef True NodeNumTag;
59 59
    typedef True EdgeNumTag;
60 60
    typedef True ArcNumTag;
61 61

	
62 62
    int nodeNum() const { return _node_num; }
63 63
    int edgeNum() const { return _edge_num; }
64 64
    int arcNum() const { return 2 * _edge_num; }
65 65

	
66 66
    int maxNodeId() const { return _node_num - 1; }
67 67
    int maxEdgeId() const { return _edge_num - 1; }
68 68
    int maxArcId() const { return 2 * _edge_num - 1; }
69 69

	
70 70
    static Node nodeFromId(int id) { return Node(id); }
71 71
    static Edge edgeFromId(int id) { return Edge(id); }
72 72
    static Arc arcFromId(int id) { return Arc(id); }
73 73

	
74 74
    static int id(Node node) { return node._id; }
75 75
    static int id(Edge edge) { return edge._id; }
76 76
    static int id(Arc arc) { return arc._id; }
77 77

	
78 78
    Node u(Edge edge) const {
79 79
      int base = edge._id & ((1 << (_dim-1)) - 1);
80 80
      int k = edge._id >> (_dim-1);
81 81
      return ((base >> k) << (k+1)) | (base & ((1 << k) - 1));
82 82
    }
83 83

	
84 84
    Node v(Edge edge) const {
85 85
      int base = edge._id & ((1 << (_dim-1)) - 1);
86 86
      int k = edge._id >> (_dim-1);
87 87
      return ((base >> k) << (k+1)) | (base & ((1 << k) - 1)) | (1 << k);
88 88
    }
89 89

	
90 90
    Node source(Arc arc) const {
91 91
      return (arc._id & 1) == 1 ? u(arc) : v(arc);
92 92
    }
93 93

	
94 94
    Node target(Arc arc) const {
95 95
      return (arc._id & 1) == 1 ? v(arc) : u(arc);
96 96
    }
97 97

	
98 98
    typedef True FindEdgeTag;
99 99
    typedef True FindArcTag;
100 100

	
101 101
    Edge findEdge(Node u, Node v, Edge prev = INVALID) const {
102 102
      if (prev != INVALID) return INVALID;
103 103
      int d = u._id ^ v._id;
104 104
      int k = 0;
105 105
      if (d == 0) return INVALID;
106 106
      for ( ; (d & 1) == 0; d >>= 1) ++k;
107 107
      if (d >> 1 != 0) return INVALID;
108 108
      return (k << (_dim-1)) | ((u._id >> (k+1)) << k) |
109 109
        (u._id & ((1 << k) - 1));
110 110
    }
111 111

	
112 112
    Arc findArc(Node u, Node v, Arc prev = INVALID) const {
113 113
      Edge edge = findEdge(u, v, prev);
114 114
      if (edge == INVALID) return INVALID;
115 115
      int k = edge._id >> (_dim-1);
116 116
      return ((u._id >> k) & 1) == 1 ? edge._id << 1 : (edge._id << 1) | 1;
117 117
    }
118 118

	
119 119
    class Node {
120 120
      friend class HypercubeGraphBase;
121 121

	
122 122
    protected:
123 123
      int _id;
124 124
      Node(int id) : _id(id) {}
125 125
    public:
126 126
      Node() {}
127 127
      Node (Invalid) : _id(-1) {}
128 128
      bool operator==(const Node node) const {return _id == node._id;}
129 129
      bool operator!=(const Node node) const {return _id != node._id;}
130 130
      bool operator<(const Node node) const {return _id < node._id;}
131 131
    };
132 132

	
133 133
    class Edge {
134 134
      friend class HypercubeGraphBase;
135 135
      friend class Arc;
136 136

	
137 137
    protected:
138 138
      int _id;
139 139

	
140 140
      Edge(int id) : _id(id) {}
141 141

	
142 142
    public:
143 143
      Edge() {}
144 144
      Edge (Invalid) : _id(-1) {}
145 145
      bool operator==(const Edge edge) const {return _id == edge._id;}
146 146
      bool operator!=(const Edge edge) const {return _id != edge._id;}
147 147
      bool operator<(const Edge edge) const {return _id < edge._id;}
148 148
    };
149 149

	
150 150
    class Arc {
151 151
      friend class HypercubeGraphBase;
152 152

	
153 153
    protected:
154 154
      int _id;
155 155

	
156 156
      Arc(int id) : _id(id) {}
157 157

	
158 158
    public:
159 159
      Arc() {}
160 160
      Arc (Invalid) : _id(-1) {}
161 161
      operator Edge() const { return _id != -1 ? Edge(_id >> 1) : INVALID; }
162 162
      bool operator==(const Arc arc) const {return _id == arc._id;}
163 163
      bool operator!=(const Arc arc) const {return _id != arc._id;}
164 164
      bool operator<(const Arc arc) const {return _id < arc._id;}
165 165
    };
166 166

	
167 167
    void first(Node& node) const {
168 168
      node._id = _node_num - 1;
169 169
    }
170 170

	
171 171
    static void next(Node& node) {
172 172
      --node._id;
173 173
    }
174 174

	
175 175
    void first(Edge& edge) const {
176 176
      edge._id = _edge_num - 1;
177 177
    }
178 178

	
179 179
    static void next(Edge& edge) {
180 180
      --edge._id;
181 181
    }
182 182

	
183 183
    void first(Arc& arc) const {
184 184
      arc._id = 2 * _edge_num - 1;
185 185
    }
186 186

	
187 187
    static void next(Arc& arc) {
188 188
      --arc._id;
189 189
    }
190 190

	
191 191
    void firstInc(Edge& edge, bool& dir, const Node& node) const {
192 192
      edge._id = node._id >> 1;
193 193
      dir = (node._id & 1) == 0;
194 194
    }
195 195

	
196 196
    void nextInc(Edge& edge, bool& dir) const {
197 197
      Node n = dir ? u(edge) : v(edge);
198 198
      int k = (edge._id >> (_dim-1)) + 1;
199 199
      if (k < _dim) {
200 200
        edge._id = (k << (_dim-1)) |
201 201
          ((n._id >> (k+1)) << k) | (n._id & ((1 << k) - 1));
202 202
        dir = ((n._id >> k) & 1) == 0;
203 203
      } else {
204 204
        edge._id = -1;
205 205
        dir = true;
206 206
      }
207 207
    }
208 208

	
209 209
    void firstOut(Arc& arc, const Node& node) const {
210 210
      arc._id = ((node._id >> 1) << 1) | (~node._id & 1);
211 211
    }
212 212

	
213 213
    void nextOut(Arc& arc) const {
214 214
      Node n = (arc._id & 1) == 1 ? u(arc) : v(arc);
215 215
      int k = (arc._id >> _dim) + 1;
216 216
      if (k < _dim) {
217 217
        arc._id = (k << (_dim-1)) |
218 218
          ((n._id >> (k+1)) << k) | (n._id & ((1 << k) - 1));
219 219
        arc._id = (arc._id << 1) | (~(n._id >> k) & 1);
220 220
      } else {
221 221
        arc._id = -1;
222 222
      }
223 223
    }
224 224

	
225 225
    void firstIn(Arc& arc, const Node& node) const {
226 226
      arc._id = ((node._id >> 1) << 1) | (node._id & 1);
227 227
    }
228 228

	
229 229
    void nextIn(Arc& arc) const {
230 230
      Node n = (arc._id & 1) == 1 ? v(arc) : u(arc);
231 231
      int k = (arc._id >> _dim) + 1;
232 232
      if (k < _dim) {
233 233
        arc._id = (k << (_dim-1)) |
234 234
          ((n._id >> (k+1)) << k) | (n._id & ((1 << k) - 1));
235 235
        arc._id = (arc._id << 1) | ((n._id >> k) & 1);
236 236
      } else {
237 237
        arc._id = -1;
238 238
      }
239 239
    }
240 240

	
241 241
    static bool direction(Arc arc) {
242 242
      return (arc._id & 1) == 1;
243 243
    }
244 244

	
245 245
    static Arc direct(Edge edge, bool dir) {
246 246
      return Arc((edge._id << 1) | (dir ? 1 : 0));
247 247
    }
248 248

	
249 249
    int dimension() const {
250 250
      return _dim;
251 251
    }
252 252

	
253 253
    bool projection(Node node, int n) const {
254 254
      return static_cast<bool>(node._id & (1 << n));
255 255
    }
256 256

	
257 257
    int dimension(Edge edge) const {
258 258
      return edge._id >> (_dim-1);
259 259
    }
260 260

	
261 261
    int dimension(Arc arc) const {
262 262
      return arc._id >> _dim;
263 263
    }
264 264

	
265 265
    static int index(Node node) {
266 266
      return node._id;
267 267
    }
268 268

	
269 269
    Node operator()(int ix) const {
270 270
      return Node(ix);
271 271
    }
272 272

	
273 273
  private:
274 274
    int _dim;
275 275
    int _node_num, _edge_num;
276 276
  };
277 277

	
278 278

	
279 279
  typedef GraphExtender<HypercubeGraphBase> ExtendedHypercubeGraphBase;
280 280

	
281 281
  /// \ingroup graphs
282 282
  ///
283 283
  /// \brief Hypercube graph class
284 284
  ///
285 285
  /// HypercubeGraph implements a special graph type. The nodes of the
286 286
  /// graph are indexed with integers having at most \c dim binary digits.
287 287
  /// Two nodes are connected in the graph if and only if their indices
288 288
  /// differ only on one position in the binary form.
289 289
  /// This class is completely static and it needs constant memory space.
290 290
  /// Thus you can neither add nor delete nodes or edges, however 
291 291
  /// the structure can be resized using resize().
292 292
  ///
293 293
  /// This type fully conforms to the \ref concepts::Graph "Graph concept".
294 294
  /// Most of its member functions and nested classes are documented
295 295
  /// only in the concept class.
296 296
  ///
297
  /// This class provides constant time counting for nodes, edges and arcs.
298
  ///
297 299
  /// \note The type of the indices is chosen to \c int for efficiency
298 300
  /// reasons. Thus the maximum dimension of this implementation is 26
299 301
  /// (assuming that the size of \c int is 32 bit).
300 302
  class HypercubeGraph : public ExtendedHypercubeGraphBase {
301 303
    typedef ExtendedHypercubeGraphBase Parent;
302 304

	
303 305
  public:
304 306

	
305 307
    /// \brief Constructs a hypercube graph with \c dim dimensions.
306 308
    ///
307 309
    /// Constructs a hypercube graph with \c dim dimensions.
308 310
    HypercubeGraph(int dim) { construct(dim); }
309 311

	
310 312
    /// \brief Resizes the graph
311 313
    ///
312 314
    /// This function resizes the graph. It fully destroys and
313 315
    /// rebuilds the structure, therefore the maps of the graph will be
314 316
    /// reallocated automatically and the previous values will be lost.
315 317
    void resize(int dim) {
316 318
      Parent::notifier(Arc()).clear();
317 319
      Parent::notifier(Edge()).clear();
318 320
      Parent::notifier(Node()).clear();
319 321
      construct(dim);
320 322
      Parent::notifier(Node()).build();
321 323
      Parent::notifier(Edge()).build();
322 324
      Parent::notifier(Arc()).build();
323 325
    }
324 326

	
325 327
    /// \brief The number of dimensions.
326 328
    ///
327 329
    /// Gives back the number of dimensions.
328 330
    int dimension() const {
329 331
      return Parent::dimension();
330 332
    }
331 333

	
332 334
    /// \brief Returns \c true if the n'th bit of the node is one.
333 335
    ///
334 336
    /// Returns \c true if the n'th bit of the node is one.
335 337
    bool projection(Node node, int n) const {
336 338
      return Parent::projection(node, n);
337 339
    }
338 340

	
339 341
    /// \brief The dimension id of an edge.
340 342
    ///
341 343
    /// Gives back the dimension id of the given edge.
342 344
    /// It is in the range <tt>[0..dim-1]</tt>.
343 345
    int dimension(Edge edge) const {
344 346
      return Parent::dimension(edge);
345 347
    }
346 348

	
347 349
    /// \brief The dimension id of an arc.
348 350
    ///
349 351
    /// Gives back the dimension id of the given arc.
350 352
    /// It is in the range <tt>[0..dim-1]</tt>.
351 353
    int dimension(Arc arc) const {
352 354
      return Parent::dimension(arc);
353 355
    }
354 356

	
355 357
    /// \brief The index of a node.
356 358
    ///
357 359
    /// Gives back the index of the given node.
358 360
    /// The lower bits of the integer describes the node.
359 361
    static int index(Node node) {
360 362
      return Parent::index(node);
361 363
    }
362 364

	
363 365
    /// \brief Gives back a node by its index.
364 366
    ///
365 367
    /// Gives back a node by its index.
366 368
    Node operator()(int ix) const {
367 369
      return Parent::operator()(ix);
368 370
    }
369 371

	
370 372
    /// \brief Number of nodes.
371 373
    int nodeNum() const { return Parent::nodeNum(); }
372 374
    /// \brief Number of edges.
373 375
    int edgeNum() const { return Parent::edgeNum(); }
374 376
    /// \brief Number of arcs.
375 377
    int arcNum() const { return Parent::arcNum(); }
376 378

	
377 379
    /// \brief Linear combination map.
378 380
    ///
379 381
    /// This map makes possible to give back a linear combination
380 382
    /// for each node. It works like the \c std::accumulate function,
381 383
    /// so it accumulates the \c bf binary function with the \c fv first
382 384
    /// value. The map accumulates only on that positions (dimensions)
383 385
    /// where the index of the node is one. The values that have to be
384 386
    /// accumulated should be given by the \c begin and \c end iterators
385 387
    /// and the length of this range should be equal to the dimension
386 388
    /// number of the graph.
387 389
    ///
388 390
    ///\code
389 391
    /// const int DIM = 3;
390 392
    /// HypercubeGraph graph(DIM);
391 393
    /// dim2::Point<double> base[DIM];
392 394
    /// for (int k = 0; k < DIM; ++k) {
393 395
    ///   base[k].x = rnd();
394 396
    ///   base[k].y = rnd();
395 397
    /// }
396 398
    /// HypercubeGraph::HyperMap<dim2::Point<double> >
397 399
    ///   pos(graph, base, base + DIM, dim2::Point<double>(0.0, 0.0));
398 400
    ///\endcode
399 401
    ///
400 402
    /// \see HypercubeGraph
401 403
    template <typename T, typename BF = std::plus<T> >
402 404
    class HyperMap {
403 405
    public:
404 406

	
405 407
      /// \brief The key type of the map
406 408
      typedef Node Key;
407 409
      /// \brief The value type of the map
408 410
      typedef T Value;
409 411

	
410 412
      /// \brief Constructor for HyperMap.
411 413
      ///
412 414
      /// Construct a HyperMap for the given graph. The values that have
413 415
      /// to be accumulated should be given by the \c begin and \c end
414 416
      /// iterators and the length of this range should be equal to the
415 417
      /// dimension number of the graph.
416 418
      ///
417 419
      /// This map accumulates the \c bf binary function with the \c fv
418 420
      /// first value on that positions (dimensions) where the index of
419 421
      /// the node is one.
420 422
      template <typename It>
421 423
      HyperMap(const Graph& graph, It begin, It end,
422 424
               T fv = 0, const BF& bf = BF())
423 425
        : _graph(graph), _values(begin, end), _first_value(fv), _bin_func(bf)
424 426
      {
425 427
        LEMON_ASSERT(_values.size() == graph.dimension(),
426 428
                     "Wrong size of range");
427 429
      }
428 430

	
429 431
      /// \brief The partial accumulated value.
430 432
      ///
431 433
      /// Gives back the partial accumulated value.
432 434
      Value operator[](const Key& k) const {
433 435
        Value val = _first_value;
434 436
        int id = _graph.index(k);
435 437
        int n = 0;
436 438
        while (id != 0) {
437 439
          if (id & 1) {
438 440
            val = _bin_func(val, _values[n]);
439 441
          }
440 442
          id >>= 1;
441 443
          ++n;
442 444
        }
443 445
        return val;
444 446
      }
445 447

	
446 448
    private:
447 449
      const Graph& _graph;
448 450
      std::vector<T> _values;
449 451
      T _first_value;
450 452
      BF _bin_func;
451 453
    };
452 454

	
453 455
  };
454 456

	
455 457
}
456 458

	
457 459
#endif
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-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_LIST_GRAPH_H
20 20
#define LEMON_LIST_GRAPH_H
21 21

	
22 22
///\ingroup graphs
23 23
///\file
24 24
///\brief ListDigraph and ListGraph classes.
25 25

	
26 26
#include <lemon/core.h>
27 27
#include <lemon/error.h>
28 28
#include <lemon/bits/graph_extender.h>
29 29

	
30 30
#include <vector>
31 31
#include <list>
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  class ListDigraph;
36 36

	
37 37
  class ListDigraphBase {
38 38

	
39 39
  protected:
40 40
    struct NodeT {
41 41
      int first_in, first_out;
42 42
      int prev, next;
43 43
    };
44 44

	
45 45
    struct ArcT {
46 46
      int target, source;
47 47
      int prev_in, prev_out;
48 48
      int next_in, next_out;
49 49
    };
50 50

	
51 51
    std::vector<NodeT> nodes;
52 52

	
53 53
    int first_node;
54 54

	
55 55
    int first_free_node;
56 56

	
57 57
    std::vector<ArcT> arcs;
58 58

	
59 59
    int first_free_arc;
60 60

	
61 61
  public:
62 62

	
63 63
    typedef ListDigraphBase Digraph;
64 64

	
65 65
    class Node {
66 66
      friend class ListDigraphBase;
67 67
      friend class ListDigraph;
68 68
    protected:
69 69

	
70 70
      int id;
71 71
      explicit Node(int pid) { id = pid;}
72 72

	
73 73
    public:
74 74
      Node() {}
75 75
      Node (Invalid) { id = -1; }
76 76
      bool operator==(const Node& node) const {return id == node.id;}
77 77
      bool operator!=(const Node& node) const {return id != node.id;}
78 78
      bool operator<(const Node& node) const {return id < node.id;}
79 79
    };
80 80

	
81 81
    class Arc {
82 82
      friend class ListDigraphBase;
83 83
      friend class ListDigraph;
84 84
    protected:
85 85

	
86 86
      int id;
87 87
      explicit Arc(int pid) { id = pid;}
88 88

	
89 89
    public:
90 90
      Arc() {}
91 91
      Arc (Invalid) { id = -1; }
92 92
      bool operator==(const Arc& arc) const {return id == arc.id;}
93 93
      bool operator!=(const Arc& arc) const {return id != arc.id;}
94 94
      bool operator<(const Arc& arc) const {return id < arc.id;}
95 95
    };
96 96

	
97 97

	
98 98

	
99 99
    ListDigraphBase()
100 100
      : nodes(), first_node(-1),
101 101
        first_free_node(-1), arcs(), first_free_arc(-1) {}
102 102

	
103 103

	
104 104
    int maxNodeId() const { return nodes.size()-1; }
105 105
    int maxArcId() const { return arcs.size()-1; }
106 106

	
107 107
    Node source(Arc e) const { return Node(arcs[e.id].source); }
108 108
    Node target(Arc e) const { return Node(arcs[e.id].target); }
109 109

	
110 110

	
111 111
    void first(Node& node) const {
112 112
      node.id = first_node;
113 113
    }
114 114

	
115 115
    void next(Node& node) const {
116 116
      node.id = nodes[node.id].next;
117 117
    }
118 118

	
119 119

	
120 120
    void first(Arc& arc) const {
121 121
      int n;
122 122
      for(n = first_node;
123 123
          n != -1 && nodes[n].first_out == -1;
124 124
          n = nodes[n].next) {}
125 125
      arc.id = (n == -1) ? -1 : nodes[n].first_out;
126 126
    }
127 127

	
128 128
    void next(Arc& arc) const {
129 129
      if (arcs[arc.id].next_out != -1) {
130 130
        arc.id = arcs[arc.id].next_out;
131 131
      } else {
132 132
        int n;
133 133
        for(n = nodes[arcs[arc.id].source].next;
134 134
            n != -1 && nodes[n].first_out == -1;
135 135
            n = nodes[n].next) {}
136 136
        arc.id = (n == -1) ? -1 : nodes[n].first_out;
137 137
      }
138 138
    }
139 139

	
140 140
    void firstOut(Arc &e, const Node& v) const {
141 141
      e.id = nodes[v.id].first_out;
142 142
    }
143 143
    void nextOut(Arc &e) const {
144 144
      e.id=arcs[e.id].next_out;
145 145
    }
146 146

	
147 147
    void firstIn(Arc &e, const Node& v) const {
148 148
      e.id = nodes[v.id].first_in;
149 149
    }
150 150
    void nextIn(Arc &e) const {
151 151
      e.id=arcs[e.id].next_in;
152 152
    }
153 153

	
154 154

	
155 155
    static int id(Node v) { return v.id; }
156 156
    static int id(Arc e) { return e.id; }
157 157

	
158 158
    static Node nodeFromId(int id) { return Node(id);}
159 159
    static Arc arcFromId(int id) { return Arc(id);}
160 160

	
161 161
    bool valid(Node n) const {
162 162
      return n.id >= 0 && n.id < static_cast<int>(nodes.size()) &&
163 163
        nodes[n.id].prev != -2;
164 164
    }
165 165

	
166 166
    bool valid(Arc a) const {
167 167
      return a.id >= 0 && a.id < static_cast<int>(arcs.size()) &&
168 168
        arcs[a.id].prev_in != -2;
169 169
    }
170 170

	
171 171
    Node addNode() {
172 172
      int n;
173 173

	
174 174
      if(first_free_node==-1) {
175 175
        n = nodes.size();
176 176
        nodes.push_back(NodeT());
177 177
      } else {
178 178
        n = first_free_node;
179 179
        first_free_node = nodes[n].next;
180 180
      }
181 181

	
182 182
      nodes[n].next = first_node;
183 183
      if(first_node != -1) nodes[first_node].prev = n;
184 184
      first_node = n;
185 185
      nodes[n].prev = -1;
186 186

	
187 187
      nodes[n].first_in = nodes[n].first_out = -1;
188 188

	
189 189
      return Node(n);
190 190
    }
191 191

	
192 192
    Arc addArc(Node u, Node v) {
193 193
      int n;
194 194

	
195 195
      if (first_free_arc == -1) {
196 196
        n = arcs.size();
197 197
        arcs.push_back(ArcT());
198 198
      } else {
199 199
        n = first_free_arc;
200 200
        first_free_arc = arcs[n].next_in;
201 201
      }
202 202

	
203 203
      arcs[n].source = u.id;
204 204
      arcs[n].target = v.id;
205 205

	
206 206
      arcs[n].next_out = nodes[u.id].first_out;
207 207
      if(nodes[u.id].first_out != -1) {
208 208
        arcs[nodes[u.id].first_out].prev_out = n;
209 209
      }
210 210

	
211 211
      arcs[n].next_in = nodes[v.id].first_in;
212 212
      if(nodes[v.id].first_in != -1) {
213 213
        arcs[nodes[v.id].first_in].prev_in = n;
214 214
      }
215 215

	
216 216
      arcs[n].prev_in = arcs[n].prev_out = -1;
217 217

	
218 218
      nodes[u.id].first_out = nodes[v.id].first_in = n;
219 219

	
220 220
      return Arc(n);
221 221
    }
222 222

	
223 223
    void erase(const Node& node) {
224 224
      int n = node.id;
225 225

	
226 226
      if(nodes[n].next != -1) {
227 227
        nodes[nodes[n].next].prev = nodes[n].prev;
228 228
      }
229 229

	
230 230
      if(nodes[n].prev != -1) {
231 231
        nodes[nodes[n].prev].next = nodes[n].next;
232 232
      } else {
233 233
        first_node = nodes[n].next;
234 234
      }
235 235

	
236 236
      nodes[n].next = first_free_node;
237 237
      first_free_node = n;
238 238
      nodes[n].prev = -2;
239 239

	
240 240
    }
241 241

	
242 242
    void erase(const Arc& arc) {
243 243
      int n = arc.id;
244 244

	
245 245
      if(arcs[n].next_in!=-1) {
246 246
        arcs[arcs[n].next_in].prev_in = arcs[n].prev_in;
247 247
      }
248 248

	
249 249
      if(arcs[n].prev_in!=-1) {
250 250
        arcs[arcs[n].prev_in].next_in = arcs[n].next_in;
251 251
      } else {
252 252
        nodes[arcs[n].target].first_in = arcs[n].next_in;
253 253
      }
254 254

	
255 255

	
256 256
      if(arcs[n].next_out!=-1) {
257 257
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
258 258
      }
259 259

	
260 260
      if(arcs[n].prev_out!=-1) {
261 261
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
262 262
      } else {
263 263
        nodes[arcs[n].source].first_out = arcs[n].next_out;
264 264
      }
265 265

	
266 266
      arcs[n].next_in = first_free_arc;
267 267
      first_free_arc = n;
268 268
      arcs[n].prev_in = -2;
269 269
    }
270 270

	
271 271
    void clear() {
272 272
      arcs.clear();
273 273
      nodes.clear();
274 274
      first_node = first_free_node = first_free_arc = -1;
275 275
    }
276 276

	
277 277
  protected:
278 278
    void changeTarget(Arc e, Node n)
279 279
    {
280 280
      if(arcs[e.id].next_in != -1)
281 281
        arcs[arcs[e.id].next_in].prev_in = arcs[e.id].prev_in;
282 282
      if(arcs[e.id].prev_in != -1)
283 283
        arcs[arcs[e.id].prev_in].next_in = arcs[e.id].next_in;
284 284
      else nodes[arcs[e.id].target].first_in = arcs[e.id].next_in;
285 285
      if (nodes[n.id].first_in != -1) {
286 286
        arcs[nodes[n.id].first_in].prev_in = e.id;
287 287
      }
288 288
      arcs[e.id].target = n.id;
289 289
      arcs[e.id].prev_in = -1;
290 290
      arcs[e.id].next_in = nodes[n.id].first_in;
291 291
      nodes[n.id].first_in = e.id;
292 292
    }
293 293
    void changeSource(Arc e, Node n)
294 294
    {
295 295
      if(arcs[e.id].next_out != -1)
296 296
        arcs[arcs[e.id].next_out].prev_out = arcs[e.id].prev_out;
297 297
      if(arcs[e.id].prev_out != -1)
298 298
        arcs[arcs[e.id].prev_out].next_out = arcs[e.id].next_out;
299 299
      else nodes[arcs[e.id].source].first_out = arcs[e.id].next_out;
300 300
      if (nodes[n.id].first_out != -1) {
301 301
        arcs[nodes[n.id].first_out].prev_out = e.id;
302 302
      }
303 303
      arcs[e.id].source = n.id;
304 304
      arcs[e.id].prev_out = -1;
305 305
      arcs[e.id].next_out = nodes[n.id].first_out;
306 306
      nodes[n.id].first_out = e.id;
307 307
    }
308 308

	
309 309
  };
310 310

	
311 311
  typedef DigraphExtender<ListDigraphBase> ExtendedListDigraphBase;
312 312

	
313 313
  /// \addtogroup graphs
314 314
  /// @{
315 315

	
316 316
  ///A general directed graph structure.
317 317

	
318 318
  ///\ref ListDigraph is a versatile and fast directed graph
319 319
  ///implementation based on linked lists that are stored in
320 320
  ///\c std::vector structures.
321 321
  ///
322 322
  ///This type fully conforms to the \ref concepts::Digraph "Digraph concept"
323 323
  ///and it also provides several useful additional functionalities.
324 324
  ///Most of its member functions and nested classes are documented
325 325
  ///only in the concept class.
326 326
  ///
327
  ///This class provides only linear time counting for nodes and arcs.
328
  ///
327 329
  ///\sa concepts::Digraph
328 330
  ///\sa ListGraph
329 331
  class ListDigraph : public ExtendedListDigraphBase {
330 332
    typedef ExtendedListDigraphBase Parent;
331 333

	
332 334
  private:
333 335
    /// Digraphs are \e not copy constructible. Use DigraphCopy instead.
334 336
    ListDigraph(const ListDigraph &) :ExtendedListDigraphBase() {};
335 337
    /// \brief Assignment of a digraph to another one is \e not allowed.
336 338
    /// Use DigraphCopy instead.
337 339
    void operator=(const ListDigraph &) {}
338 340
  public:
339 341

	
340 342
    /// Constructor
341 343

	
342 344
    /// Constructor.
343 345
    ///
344 346
    ListDigraph() {}
345 347

	
346 348
    ///Add a new node to the digraph.
347 349

	
348 350
    ///This function adds a new node to the digraph.
349 351
    ///\return The new node.
350 352
    Node addNode() { return Parent::addNode(); }
351 353

	
352 354
    ///Add a new arc to the digraph.
353 355

	
354 356
    ///This function adds a new arc to the digraph with source node \c s
355 357
    ///and target node \c t.
356 358
    ///\return The new arc.
357 359
    Arc addArc(Node s, Node t) {
358 360
      return Parent::addArc(s, t);
359 361
    }
360 362

	
361 363
    ///\brief Erase a node from the digraph.
362 364
    ///
363
    ///This function erases the given node from the digraph.
365
    ///This function erases the given node along with its outgoing and
366
    ///incoming arcs from the digraph.
367
    ///
368
    ///\note All iterators referencing the removed node or the connected
369
    ///arcs are invalidated, of course.
364 370
    void erase(Node n) { Parent::erase(n); }
365 371

	
366 372
    ///\brief Erase an arc from the digraph.
367 373
    ///
368 374
    ///This function erases the given arc from the digraph.
375
    ///
376
    ///\note All iterators referencing the removed arc are invalidated,
377
    ///of course.
369 378
    void erase(Arc a) { Parent::erase(a); }
370 379

	
371 380
    /// Node validity check
372 381

	
373 382
    /// This function gives back \c true if the given node is valid,
374 383
    /// i.e. it is a real node of the digraph.
375 384
    ///
376 385
    /// \warning A removed node could become valid again if new nodes are
377 386
    /// added to the digraph.
378 387
    bool valid(Node n) const { return Parent::valid(n); }
379 388

	
380 389
    /// Arc validity check
381 390

	
382 391
    /// This function gives back \c true if the given arc is valid,
383 392
    /// i.e. it is a real arc of the digraph.
384 393
    ///
385 394
    /// \warning A removed arc could become valid again if new arcs are
386 395
    /// added to the digraph.
387 396
    bool valid(Arc a) const { return Parent::valid(a); }
388 397

	
389 398
    /// Change the target node of an arc
390 399

	
391 400
    /// This function changes the target node of the given arc \c a to \c n.
392 401
    ///
393 402
    ///\note \c ArcIt and \c OutArcIt iterators referencing the changed
394 403
    ///arc remain valid, however \c InArcIt iterators are invalidated.
395 404
    ///
396 405
    ///\warning This functionality cannot be used together with the Snapshot
397 406
    ///feature.
398 407
    void changeTarget(Arc a, Node n) {
399 408
      Parent::changeTarget(a,n);
400 409
    }
401 410
    /// Change the source node of an arc
402 411

	
403 412
    /// This function changes the source node of the given arc \c a to \c n.
404 413
    ///
405 414
    ///\note \c InArcIt iterators referencing the changed arc remain
406 415
    ///valid, however \c ArcIt and \c OutArcIt iterators are invalidated.
407 416
    ///
408 417
    ///\warning This functionality cannot be used together with the Snapshot
409 418
    ///feature.
410 419
    void changeSource(Arc a, Node n) {
411 420
      Parent::changeSource(a,n);
412 421
    }
413 422

	
414 423
    /// Reverse the direction of an arc.
415 424

	
416 425
    /// This function reverses the direction of the given arc.
417 426
    ///\note \c ArcIt, \c OutArcIt and \c InArcIt iterators referencing
418 427
    ///the changed arc are invalidated.
419 428
    ///
420 429
    ///\warning This functionality cannot be used together with the Snapshot
421 430
    ///feature.
422 431
    void reverseArc(Arc a) {
423 432
      Node t=target(a);
424 433
      changeTarget(a,source(a));
425 434
      changeSource(a,t);
426 435
    }
427 436

	
428 437
    ///Contract two nodes.
429 438

	
430 439
    ///This function contracts the given two nodes.
431 440
    ///Node \c v is removed, but instead of deleting its
432 441
    ///incident arcs, they are joined to node \c u.
433 442
    ///If the last parameter \c r is \c true (this is the default value),
434 443
    ///then the newly created loops are removed.
435 444
    ///
436 445
    ///\note The moved arcs are joined to node \c u using changeSource()
437 446
    ///or changeTarget(), thus \c ArcIt and \c OutArcIt iterators are
438 447
    ///invalidated for the outgoing arcs of node \c v and \c InArcIt
439 448
    ///iterators are invalidated for the incomming arcs of \c v.
440 449
    ///Moreover all iterators referencing node \c v or the removed 
441 450
    ///loops are also invalidated. Other iterators remain valid.
442 451
    ///
443 452
    ///\warning This functionality cannot be used together with the Snapshot
444 453
    ///feature.
445 454
    void contract(Node u, Node v, bool r = true)
446 455
    {
447 456
      for(OutArcIt e(*this,v);e!=INVALID;) {
448 457
        OutArcIt f=e;
449 458
        ++f;
450 459
        if(r && target(e)==u) erase(e);
451 460
        else changeSource(e,u);
452 461
        e=f;
453 462
      }
454 463
      for(InArcIt e(*this,v);e!=INVALID;) {
455 464
        InArcIt f=e;
456 465
        ++f;
457 466
        if(r && source(e)==u) erase(e);
458 467
        else changeTarget(e,u);
459 468
        e=f;
460 469
      }
461 470
      erase(v);
462 471
    }
463 472

	
464 473
    ///Split a node.
465 474

	
466 475
    ///This function splits the given node. First, a new node is added
467 476
    ///to the digraph, then the source of each outgoing arc of node \c n
468 477
    ///is moved to this new node.
469 478
    ///If the second parameter \c connect is \c true (this is the default
470 479
    ///value), then a new arc from node \c n to the newly created node
471 480
    ///is also added.
472 481
    ///\return The newly created node.
473 482
    ///
474 483
    ///\note All iterators remain valid.
475 484
    ///
476 485
    ///\warning This functionality cannot be used together with the
477 486
    ///Snapshot feature.
478 487
    Node split(Node n, bool connect = true) {
479 488
      Node b = addNode();
480 489
      nodes[b.id].first_out=nodes[n.id].first_out;
481 490
      nodes[n.id].first_out=-1;
482 491
      for(int i=nodes[b.id].first_out; i!=-1; i=arcs[i].next_out) {
483 492
        arcs[i].source=b.id;
484 493
      }
485 494
      if (connect) addArc(n,b);
486 495
      return b;
487 496
    }
488 497

	
489 498
    ///Split an arc.
490 499

	
491 500
    ///This function splits the given arc. First, a new node \c v is
492 501
    ///added to the digraph, then the target node of the original arc
493 502
    ///is set to \c v. Finally, an arc from \c v to the original target
494 503
    ///is added.
495 504
    ///\return The newly created node.
496 505
    ///
497 506
    ///\note \c InArcIt iterators referencing the original arc are
498 507
    ///invalidated. Other iterators remain valid.
499 508
    ///
500 509
    ///\warning This functionality cannot be used together with the
501 510
    ///Snapshot feature.
502 511
    Node split(Arc a) {
503 512
      Node v = addNode();
504 513
      addArc(v,target(a));
505 514
      changeTarget(a,v);
506 515
      return v;
507 516
    }
508 517

	
509 518
    ///Clear the digraph.
510 519

	
511 520
    ///This function erases all nodes and arcs from the digraph.
512 521
    ///
522
    ///\note All iterators of the digraph are invalidated, of course.
513 523
    void clear() {
514 524
      Parent::clear();
515 525
    }
516 526

	
517 527
    /// Reserve memory for nodes.
518 528

	
519 529
    /// Using this function, it is possible to avoid superfluous memory
520 530
    /// allocation: if you know that the digraph you want to build will
521 531
    /// be large (e.g. it will contain millions of nodes and/or arcs),
522 532
    /// then it is worth reserving space for this amount before starting
523 533
    /// to build the digraph.
524 534
    /// \sa reserveArc()
525 535
    void reserveNode(int n) { nodes.reserve(n); };
526 536

	
527 537
    /// Reserve memory for arcs.
528 538

	
529 539
    /// Using this function, it is possible to avoid superfluous memory
530 540
    /// allocation: if you know that the digraph you want to build will
531 541
    /// be large (e.g. it will contain millions of nodes and/or arcs),
532 542
    /// then it is worth reserving space for this amount before starting
533 543
    /// to build the digraph.
534 544
    /// \sa reserveNode()
535 545
    void reserveArc(int m) { arcs.reserve(m); };
536 546

	
537 547
    /// \brief Class to make a snapshot of the digraph and restore
538 548
    /// it later.
539 549
    ///
540 550
    /// Class to make a snapshot of the digraph and restore it later.
541 551
    ///
542 552
    /// The newly added nodes and arcs can be removed using the
543 553
    /// restore() function.
544 554
    ///
545 555
    /// \note After a state is restored, you cannot restore a later state, 
546 556
    /// i.e. you cannot add the removed nodes and arcs again using
547 557
    /// another Snapshot instance.
548 558
    ///
549 559
    /// \warning Node and arc deletions and other modifications (e.g.
550 560
    /// reversing, contracting, splitting arcs or nodes) cannot be
551 561
    /// restored. These events invalidate the snapshot.
552 562
    /// However the arcs and nodes that were added to the digraph after
553 563
    /// making the current snapshot can be removed without invalidating it.
554 564
    class Snapshot {
555 565
    protected:
556 566

	
557 567
      typedef Parent::NodeNotifier NodeNotifier;
558 568

	
559 569
      class NodeObserverProxy : public NodeNotifier::ObserverBase {
560 570
      public:
561 571

	
562 572
        NodeObserverProxy(Snapshot& _snapshot)
563 573
          : snapshot(_snapshot) {}
564 574

	
565 575
        using NodeNotifier::ObserverBase::attach;
566 576
        using NodeNotifier::ObserverBase::detach;
567 577
        using NodeNotifier::ObserverBase::attached;
568 578

	
569 579
      protected:
570 580

	
571 581
        virtual void add(const Node& node) {
572 582
          snapshot.addNode(node);
573 583
        }
574 584
        virtual void add(const std::vector<Node>& nodes) {
575 585
          for (int i = nodes.size() - 1; i >= 0; ++i) {
576 586
            snapshot.addNode(nodes[i]);
577 587
          }
578 588
        }
579 589
        virtual void erase(const Node& node) {
580 590
          snapshot.eraseNode(node);
581 591
        }
582 592
        virtual void erase(const std::vector<Node>& nodes) {
583 593
          for (int i = 0; i < int(nodes.size()); ++i) {
584 594
            snapshot.eraseNode(nodes[i]);
585 595
          }
586 596
        }
587 597
        virtual void build() {
588 598
          Node node;
589 599
          std::vector<Node> nodes;
590 600
          for (notifier()->first(node); node != INVALID;
591 601
               notifier()->next(node)) {
592 602
            nodes.push_back(node);
593 603
          }
594 604
          for (int i = nodes.size() - 1; i >= 0; --i) {
595 605
            snapshot.addNode(nodes[i]);
596 606
          }
597 607
        }
598 608
        virtual void clear() {
599 609
          Node node;
600 610
          for (notifier()->first(node); node != INVALID;
601 611
               notifier()->next(node)) {
602 612
            snapshot.eraseNode(node);
603 613
          }
604 614
        }
605 615

	
606 616
        Snapshot& snapshot;
607 617
      };
608 618

	
609 619
      class ArcObserverProxy : public ArcNotifier::ObserverBase {
610 620
      public:
611 621

	
612 622
        ArcObserverProxy(Snapshot& _snapshot)
613 623
          : snapshot(_snapshot) {}
614 624

	
615 625
        using ArcNotifier::ObserverBase::attach;
616 626
        using ArcNotifier::ObserverBase::detach;
617 627
        using ArcNotifier::ObserverBase::attached;
618 628

	
619 629
      protected:
620 630

	
621 631
        virtual void add(const Arc& arc) {
622 632
          snapshot.addArc(arc);
623 633
        }
624 634
        virtual void add(const std::vector<Arc>& arcs) {
625 635
          for (int i = arcs.size() - 1; i >= 0; ++i) {
626 636
            snapshot.addArc(arcs[i]);
627 637
          }
628 638
        }
629 639
        virtual void erase(const Arc& arc) {
630 640
          snapshot.eraseArc(arc);
631 641
        }
632 642
        virtual void erase(const std::vector<Arc>& arcs) {
633 643
          for (int i = 0; i < int(arcs.size()); ++i) {
634 644
            snapshot.eraseArc(arcs[i]);
635 645
          }
636 646
        }
637 647
        virtual void build() {
638 648
          Arc arc;
639 649
          std::vector<Arc> arcs;
640 650
          for (notifier()->first(arc); arc != INVALID;
641 651
               notifier()->next(arc)) {
642 652
            arcs.push_back(arc);
643 653
          }
644 654
          for (int i = arcs.size() - 1; i >= 0; --i) {
645 655
            snapshot.addArc(arcs[i]);
646 656
          }
647 657
        }
648 658
        virtual void clear() {
649 659
          Arc arc;
650 660
          for (notifier()->first(arc); arc != INVALID;
651 661
               notifier()->next(arc)) {
652 662
            snapshot.eraseArc(arc);
653 663
          }
654 664
        }
655 665

	
656 666
        Snapshot& snapshot;
657 667
      };
658 668

	
659 669
      ListDigraph *digraph;
660 670

	
661 671
      NodeObserverProxy node_observer_proxy;
662 672
      ArcObserverProxy arc_observer_proxy;
663 673

	
664 674
      std::list<Node> added_nodes;
665 675
      std::list<Arc> added_arcs;
666 676

	
667 677

	
668 678
      void addNode(const Node& node) {
669 679
        added_nodes.push_front(node);
670 680
      }
671 681
      void eraseNode(const Node& node) {
672 682
        std::list<Node>::iterator it =
673 683
          std::find(added_nodes.begin(), added_nodes.end(), node);
674 684
        if (it == added_nodes.end()) {
675 685
          clear();
676 686
          arc_observer_proxy.detach();
677 687
          throw NodeNotifier::ImmediateDetach();
678 688
        } else {
679 689
          added_nodes.erase(it);
680 690
        }
681 691
      }
682 692

	
683 693
      void addArc(const Arc& arc) {
684 694
        added_arcs.push_front(arc);
685 695
      }
686 696
      void eraseArc(const Arc& arc) {
687 697
        std::list<Arc>::iterator it =
688 698
          std::find(added_arcs.begin(), added_arcs.end(), arc);
689 699
        if (it == added_arcs.end()) {
690 700
          clear();
691 701
          node_observer_proxy.detach();
692 702
          throw ArcNotifier::ImmediateDetach();
693 703
        } else {
694 704
          added_arcs.erase(it);
695 705
        }
696 706
      }
697 707

	
698 708
      void attach(ListDigraph &_digraph) {
699 709
        digraph = &_digraph;
700 710
        node_observer_proxy.attach(digraph->notifier(Node()));
701 711
        arc_observer_proxy.attach(digraph->notifier(Arc()));
702 712
      }
703 713

	
704 714
      void detach() {
705 715
        node_observer_proxy.detach();
706 716
        arc_observer_proxy.detach();
707 717
      }
708 718

	
709 719
      bool attached() const {
710 720
        return node_observer_proxy.attached();
711 721
      }
712 722

	
713 723
      void clear() {
714 724
        added_nodes.clear();
715 725
        added_arcs.clear();
716 726
      }
717 727

	
718 728
    public:
719 729

	
720 730
      /// \brief Default constructor.
721 731
      ///
722 732
      /// Default constructor.
723 733
      /// You have to call save() to actually make a snapshot.
724 734
      Snapshot()
725 735
        : digraph(0), node_observer_proxy(*this),
726 736
          arc_observer_proxy(*this) {}
727 737

	
728 738
      /// \brief Constructor that immediately makes a snapshot.
729 739
      ///
730 740
      /// This constructor immediately makes a snapshot of the given digraph.
731 741
      Snapshot(ListDigraph &gr)
732 742
        : node_observer_proxy(*this),
733 743
          arc_observer_proxy(*this) {
734 744
        attach(gr);
735 745
      }
736 746

	
737 747
      /// \brief Make a snapshot.
738 748
      ///
739 749
      /// This function makes a snapshot of the given digraph.
740 750
      /// It can be called more than once. In case of a repeated
741 751
      /// call, the previous snapshot gets lost.
742 752
      void save(ListDigraph &gr) {
743 753
        if (attached()) {
744 754
          detach();
745 755
          clear();
746 756
        }
747 757
        attach(gr);
748 758
      }
749 759

	
750 760
      /// \brief Undo the changes until the last snapshot.
751 761
      ///
752 762
      /// This function undos the changes until the last snapshot
753 763
      /// created by save() or Snapshot(ListDigraph&).
754 764
      ///
755 765
      /// \warning This method invalidates the snapshot, i.e. repeated
756 766
      /// restoring is not supported unless you call save() again.
757 767
      void restore() {
758 768
        detach();
759 769
        for(std::list<Arc>::iterator it = added_arcs.begin();
760 770
            it != added_arcs.end(); ++it) {
761 771
          digraph->erase(*it);
762 772
        }
763 773
        for(std::list<Node>::iterator it = added_nodes.begin();
764 774
            it != added_nodes.end(); ++it) {
765 775
          digraph->erase(*it);
766 776
        }
767 777
        clear();
768 778
      }
769 779

	
770 780
      /// \brief Returns \c true if the snapshot is valid.
771 781
      ///
772 782
      /// This function returns \c true if the snapshot is valid.
773 783
      bool valid() const {
774 784
        return attached();
775 785
      }
776 786
    };
777 787

	
778 788
  };
779 789

	
780 790
  ///@}
781 791

	
782 792
  class ListGraphBase {
783 793

	
784 794
  protected:
785 795

	
786 796
    struct NodeT {
787 797
      int first_out;
788 798
      int prev, next;
789 799
    };
790 800

	
791 801
    struct ArcT {
792 802
      int target;
793 803
      int prev_out, next_out;
794 804
    };
795 805

	
796 806
    std::vector<NodeT> nodes;
797 807

	
798 808
    int first_node;
799 809

	
800 810
    int first_free_node;
801 811

	
802 812
    std::vector<ArcT> arcs;
803 813

	
804 814
    int first_free_arc;
805 815

	
806 816
  public:
807 817

	
808 818
    typedef ListGraphBase Graph;
809 819

	
810 820
    class Node {
811 821
      friend class ListGraphBase;
812 822
    protected:
813 823

	
814 824
      int id;
815 825
      explicit Node(int pid) { id = pid;}
816 826

	
817 827
    public:
818 828
      Node() {}
819 829
      Node (Invalid) { id = -1; }
820 830
      bool operator==(const Node& node) const {return id == node.id;}
821 831
      bool operator!=(const Node& node) const {return id != node.id;}
822 832
      bool operator<(const Node& node) const {return id < node.id;}
823 833
    };
824 834

	
825 835
    class Edge {
826 836
      friend class ListGraphBase;
827 837
    protected:
828 838

	
829 839
      int id;
830 840
      explicit Edge(int pid) { id = pid;}
831 841

	
832 842
    public:
833 843
      Edge() {}
834 844
      Edge (Invalid) { id = -1; }
835 845
      bool operator==(const Edge& edge) const {return id == edge.id;}
836 846
      bool operator!=(const Edge& edge) const {return id != edge.id;}
837 847
      bool operator<(const Edge& edge) const {return id < edge.id;}
838 848
    };
839 849

	
840 850
    class Arc {
841 851
      friend class ListGraphBase;
842 852
    protected:
843 853

	
844 854
      int id;
845 855
      explicit Arc(int pid) { id = pid;}
846 856

	
847 857
    public:
848 858
      operator Edge() const {
849 859
        return id != -1 ? edgeFromId(id / 2) : INVALID;
850 860
      }
851 861

	
852 862
      Arc() {}
853 863
      Arc (Invalid) { id = -1; }
854 864
      bool operator==(const Arc& arc) const {return id == arc.id;}
855 865
      bool operator!=(const Arc& arc) const {return id != arc.id;}
856 866
      bool operator<(const Arc& arc) const {return id < arc.id;}
857 867
    };
858 868

	
859 869
    ListGraphBase()
860 870
      : nodes(), first_node(-1),
861 871
        first_free_node(-1), arcs(), first_free_arc(-1) {}
862 872

	
863 873

	
864 874
    int maxNodeId() const { return nodes.size()-1; }
865 875
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
866 876
    int maxArcId() const { return arcs.size()-1; }
867 877

	
868 878
    Node source(Arc e) const { return Node(arcs[e.id ^ 1].target); }
869 879
    Node target(Arc e) const { return Node(arcs[e.id].target); }
870 880

	
871 881
    Node u(Edge e) const { return Node(arcs[2 * e.id].target); }
872 882
    Node v(Edge e) const { return Node(arcs[2 * e.id + 1].target); }
873 883

	
874 884
    static bool direction(Arc e) {
875 885
      return (e.id & 1) == 1;
876 886
    }
877 887

	
878 888
    static Arc direct(Edge e, bool d) {
879 889
      return Arc(e.id * 2 + (d ? 1 : 0));
880 890
    }
881 891

	
882 892
    void first(Node& node) const {
883 893
      node.id = first_node;
884 894
    }
885 895

	
886 896
    void next(Node& node) const {
887 897
      node.id = nodes[node.id].next;
888 898
    }
889 899

	
890 900
    void first(Arc& e) const {
891 901
      int n = first_node;
892 902
      while (n != -1 && nodes[n].first_out == -1) {
893 903
        n = nodes[n].next;
894 904
      }
895 905
      e.id = (n == -1) ? -1 : nodes[n].first_out;
896 906
    }
897 907

	
898 908
    void next(Arc& e) const {
899 909
      if (arcs[e.id].next_out != -1) {
900 910
        e.id = arcs[e.id].next_out;
901 911
      } else {
902 912
        int n = nodes[arcs[e.id ^ 1].target].next;
903 913
        while(n != -1 && nodes[n].first_out == -1) {
904 914
          n = nodes[n].next;
905 915
        }
906 916
        e.id = (n == -1) ? -1 : nodes[n].first_out;
907 917
      }
908 918
    }
909 919

	
910 920
    void first(Edge& e) const {
911 921
      int n = first_node;
912 922
      while (n != -1) {
913 923
        e.id = nodes[n].first_out;
914 924
        while ((e.id & 1) != 1) {
915 925
          e.id = arcs[e.id].next_out;
916 926
        }
917 927
        if (e.id != -1) {
918 928
          e.id /= 2;
919 929
          return;
920 930
        }
921 931
        n = nodes[n].next;
922 932
      }
923 933
      e.id = -1;
924 934
    }
925 935

	
926 936
    void next(Edge& e) const {
927 937
      int n = arcs[e.id * 2].target;
928 938
      e.id = arcs[(e.id * 2) | 1].next_out;
929 939
      while ((e.id & 1) != 1) {
930 940
        e.id = arcs[e.id].next_out;
931 941
      }
932 942
      if (e.id != -1) {
933 943
        e.id /= 2;
934 944
        return;
935 945
      }
936 946
      n = nodes[n].next;
937 947
      while (n != -1) {
938 948
        e.id = nodes[n].first_out;
939 949
        while ((e.id & 1) != 1) {
940 950
          e.id = arcs[e.id].next_out;
941 951
        }
942 952
        if (e.id != -1) {
943 953
          e.id /= 2;
944 954
          return;
945 955
        }
946 956
        n = nodes[n].next;
947 957
      }
948 958
      e.id = -1;
949 959
    }
950 960

	
951 961
    void firstOut(Arc &e, const Node& v) const {
952 962
      e.id = nodes[v.id].first_out;
953 963
    }
954 964
    void nextOut(Arc &e) const {
955 965
      e.id = arcs[e.id].next_out;
956 966
    }
957 967

	
958 968
    void firstIn(Arc &e, const Node& v) const {
959 969
      e.id = ((nodes[v.id].first_out) ^ 1);
960 970
      if (e.id == -2) e.id = -1;
961 971
    }
962 972
    void nextIn(Arc &e) const {
963 973
      e.id = ((arcs[e.id ^ 1].next_out) ^ 1);
964 974
      if (e.id == -2) e.id = -1;
965 975
    }
966 976

	
967 977
    void firstInc(Edge &e, bool& d, const Node& v) const {
968 978
      int a = nodes[v.id].first_out;
969 979
      if (a != -1 ) {
970 980
        e.id = a / 2;
971 981
        d = ((a & 1) == 1);
972 982
      } else {
973 983
        e.id = -1;
974 984
        d = true;
975 985
      }
976 986
    }
977 987
    void nextInc(Edge &e, bool& d) const {
978 988
      int a = (arcs[(e.id * 2) | (d ? 1 : 0)].next_out);
979 989
      if (a != -1 ) {
980 990
        e.id = a / 2;
981 991
        d = ((a & 1) == 1);
982 992
      } else {
983 993
        e.id = -1;
984 994
        d = true;
985 995
      }
986 996
    }
987 997

	
988 998
    static int id(Node v) { return v.id; }
989 999
    static int id(Arc e) { return e.id; }
990 1000
    static int id(Edge e) { return e.id; }
991 1001

	
992 1002
    static Node nodeFromId(int id) { return Node(id);}
993 1003
    static Arc arcFromId(int id) { return Arc(id);}
994 1004
    static Edge edgeFromId(int id) { return Edge(id);}
995 1005

	
996 1006
    bool valid(Node n) const {
997 1007
      return n.id >= 0 && n.id < static_cast<int>(nodes.size()) &&
998 1008
        nodes[n.id].prev != -2;
999 1009
    }
1000 1010

	
1001 1011
    bool valid(Arc a) const {
1002 1012
      return a.id >= 0 && a.id < static_cast<int>(arcs.size()) &&
1003 1013
        arcs[a.id].prev_out != -2;
1004 1014
    }
1005 1015

	
1006 1016
    bool valid(Edge e) const {
1007 1017
      return e.id >= 0 && 2 * e.id < static_cast<int>(arcs.size()) &&
1008 1018
        arcs[2 * e.id].prev_out != -2;
1009 1019
    }
1010 1020

	
1011 1021
    Node addNode() {
1012 1022
      int n;
1013 1023

	
1014 1024
      if(first_free_node==-1) {
1015 1025
        n = nodes.size();
1016 1026
        nodes.push_back(NodeT());
1017 1027
      } else {
1018 1028
        n = first_free_node;
1019 1029
        first_free_node = nodes[n].next;
1020 1030
      }
1021 1031

	
1022 1032
      nodes[n].next = first_node;
1023 1033
      if (first_node != -1) nodes[first_node].prev = n;
1024 1034
      first_node = n;
1025 1035
      nodes[n].prev = -1;
1026 1036

	
1027 1037
      nodes[n].first_out = -1;
1028 1038

	
1029 1039
      return Node(n);
1030 1040
    }
1031 1041

	
1032 1042
    Edge addEdge(Node u, Node v) {
1033 1043
      int n;
1034 1044

	
1035 1045
      if (first_free_arc == -1) {
1036 1046
        n = arcs.size();
1037 1047
        arcs.push_back(ArcT());
1038 1048
        arcs.push_back(ArcT());
1039 1049
      } else {
1040 1050
        n = first_free_arc;
1041 1051
        first_free_arc = arcs[n].next_out;
1042 1052
      }
1043 1053

	
1044 1054
      arcs[n].target = u.id;
1045 1055
      arcs[n | 1].target = v.id;
1046 1056

	
1047 1057
      arcs[n].next_out = nodes[v.id].first_out;
1048 1058
      if (nodes[v.id].first_out != -1) {
1049 1059
        arcs[nodes[v.id].first_out].prev_out = n;
1050 1060
      }
1051 1061
      arcs[n].prev_out = -1;
1052 1062
      nodes[v.id].first_out = n;
1053 1063

	
1054 1064
      arcs[n | 1].next_out = nodes[u.id].first_out;
1055 1065
      if (nodes[u.id].first_out != -1) {
1056 1066
        arcs[nodes[u.id].first_out].prev_out = (n | 1);
1057 1067
      }
1058 1068
      arcs[n | 1].prev_out = -1;
1059 1069
      nodes[u.id].first_out = (n | 1);
1060 1070

	
1061 1071
      return Edge(n / 2);
1062 1072
    }
1063 1073

	
1064 1074
    void erase(const Node& node) {
1065 1075
      int n = node.id;
1066 1076

	
1067 1077
      if(nodes[n].next != -1) {
1068 1078
        nodes[nodes[n].next].prev = nodes[n].prev;
1069 1079
      }
1070 1080

	
1071 1081
      if(nodes[n].prev != -1) {
1072 1082
        nodes[nodes[n].prev].next = nodes[n].next;
1073 1083
      } else {
1074 1084
        first_node = nodes[n].next;
1075 1085
      }
1076 1086

	
1077 1087
      nodes[n].next = first_free_node;
1078 1088
      first_free_node = n;
1079 1089
      nodes[n].prev = -2;
1080 1090
    }
1081 1091

	
1082 1092
    void erase(const Edge& edge) {
1083 1093
      int n = edge.id * 2;
1084 1094

	
1085 1095
      if (arcs[n].next_out != -1) {
1086 1096
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
1087 1097
      }
1088 1098

	
1089 1099
      if (arcs[n].prev_out != -1) {
1090 1100
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
1091 1101
      } else {
1092 1102
        nodes[arcs[n | 1].target].first_out = arcs[n].next_out;
1093 1103
      }
1094 1104

	
1095 1105
      if (arcs[n | 1].next_out != -1) {
1096 1106
        arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out;
1097 1107
      }
1098 1108

	
1099 1109
      if (arcs[n | 1].prev_out != -1) {
1100 1110
        arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out;
1101 1111
      } else {
1102 1112
        nodes[arcs[n].target].first_out = arcs[n | 1].next_out;
1103 1113
      }
1104 1114

	
1105 1115
      arcs[n].next_out = first_free_arc;
1106 1116
      first_free_arc = n;
1107 1117
      arcs[n].prev_out = -2;
1108 1118
      arcs[n | 1].prev_out = -2;
1109 1119

	
1110 1120
    }
1111 1121

	
1112 1122
    void clear() {
1113 1123
      arcs.clear();
1114 1124
      nodes.clear();
1115 1125
      first_node = first_free_node = first_free_arc = -1;
1116 1126
    }
1117 1127

	
1118 1128
  protected:
1119 1129

	
1120 1130
    void changeV(Edge e, Node n) {
1121 1131
      if(arcs[2 * e.id].next_out != -1) {
1122 1132
        arcs[arcs[2 * e.id].next_out].prev_out = arcs[2 * e.id].prev_out;
1123 1133
      }
1124 1134
      if(arcs[2 * e.id].prev_out != -1) {
1125 1135
        arcs[arcs[2 * e.id].prev_out].next_out =
1126 1136
          arcs[2 * e.id].next_out;
1127 1137
      } else {
1128 1138
        nodes[arcs[(2 * e.id) | 1].target].first_out =
1129 1139
          arcs[2 * e.id].next_out;
1130 1140
      }
1131 1141

	
1132 1142
      if (nodes[n.id].first_out != -1) {
1133 1143
        arcs[nodes[n.id].first_out].prev_out = 2 * e.id;
1134 1144
      }
1135 1145
      arcs[(2 * e.id) | 1].target = n.id;
1136 1146
      arcs[2 * e.id].prev_out = -1;
1137 1147
      arcs[2 * e.id].next_out = nodes[n.id].first_out;
1138 1148
      nodes[n.id].first_out = 2 * e.id;
1139 1149
    }
1140 1150

	
1141 1151
    void changeU(Edge e, Node n) {
1142 1152
      if(arcs[(2 * e.id) | 1].next_out != -1) {
1143 1153
        arcs[arcs[(2 * e.id) | 1].next_out].prev_out =
1144 1154
          arcs[(2 * e.id) | 1].prev_out;
1145 1155
      }
1146 1156
      if(arcs[(2 * e.id) | 1].prev_out != -1) {
1147 1157
        arcs[arcs[(2 * e.id) | 1].prev_out].next_out =
1148 1158
          arcs[(2 * e.id) | 1].next_out;
1149 1159
      } else {
1150 1160
        nodes[arcs[2 * e.id].target].first_out =
1151 1161
          arcs[(2 * e.id) | 1].next_out;
1152 1162
      }
1153 1163

	
1154 1164
      if (nodes[n.id].first_out != -1) {
1155 1165
        arcs[nodes[n.id].first_out].prev_out = ((2 * e.id) | 1);
1156 1166
      }
1157 1167
      arcs[2 * e.id].target = n.id;
1158 1168
      arcs[(2 * e.id) | 1].prev_out = -1;
1159 1169
      arcs[(2 * e.id) | 1].next_out = nodes[n.id].first_out;
1160 1170
      nodes[n.id].first_out = ((2 * e.id) | 1);
1161 1171
    }
1162 1172

	
1163 1173
  };
1164 1174

	
1165 1175
  typedef GraphExtender<ListGraphBase> ExtendedListGraphBase;
1166 1176

	
1167 1177

	
1168 1178
  /// \addtogroup graphs
1169 1179
  /// @{
1170 1180

	
1171 1181
  ///A general undirected graph structure.
1172 1182

	
1173 1183
  ///\ref ListGraph is a versatile and fast undirected graph
1174 1184
  ///implementation based on linked lists that are stored in
1175 1185
  ///\c std::vector structures.
1176 1186
  ///
1177 1187
  ///This type fully conforms to the \ref concepts::Graph "Graph concept"
1178 1188
  ///and it also provides several useful additional functionalities.
1179 1189
  ///Most of its member functions and nested classes are documented
1180 1190
  ///only in the concept class.
1181 1191
  ///
1192
  ///This class provides only linear time counting for nodes, edges and arcs.
1193
  ///
1182 1194
  ///\sa concepts::Graph
1183 1195
  ///\sa ListDigraph
1184 1196
  class ListGraph : public ExtendedListGraphBase {
1185 1197
    typedef ExtendedListGraphBase Parent;
1186 1198

	
1187 1199
  private:
1188 1200
    /// Graphs are \e not copy constructible. Use GraphCopy instead.
1189 1201
    ListGraph(const ListGraph &) :ExtendedListGraphBase()  {};
1190 1202
    /// \brief Assignment of a graph to another one is \e not allowed.
1191 1203
    /// Use GraphCopy instead.
1192 1204
    void operator=(const ListGraph &) {}
1193 1205
  public:
1194 1206
    /// Constructor
1195 1207

	
1196 1208
    /// Constructor.
1197 1209
    ///
1198 1210
    ListGraph() {}
1199 1211

	
1200 1212
    typedef Parent::OutArcIt IncEdgeIt;
1201 1213

	
1202 1214
    /// \brief Add a new node to the graph.
1203 1215
    ///
1204 1216
    /// This function adds a new node to the graph.
1205 1217
    /// \return The new node.
1206 1218
    Node addNode() { return Parent::addNode(); }
1207 1219

	
1208 1220
    /// \brief Add a new edge to the graph.
1209 1221
    ///
1210 1222
    /// This function adds a new edge to the graph between nodes
1211 1223
    /// \c u and \c v with inherent orientation from node \c u to
1212 1224
    /// node \c v.
1213 1225
    /// \return The new edge.
1214 1226
    Edge addEdge(Node u, Node v) {
1215 1227
      return Parent::addEdge(u, v);
1216 1228
    }
1217 1229

	
1218 1230
    ///\brief Erase a node from the graph.
1219 1231
    ///
1220
    /// This function erases the given node from the graph.
1232
    /// This function erases the given node along with its incident arcs
1233
    /// from the graph.
1234
    ///
1235
    /// \note All iterators referencing the removed node or the incident
1236
    /// edges are invalidated, of course.
1221 1237
    void erase(Node n) { Parent::erase(n); }
1222 1238

	
1223 1239
    ///\brief Erase an edge from the graph.
1224 1240
    ///
1225 1241
    /// This function erases the given edge from the graph.
1242
    ///
1243
    /// \note All iterators referencing the removed edge are invalidated,
1244
    /// of course.
1226 1245
    void erase(Edge e) { Parent::erase(e); }
1227 1246
    /// Node validity check
1228 1247

	
1229 1248
    /// This function gives back \c true if the given node is valid,
1230 1249
    /// i.e. it is a real node of the graph.
1231 1250
    ///
1232 1251
    /// \warning A removed node could become valid again if new nodes are
1233 1252
    /// added to the graph.
1234 1253
    bool valid(Node n) const { return Parent::valid(n); }
1235 1254
    /// Edge validity check
1236 1255

	
1237 1256
    /// This function gives back \c true if the given edge is valid,
1238 1257
    /// i.e. it is a real edge of the graph.
1239 1258
    ///
1240 1259
    /// \warning A removed edge could become valid again if new edges are
1241 1260
    /// added to the graph.
1242 1261
    bool valid(Edge e) const { return Parent::valid(e); }
1243 1262
    /// Arc validity check
1244 1263

	
1245 1264
    /// This function gives back \c true if the given arc is valid,
1246 1265
    /// i.e. it is a real arc of the graph.
1247 1266
    ///
1248 1267
    /// \warning A removed arc could become valid again if new edges are
1249 1268
    /// added to the graph.
1250 1269
    bool valid(Arc a) const { return Parent::valid(a); }
1251 1270

	
1252 1271
    /// \brief Change the first node of an edge.
1253 1272
    ///
1254 1273
    /// This function changes the first node of the given edge \c e to \c n.
1255 1274
    ///
1256 1275
    ///\note \c EdgeIt and \c ArcIt iterators referencing the
1257 1276
    ///changed edge are invalidated and all other iterators whose
1258 1277
    ///base node is the changed node are also invalidated.
1259 1278
    ///
1260 1279
    ///\warning This functionality cannot be used together with the
1261 1280
    ///Snapshot feature.
1262 1281
    void changeU(Edge e, Node n) {
1263 1282
      Parent::changeU(e,n);
1264 1283
    }
1265 1284
    /// \brief Change the second node of an edge.
1266 1285
    ///
1267 1286
    /// This function changes the second node of the given edge \c e to \c n.
1268 1287
    ///
1269 1288
    ///\note \c EdgeIt iterators referencing the changed edge remain
1270 1289
    ///valid, however \c ArcIt iterators referencing the changed edge and
1271 1290
    ///all other iterators whose base node is the changed node are also
1272 1291
    ///invalidated.
1273 1292
    ///
1274 1293
    ///\warning This functionality cannot be used together with the
1275 1294
    ///Snapshot feature.
1276 1295
    void changeV(Edge e, Node n) {
1277 1296
      Parent::changeV(e,n);
1278 1297
    }
1279 1298

	
1280 1299
    /// \brief Contract two nodes.
1281 1300
    ///
1282 1301
    /// This function contracts the given two nodes.
1283 1302
    /// Node \c b is removed, but instead of deleting
1284 1303
    /// its incident edges, they are joined to node \c a.
1285 1304
    /// If the last parameter \c r is \c true (this is the default value),
1286 1305
    /// then the newly created loops are removed.
1287 1306
    ///
1288 1307
    /// \note The moved edges are joined to node \c a using changeU()
1289 1308
    /// or changeV(), thus all edge and arc iterators whose base node is
1290 1309
    /// \c b are invalidated.
1291 1310
    /// Moreover all iterators referencing node \c b or the removed 
1292 1311
    /// loops are also invalidated. Other iterators remain valid.
1293 1312
    ///
1294 1313
    ///\warning This functionality cannot be used together with the
1295 1314
    ///Snapshot feature.
1296 1315
    void contract(Node a, Node b, bool r = true) {
1297 1316
      for(IncEdgeIt e(*this, b); e!=INVALID;) {
1298 1317
        IncEdgeIt f = e; ++f;
1299 1318
        if (r && runningNode(e) == a) {
1300 1319
          erase(e);
1301 1320
        } else if (u(e) == b) {
1302 1321
          changeU(e, a);
1303 1322
        } else {
1304 1323
          changeV(e, a);
1305 1324
        }
1306 1325
        e = f;
1307 1326
      }
1308 1327
      erase(b);
1309 1328
    }
1310 1329

	
1311 1330
    ///Clear the graph.
1312 1331

	
1313 1332
    ///This function erases all nodes and arcs from the graph.
1314 1333
    ///
1334
    ///\note All iterators of the graph are invalidated, of course.
1315 1335
    void clear() {
1316 1336
      Parent::clear();
1317 1337
    }
1318 1338

	
1319 1339
    /// Reserve memory for nodes.
1320 1340

	
1321 1341
    /// Using this function, it is possible to avoid superfluous memory
1322 1342
    /// allocation: if you know that the graph you want to build will
1323 1343
    /// be large (e.g. it will contain millions of nodes and/or edges),
1324 1344
    /// then it is worth reserving space for this amount before starting
1325 1345
    /// to build the graph.
1326 1346
    /// \sa reserveEdge()
1327 1347
    void reserveNode(int n) { nodes.reserve(n); };
1328 1348

	
1329 1349
    /// Reserve memory for edges.
1330 1350

	
1331 1351
    /// Using this function, it is possible to avoid superfluous memory
1332 1352
    /// allocation: if you know that the graph you want to build will
1333 1353
    /// be large (e.g. it will contain millions of nodes and/or edges),
1334 1354
    /// then it is worth reserving space for this amount before starting
1335 1355
    /// to build the graph.
1336 1356
    /// \sa reserveNode()
1337 1357
    void reserveEdge(int m) { arcs.reserve(2 * m); };
1338 1358

	
1339 1359
    /// \brief Class to make a snapshot of the graph and restore
1340 1360
    /// it later.
1341 1361
    ///
1342 1362
    /// Class to make a snapshot of the graph and restore it later.
1343 1363
    ///
1344 1364
    /// The newly added nodes and edges can be removed
1345 1365
    /// using the restore() function.
1346 1366
    ///
1347 1367
    /// \note After a state is restored, you cannot restore a later state, 
1348 1368
    /// i.e. you cannot add the removed nodes and edges again using
1349 1369
    /// another Snapshot instance.
1350 1370
    ///
1351 1371
    /// \warning Node and edge deletions and other modifications
1352 1372
    /// (e.g. changing the end-nodes of edges or contracting nodes)
1353 1373
    /// cannot be restored. These events invalidate the snapshot.
1354 1374
    /// However the edges and nodes that were added to the graph after
1355 1375
    /// making the current snapshot can be removed without invalidating it.
1356 1376
    class Snapshot {
1357 1377
    protected:
1358 1378

	
1359 1379
      typedef Parent::NodeNotifier NodeNotifier;
1360 1380

	
1361 1381
      class NodeObserverProxy : public NodeNotifier::ObserverBase {
1362 1382
      public:
1363 1383

	
1364 1384
        NodeObserverProxy(Snapshot& _snapshot)
1365 1385
          : snapshot(_snapshot) {}
1366 1386

	
1367 1387
        using NodeNotifier::ObserverBase::attach;
1368 1388
        using NodeNotifier::ObserverBase::detach;
1369 1389
        using NodeNotifier::ObserverBase::attached;
1370 1390

	
1371 1391
      protected:
1372 1392

	
1373 1393
        virtual void add(const Node& node) {
1374 1394
          snapshot.addNode(node);
1375 1395
        }
1376 1396
        virtual void add(const std::vector<Node>& nodes) {
1377 1397
          for (int i = nodes.size() - 1; i >= 0; ++i) {
1378 1398
            snapshot.addNode(nodes[i]);
1379 1399
          }
1380 1400
        }
1381 1401
        virtual void erase(const Node& node) {
1382 1402
          snapshot.eraseNode(node);
1383 1403
        }
1384 1404
        virtual void erase(const std::vector<Node>& nodes) {
1385 1405
          for (int i = 0; i < int(nodes.size()); ++i) {
1386 1406
            snapshot.eraseNode(nodes[i]);
1387 1407
          }
1388 1408
        }
1389 1409
        virtual void build() {
1390 1410
          Node node;
1391 1411
          std::vector<Node> nodes;
1392 1412
          for (notifier()->first(node); node != INVALID;
1393 1413
               notifier()->next(node)) {
1394 1414
            nodes.push_back(node);
1395 1415
          }
1396 1416
          for (int i = nodes.size() - 1; i >= 0; --i) {
1397 1417
            snapshot.addNode(nodes[i]);
1398 1418
          }
1399 1419
        }
1400 1420
        virtual void clear() {
1401 1421
          Node node;
1402 1422
          for (notifier()->first(node); node != INVALID;
1403 1423
               notifier()->next(node)) {
1404 1424
            snapshot.eraseNode(node);
1405 1425
          }
1406 1426
        }
1407 1427

	
1408 1428
        Snapshot& snapshot;
1409 1429
      };
1410 1430

	
1411 1431
      class EdgeObserverProxy : public EdgeNotifier::ObserverBase {
1412 1432
      public:
1413 1433

	
1414 1434
        EdgeObserverProxy(Snapshot& _snapshot)
1415 1435
          : snapshot(_snapshot) {}
1416 1436

	
1417 1437
        using EdgeNotifier::ObserverBase::attach;
1418 1438
        using EdgeNotifier::ObserverBase::detach;
1419 1439
        using EdgeNotifier::ObserverBase::attached;
1420 1440

	
1421 1441
      protected:
1422 1442

	
1423 1443
        virtual void add(const Edge& edge) {
1424 1444
          snapshot.addEdge(edge);
1425 1445
        }
1426 1446
        virtual void add(const std::vector<Edge>& edges) {
1427 1447
          for (int i = edges.size() - 1; i >= 0; ++i) {
1428 1448
            snapshot.addEdge(edges[i]);
1429 1449
          }
1430 1450
        }
1431 1451
        virtual void erase(const Edge& edge) {
1432 1452
          snapshot.eraseEdge(edge);
1433 1453
        }
1434 1454
        virtual void erase(const std::vector<Edge>& edges) {
1435 1455
          for (int i = 0; i < int(edges.size()); ++i) {
1436 1456
            snapshot.eraseEdge(edges[i]);
1437 1457
          }
1438 1458
        }
1439 1459
        virtual void build() {
1440 1460
          Edge edge;
1441 1461
          std::vector<Edge> edges;
1442 1462
          for (notifier()->first(edge); edge != INVALID;
1443 1463
               notifier()->next(edge)) {
1444 1464
            edges.push_back(edge);
1445 1465
          }
1446 1466
          for (int i = edges.size() - 1; i >= 0; --i) {
1447 1467
            snapshot.addEdge(edges[i]);
1448 1468
          }
1449 1469
        }
1450 1470
        virtual void clear() {
1451 1471
          Edge edge;
1452 1472
          for (notifier()->first(edge); edge != INVALID;
1453 1473
               notifier()->next(edge)) {
1454 1474
            snapshot.eraseEdge(edge);
1455 1475
          }
1456 1476
        }
1457 1477

	
1458 1478
        Snapshot& snapshot;
1459 1479
      };
1460 1480

	
1461 1481
      ListGraph *graph;
1462 1482

	
1463 1483
      NodeObserverProxy node_observer_proxy;
1464 1484
      EdgeObserverProxy edge_observer_proxy;
1465 1485

	
1466 1486
      std::list<Node> added_nodes;
1467 1487
      std::list<Edge> added_edges;
1468 1488

	
1469 1489

	
1470 1490
      void addNode(const Node& node) {
1471 1491
        added_nodes.push_front(node);
1472 1492
      }
1473 1493
      void eraseNode(const Node& node) {
1474 1494
        std::list<Node>::iterator it =
1475 1495
          std::find(added_nodes.begin(), added_nodes.end(), node);
1476 1496
        if (it == added_nodes.end()) {
1477 1497
          clear();
1478 1498
          edge_observer_proxy.detach();
1479 1499
          throw NodeNotifier::ImmediateDetach();
1480 1500
        } else {
1481 1501
          added_nodes.erase(it);
1482 1502
        }
1483 1503
      }
1484 1504

	
1485 1505
      void addEdge(const Edge& edge) {
1486 1506
        added_edges.push_front(edge);
1487 1507
      }
1488 1508
      void eraseEdge(const Edge& edge) {
1489 1509
        std::list<Edge>::iterator it =
1490 1510
          std::find(added_edges.begin(), added_edges.end(), edge);
1491 1511
        if (it == added_edges.end()) {
1492 1512
          clear();
1493 1513
          node_observer_proxy.detach();
1494 1514
          throw EdgeNotifier::ImmediateDetach();
1495 1515
        } else {
1496 1516
          added_edges.erase(it);
1497 1517
        }
1498 1518
      }
1499 1519

	
1500 1520
      void attach(ListGraph &_graph) {
1501 1521
        graph = &_graph;
1502 1522
        node_observer_proxy.attach(graph->notifier(Node()));
1503 1523
        edge_observer_proxy.attach(graph->notifier(Edge()));
1504 1524
      }
1505 1525

	
1506 1526
      void detach() {
1507 1527
        node_observer_proxy.detach();
1508 1528
        edge_observer_proxy.detach();
1509 1529
      }
1510 1530

	
1511 1531
      bool attached() const {
1512 1532
        return node_observer_proxy.attached();
1513 1533
      }
1514 1534

	
1515 1535
      void clear() {
1516 1536
        added_nodes.clear();
1517 1537
        added_edges.clear();
1518 1538
      }
1519 1539

	
1520 1540
    public:
1521 1541

	
1522 1542
      /// \brief Default constructor.
1523 1543
      ///
1524 1544
      /// Default constructor.
1525 1545
      /// You have to call save() to actually make a snapshot.
1526 1546
      Snapshot()
1527 1547
        : graph(0), node_observer_proxy(*this),
1528 1548
          edge_observer_proxy(*this) {}
1529 1549

	
1530 1550
      /// \brief Constructor that immediately makes a snapshot.
1531 1551
      ///
1532 1552
      /// This constructor immediately makes a snapshot of the given graph.
1533 1553
      Snapshot(ListGraph &gr)
1534 1554
        : node_observer_proxy(*this),
1535 1555
          edge_observer_proxy(*this) {
1536 1556
        attach(gr);
1537 1557
      }
1538 1558

	
1539 1559
      /// \brief Make a snapshot.
1540 1560
      ///
1541 1561
      /// This function makes a snapshot of the given graph.
1542 1562
      /// It can be called more than once. In case of a repeated
1543 1563
      /// call, the previous snapshot gets lost.
1544 1564
      void save(ListGraph &gr) {
1545 1565
        if (attached()) {
1546 1566
          detach();
1547 1567
          clear();
1548 1568
        }
1549 1569
        attach(gr);
1550 1570
      }
1551 1571

	
1552 1572
      /// \brief Undo the changes until the last snapshot.
1553 1573
      ///
1554 1574
      /// This function undos the changes until the last snapshot
1555 1575
      /// created by save() or Snapshot(ListGraph&).
1556 1576
      ///
1557 1577
      /// \warning This method invalidates the snapshot, i.e. repeated
1558 1578
      /// restoring is not supported unless you call save() again.
1559 1579
      void restore() {
1560 1580
        detach();
1561 1581
        for(std::list<Edge>::iterator it = added_edges.begin();
1562 1582
            it != added_edges.end(); ++it) {
1563 1583
          graph->erase(*it);
1564 1584
        }
1565 1585
        for(std::list<Node>::iterator it = added_nodes.begin();
1566 1586
            it != added_nodes.end(); ++it) {
1567 1587
          graph->erase(*it);
1568 1588
        }
1569 1589
        clear();
1570 1590
      }
1571 1591

	
1572 1592
      /// \brief Returns \c true if the snapshot is valid.
1573 1593
      ///
1574 1594
      /// This function returns \c true if the snapshot is valid.
1575 1595
      bool valid() const {
1576 1596
        return attached();
1577 1597
      }
1578 1598
    };
1579 1599
  };
1580 1600

	
1581 1601
  /// @}
1582 1602
} //namespace lemon
1583 1603

	
1584 1604

	
1585 1605
#endif
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-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_SMART_GRAPH_H
20 20
#define LEMON_SMART_GRAPH_H
21 21

	
22 22
///\ingroup graphs
23 23
///\file
24 24
///\brief SmartDigraph and SmartGraph classes.
25 25

	
26 26
#include <vector>
27 27

	
28 28
#include <lemon/core.h>
29 29
#include <lemon/error.h>
30 30
#include <lemon/bits/graph_extender.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  class SmartDigraph;
35 35

	
36 36
  class SmartDigraphBase {
37 37
  protected:
38 38

	
39 39
    struct NodeT
40 40
    {
41 41
      int first_in, first_out;
42 42
      NodeT() {}
43 43
    };
44 44
    struct ArcT
45 45
    {
46 46
      int target, source, next_in, next_out;
47 47
      ArcT() {}
48 48
    };
49 49

	
50 50
    std::vector<NodeT> nodes;
51 51
    std::vector<ArcT> arcs;
52 52

	
53 53
  public:
54 54

	
55 55
    typedef SmartDigraphBase Digraph;
56 56

	
57 57
    class Node;
58 58
    class Arc;
59 59

	
60 60
  public:
61 61

	
62 62
    SmartDigraphBase() : nodes(), arcs() { }
63 63
    SmartDigraphBase(const SmartDigraphBase &_g)
64 64
      : nodes(_g.nodes), arcs(_g.arcs) { }
65 65

	
66 66
    typedef True NodeNumTag;
67 67
    typedef True ArcNumTag;
68 68

	
69 69
    int nodeNum() const { return nodes.size(); }
70 70
    int arcNum() const { return arcs.size(); }
71 71

	
72 72
    int maxNodeId() const { return nodes.size()-1; }
73 73
    int maxArcId() const { return arcs.size()-1; }
74 74

	
75 75
    Node addNode() {
76 76
      int n = nodes.size();
77 77
      nodes.push_back(NodeT());
78 78
      nodes[n].first_in = -1;
79 79
      nodes[n].first_out = -1;
80 80
      return Node(n);
81 81
    }
82 82

	
83 83
    Arc addArc(Node u, Node v) {
84 84
      int n = arcs.size();
85 85
      arcs.push_back(ArcT());
86 86
      arcs[n].source = u._id;
87 87
      arcs[n].target = v._id;
88 88
      arcs[n].next_out = nodes[u._id].first_out;
89 89
      arcs[n].next_in = nodes[v._id].first_in;
90 90
      nodes[u._id].first_out = nodes[v._id].first_in = n;
91 91

	
92 92
      return Arc(n);
93 93
    }
94 94

	
95 95
    void clear() {
96 96
      arcs.clear();
97 97
      nodes.clear();
98 98
    }
99 99

	
100 100
    Node source(Arc a) const { return Node(arcs[a._id].source); }
101 101
    Node target(Arc a) const { return Node(arcs[a._id].target); }
102 102

	
103 103
    static int id(Node v) { return v._id; }
104 104
    static int id(Arc a) { return a._id; }
105 105

	
106 106
    static Node nodeFromId(int id) { return Node(id);}
107 107
    static Arc arcFromId(int id) { return Arc(id);}
108 108

	
109 109
    bool valid(Node n) const {
110 110
      return n._id >= 0 && n._id < static_cast<int>(nodes.size());
111 111
    }
112 112
    bool valid(Arc a) const {
113 113
      return a._id >= 0 && a._id < static_cast<int>(arcs.size());
114 114
    }
115 115

	
116 116
    class Node {
117 117
      friend class SmartDigraphBase;
118 118
      friend class SmartDigraph;
119 119

	
120 120
    protected:
121 121
      int _id;
122 122
      explicit Node(int id) : _id(id) {}
123 123
    public:
124 124
      Node() {}
125 125
      Node (Invalid) : _id(-1) {}
126 126
      bool operator==(const Node i) const {return _id == i._id;}
127 127
      bool operator!=(const Node i) const {return _id != i._id;}
128 128
      bool operator<(const Node i) const {return _id < i._id;}
129 129
    };
130 130

	
131 131

	
132 132
    class Arc {
133 133
      friend class SmartDigraphBase;
134 134
      friend class SmartDigraph;
135 135

	
136 136
    protected:
137 137
      int _id;
138 138
      explicit Arc(int id) : _id(id) {}
139 139
    public:
140 140
      Arc() { }
141 141
      Arc (Invalid) : _id(-1) {}
142 142
      bool operator==(const Arc i) const {return _id == i._id;}
143 143
      bool operator!=(const Arc i) const {return _id != i._id;}
144 144
      bool operator<(const Arc i) const {return _id < i._id;}
145 145
    };
146 146

	
147 147
    void first(Node& node) const {
148 148
      node._id = nodes.size() - 1;
149 149
    }
150 150

	
151 151
    static void next(Node& node) {
152 152
      --node._id;
153 153
    }
154 154

	
155 155
    void first(Arc& arc) const {
156 156
      arc._id = arcs.size() - 1;
157 157
    }
158 158

	
159 159
    static void next(Arc& arc) {
160 160
      --arc._id;
161 161
    }
162 162

	
163 163
    void firstOut(Arc& arc, const Node& node) const {
164 164
      arc._id = nodes[node._id].first_out;
165 165
    }
166 166

	
167 167
    void nextOut(Arc& arc) const {
168 168
      arc._id = arcs[arc._id].next_out;
169 169
    }
170 170

	
171 171
    void firstIn(Arc& arc, const Node& node) const {
172 172
      arc._id = nodes[node._id].first_in;
173 173
    }
174 174

	
175 175
    void nextIn(Arc& arc) const {
176 176
      arc._id = arcs[arc._id].next_in;
177 177
    }
178 178

	
179 179
  };
180 180

	
181 181
  typedef DigraphExtender<SmartDigraphBase> ExtendedSmartDigraphBase;
182 182

	
183 183
  ///\ingroup graphs
184 184
  ///
185 185
  ///\brief A smart directed graph class.
186 186
  ///
187 187
  ///\ref SmartDigraph is a simple and fast digraph implementation.
188 188
  ///It is also quite memory efficient but at the price
189 189
  ///that it does not support node and arc deletion 
190 190
  ///(except for the Snapshot feature).
191 191
  ///
192 192
  ///This type fully conforms to the \ref concepts::Digraph "Digraph concept"
193 193
  ///and it also provides some additional functionalities.
194 194
  ///Most of its member functions and nested classes are documented
195 195
  ///only in the concept class.
196 196
  ///
197
  ///This class provides constant time counting for nodes and arcs.
198
  ///
197 199
  ///\sa concepts::Digraph
198 200
  ///\sa SmartGraph
199 201
  class SmartDigraph : public ExtendedSmartDigraphBase {
200 202
    typedef ExtendedSmartDigraphBase Parent;
201 203

	
202 204
  private:
203 205
    /// Digraphs are \e not copy constructible. Use DigraphCopy instead.
204 206
    SmartDigraph(const SmartDigraph &) : ExtendedSmartDigraphBase() {};
205 207
    /// \brief Assignment of a digraph to another one is \e not allowed.
206 208
    /// Use DigraphCopy instead.
207 209
    void operator=(const SmartDigraph &) {}
208 210

	
209 211
  public:
210 212

	
211 213
    /// Constructor
212 214

	
213 215
    /// Constructor.
214 216
    ///
215 217
    SmartDigraph() {};
216 218

	
217 219
    ///Add a new node to the digraph.
218 220

	
219 221
    ///This function adds a new node to the digraph.
220 222
    ///\return The new node.
221 223
    Node addNode() { return Parent::addNode(); }
222 224

	
223 225
    ///Add a new arc to the digraph.
224 226

	
225 227
    ///This function adds a new arc to the digraph with source node \c s
226 228
    ///and target node \c t.
227 229
    ///\return The new arc.
228 230
    Arc addArc(Node s, Node t) {
229 231
      return Parent::addArc(s, t);
230 232
    }
231 233

	
232 234
    /// \brief Node validity check
233 235
    ///
234 236
    /// This function gives back \c true if the given node is valid,
235 237
    /// i.e. it is a real node of the digraph.
236 238
    ///
237 239
    /// \warning A removed node (using Snapshot) could become valid again
238 240
    /// if new nodes are added to the digraph.
239 241
    bool valid(Node n) const { return Parent::valid(n); }
240 242

	
241 243
    /// \brief Arc validity check
242 244
    ///
243 245
    /// This function gives back \c true if the given arc is valid,
244 246
    /// i.e. it is a real arc of the digraph.
245 247
    ///
246 248
    /// \warning A removed arc (using Snapshot) could become valid again
247 249
    /// if new arcs are added to the graph.
248 250
    bool valid(Arc a) const { return Parent::valid(a); }
249 251

	
250 252
    ///Split a node.
251 253

	
252 254
    ///This function splits the given node. First, a new node is added
253 255
    ///to the digraph, then the source of each outgoing arc of node \c n
254 256
    ///is moved to this new node.
255 257
    ///If the second parameter \c connect is \c true (this is the default
256 258
    ///value), then a new arc from node \c n to the newly created node
257 259
    ///is also added.
258 260
    ///\return The newly created node.
259 261
    ///
260 262
    ///\note All iterators remain valid.
261 263
    ///
262 264
    ///\warning This functionality cannot be used together with the Snapshot
263 265
    ///feature.
264 266
    Node split(Node n, bool connect = true)
265 267
    {
266 268
      Node b = addNode();
267 269
      nodes[b._id].first_out=nodes[n._id].first_out;
268 270
      nodes[n._id].first_out=-1;
269 271
      for(int i=nodes[b._id].first_out; i!=-1; i=arcs[i].next_out) {
270 272
        arcs[i].source=b._id;
271 273
      }
272 274
      if(connect) addArc(n,b);
273 275
      return b;
274 276
    }
275 277

	
276 278
    ///Clear the digraph.
277 279

	
278 280
    ///This function erases all nodes and arcs from the digraph.
279 281
    ///
280 282
    void clear() {
281 283
      Parent::clear();
282 284
    }
283 285

	
284 286
    /// Reserve memory for nodes.
285 287

	
286 288
    /// Using this function, it is possible to avoid superfluous memory
287 289
    /// allocation: if you know that the digraph you want to build will
288 290
    /// be large (e.g. it will contain millions of nodes and/or arcs),
289 291
    /// then it is worth reserving space for this amount before starting
290 292
    /// to build the digraph.
291 293
    /// \sa reserveArc()
292 294
    void reserveNode(int n) { nodes.reserve(n); };
293 295

	
294 296
    /// Reserve memory for arcs.
295 297

	
296 298
    /// Using this function, it is possible to avoid superfluous memory
297 299
    /// allocation: if you know that the digraph you want to build will
298 300
    /// be large (e.g. it will contain millions of nodes and/or arcs),
299 301
    /// then it is worth reserving space for this amount before starting
300 302
    /// to build the digraph.
301 303
    /// \sa reserveNode()
302 304
    void reserveArc(int m) { arcs.reserve(m); };
303 305

	
304 306
  public:
305 307

	
306 308
    class Snapshot;
307 309

	
308 310
  protected:
309 311

	
310 312
    void restoreSnapshot(const Snapshot &s)
311 313
    {
312 314
      while(s.arc_num<arcs.size()) {
313 315
        Arc arc = arcFromId(arcs.size()-1);
314 316
        Parent::notifier(Arc()).erase(arc);
315 317
        nodes[arcs.back().source].first_out=arcs.back().next_out;
316 318
        nodes[arcs.back().target].first_in=arcs.back().next_in;
317 319
        arcs.pop_back();
318 320
      }
319 321
      while(s.node_num<nodes.size()) {
320 322
        Node node = nodeFromId(nodes.size()-1);
321 323
        Parent::notifier(Node()).erase(node);
322 324
        nodes.pop_back();
323 325
      }
324 326
    }
325 327

	
326 328
  public:
327 329

	
328 330
    ///Class to make a snapshot of the digraph and to restore it later.
329 331

	
330 332
    ///Class to make a snapshot of the digraph and to restore it later.
331 333
    ///
332 334
    ///The newly added nodes and arcs can be removed using the
333 335
    ///restore() function. This is the only way for deleting nodes and/or
334 336
    ///arcs from a SmartDigraph structure.
335 337
    ///
336 338
    ///\note After a state is restored, you cannot restore a later state, 
337 339
    ///i.e. you cannot add the removed nodes and arcs again using
338 340
    ///another Snapshot instance.
339 341
    ///
340 342
    ///\warning Node splitting cannot be restored.
341 343
    ///\warning The validity of the snapshot is not stored due to
342 344
    ///performance reasons. If you do not use the snapshot correctly,
343 345
    ///it can cause broken program, invalid or not restored state of
344 346
    ///the digraph or no change.
345 347
    class Snapshot
346 348
    {
347 349
      SmartDigraph *_graph;
348 350
    protected:
349 351
      friend class SmartDigraph;
350 352
      unsigned int node_num;
351 353
      unsigned int arc_num;
352 354
    public:
353 355
      ///Default constructor.
354 356

	
355 357
      ///Default constructor.
356 358
      ///You have to call save() to actually make a snapshot.
357 359
      Snapshot() : _graph(0) {}
358 360
      ///Constructor that immediately makes a snapshot
359 361

	
360 362
      ///This constructor immediately makes a snapshot of the given digraph.
361 363
      ///
362 364
      Snapshot(SmartDigraph &gr) : _graph(&gr) {
363 365
        node_num=_graph->nodes.size();
364 366
        arc_num=_graph->arcs.size();
365 367
      }
366 368

	
367 369
      ///Make a snapshot.
368 370

	
369 371
      ///This function makes a snapshot of the given digraph.
370 372
      ///It can be called more than once. In case of a repeated
371 373
      ///call, the previous snapshot gets lost.
372 374
      void save(SmartDigraph &gr) {
373 375
        _graph=&gr;
374 376
        node_num=_graph->nodes.size();
375 377
        arc_num=_graph->arcs.size();
376 378
      }
377 379

	
378 380
      ///Undo the changes until a snapshot.
379 381

	
380 382
      ///This function undos the changes until the last snapshot
381 383
      ///created by save() or Snapshot(SmartDigraph&).
382 384
      void restore()
383 385
      {
384 386
        _graph->restoreSnapshot(*this);
385 387
      }
386 388
    };
387 389
  };
388 390

	
389 391

	
390 392
  class SmartGraphBase {
391 393

	
392 394
  protected:
393 395

	
394 396
    struct NodeT {
395 397
      int first_out;
396 398
    };
397 399

	
398 400
    struct ArcT {
399 401
      int target;
400 402
      int next_out;
401 403
    };
402 404

	
403 405
    std::vector<NodeT> nodes;
404 406
    std::vector<ArcT> arcs;
405 407

	
406 408
    int first_free_arc;
407 409

	
408 410
  public:
409 411

	
410 412
    typedef SmartGraphBase Graph;
411 413

	
412 414
    class Node;
413 415
    class Arc;
414 416
    class Edge;
415 417

	
416 418
    class Node {
417 419
      friend class SmartGraphBase;
418 420
    protected:
419 421

	
420 422
      int _id;
421 423
      explicit Node(int id) { _id = id;}
422 424

	
423 425
    public:
424 426
      Node() {}
425 427
      Node (Invalid) { _id = -1; }
426 428
      bool operator==(const Node& node) const {return _id == node._id;}
427 429
      bool operator!=(const Node& node) const {return _id != node._id;}
428 430
      bool operator<(const Node& node) const {return _id < node._id;}
429 431
    };
430 432

	
431 433
    class Edge {
432 434
      friend class SmartGraphBase;
433 435
    protected:
434 436

	
435 437
      int _id;
436 438
      explicit Edge(int id) { _id = id;}
437 439

	
438 440
    public:
439 441
      Edge() {}
440 442
      Edge (Invalid) { _id = -1; }
441 443
      bool operator==(const Edge& arc) const {return _id == arc._id;}
442 444
      bool operator!=(const Edge& arc) const {return _id != arc._id;}
443 445
      bool operator<(const Edge& arc) const {return _id < arc._id;}
444 446
    };
445 447

	
446 448
    class Arc {
447 449
      friend class SmartGraphBase;
448 450
    protected:
449 451

	
450 452
      int _id;
451 453
      explicit Arc(int id) { _id = id;}
452 454

	
453 455
    public:
454 456
      operator Edge() const {
455 457
        return _id != -1 ? edgeFromId(_id / 2) : INVALID;
456 458
      }
457 459

	
458 460
      Arc() {}
459 461
      Arc (Invalid) { _id = -1; }
460 462
      bool operator==(const Arc& arc) const {return _id == arc._id;}
461 463
      bool operator!=(const Arc& arc) const {return _id != arc._id;}
462 464
      bool operator<(const Arc& arc) const {return _id < arc._id;}
463 465
    };
464 466

	
465 467

	
466 468

	
467 469
    SmartGraphBase()
468 470
      : nodes(), arcs() {}
469 471

	
470 472
    typedef True NodeNumTag;
471 473
    typedef True EdgeNumTag;
472 474
    typedef True ArcNumTag;
473 475

	
474 476
    int nodeNum() const { return nodes.size(); }
475 477
    int edgeNum() const { return arcs.size() / 2; }
476 478
    int arcNum() const { return arcs.size(); }
477 479

	
478 480
    int maxNodeId() const { return nodes.size()-1; }
479 481
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
480 482
    int maxArcId() const { return arcs.size()-1; }
481 483

	
482 484
    Node source(Arc e) const { return Node(arcs[e._id ^ 1].target); }
483 485
    Node target(Arc e) const { return Node(arcs[e._id].target); }
484 486

	
485 487
    Node u(Edge e) const { return Node(arcs[2 * e._id].target); }
486 488
    Node v(Edge e) const { return Node(arcs[2 * e._id + 1].target); }
487 489

	
488 490
    static bool direction(Arc e) {
489 491
      return (e._id & 1) == 1;
490 492
    }
491 493

	
492 494
    static Arc direct(Edge e, bool d) {
493 495
      return Arc(e._id * 2 + (d ? 1 : 0));
494 496
    }
495 497

	
496 498
    void first(Node& node) const {
497 499
      node._id = nodes.size() - 1;
498 500
    }
499 501

	
500 502
    static void next(Node& node) {
501 503
      --node._id;
502 504
    }
503 505

	
504 506
    void first(Arc& arc) const {
505 507
      arc._id = arcs.size() - 1;
506 508
    }
507 509

	
508 510
    static void next(Arc& arc) {
509 511
      --arc._id;
510 512
    }
511 513

	
512 514
    void first(Edge& arc) const {
513 515
      arc._id = arcs.size() / 2 - 1;
514 516
    }
515 517

	
516 518
    static void next(Edge& arc) {
517 519
      --arc._id;
518 520
    }
519 521

	
520 522
    void firstOut(Arc &arc, const Node& v) const {
521 523
      arc._id = nodes[v._id].first_out;
522 524
    }
523 525
    void nextOut(Arc &arc) const {
524 526
      arc._id = arcs[arc._id].next_out;
525 527
    }
526 528

	
527 529
    void firstIn(Arc &arc, const Node& v) const {
528 530
      arc._id = ((nodes[v._id].first_out) ^ 1);
529 531
      if (arc._id == -2) arc._id = -1;
530 532
    }
531 533
    void nextIn(Arc &arc) const {
532 534
      arc._id = ((arcs[arc._id ^ 1].next_out) ^ 1);
533 535
      if (arc._id == -2) arc._id = -1;
534 536
    }
535 537

	
536 538
    void firstInc(Edge &arc, bool& d, const Node& v) const {
537 539
      int de = nodes[v._id].first_out;
538 540
      if (de != -1) {
539 541
        arc._id = de / 2;
540 542
        d = ((de & 1) == 1);
541 543
      } else {
542 544
        arc._id = -1;
543 545
        d = true;
544 546
      }
545 547
    }
546 548
    void nextInc(Edge &arc, bool& d) const {
547 549
      int de = (arcs[(arc._id * 2) | (d ? 1 : 0)].next_out);
548 550
      if (de != -1) {
549 551
        arc._id = de / 2;
550 552
        d = ((de & 1) == 1);
551 553
      } else {
552 554
        arc._id = -1;
553 555
        d = true;
554 556
      }
555 557
    }
556 558

	
557 559
    static int id(Node v) { return v._id; }
558 560
    static int id(Arc e) { return e._id; }
559 561
    static int id(Edge e) { return e._id; }
560 562

	
561 563
    static Node nodeFromId(int id) { return Node(id);}
562 564
    static Arc arcFromId(int id) { return Arc(id);}
563 565
    static Edge edgeFromId(int id) { return Edge(id);}
564 566

	
565 567
    bool valid(Node n) const {
566 568
      return n._id >= 0 && n._id < static_cast<int>(nodes.size());
567 569
    }
568 570
    bool valid(Arc a) const {
569 571
      return a._id >= 0 && a._id < static_cast<int>(arcs.size());
570 572
    }
571 573
    bool valid(Edge e) const {
572 574
      return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size());
573 575
    }
574 576

	
575 577
    Node addNode() {
576 578
      int n = nodes.size();
577 579
      nodes.push_back(NodeT());
578 580
      nodes[n].first_out = -1;
579 581

	
580 582
      return Node(n);
581 583
    }
582 584

	
583 585
    Edge addEdge(Node u, Node v) {
584 586
      int n = arcs.size();
585 587
      arcs.push_back(ArcT());
586 588
      arcs.push_back(ArcT());
587 589

	
588 590
      arcs[n].target = u._id;
589 591
      arcs[n | 1].target = v._id;
590 592

	
591 593
      arcs[n].next_out = nodes[v._id].first_out;
592 594
      nodes[v._id].first_out = n;
593 595

	
594 596
      arcs[n | 1].next_out = nodes[u._id].first_out;
595 597
      nodes[u._id].first_out = (n | 1);
596 598

	
597 599
      return Edge(n / 2);
598 600
    }
599 601

	
600 602
    void clear() {
601 603
      arcs.clear();
602 604
      nodes.clear();
603 605
    }
604 606

	
605 607
  };
606 608

	
607 609
  typedef GraphExtender<SmartGraphBase> ExtendedSmartGraphBase;
608 610

	
609 611
  /// \ingroup graphs
610 612
  ///
611 613
  /// \brief A smart undirected graph class.
612 614
  ///
613 615
  /// \ref SmartGraph is a simple and fast graph implementation.
614 616
  /// It is also quite memory efficient but at the price
615 617
  /// that it does not support node and edge deletion 
616 618
  /// (except for the Snapshot feature).
617 619
  ///
618 620
  /// This type fully conforms to the \ref concepts::Graph "Graph concept"
619 621
  /// and it also provides some additional functionalities.
620 622
  /// Most of its member functions and nested classes are documented
621 623
  /// only in the concept class.
622 624
  ///
625
  /// This class provides constant time counting for nodes, edges and arcs.
626
  ///
623 627
  /// \sa concepts::Graph
624 628
  /// \sa SmartDigraph
625 629
  class SmartGraph : public ExtendedSmartGraphBase {
626 630
    typedef ExtendedSmartGraphBase Parent;
627 631

	
628 632
  private:
629 633
    /// Graphs are \e not copy constructible. Use GraphCopy instead.
630 634
    SmartGraph(const SmartGraph &) : ExtendedSmartGraphBase() {};
631 635
    /// \brief Assignment of a graph to another one is \e not allowed.
632 636
    /// Use GraphCopy instead.
633 637
    void operator=(const SmartGraph &) {}
634 638

	
635 639
  public:
636 640

	
637 641
    /// Constructor
638 642

	
639 643
    /// Constructor.
640 644
    ///
641 645
    SmartGraph() {}
642 646

	
643 647
    /// \brief Add a new node to the graph.
644 648
    ///
645 649
    /// This function adds a new node to the graph.
646 650
    /// \return The new node.
647 651
    Node addNode() { return Parent::addNode(); }
648 652

	
649 653
    /// \brief Add a new edge to the graph.
650 654
    ///
651 655
    /// This function adds a new edge to the graph between nodes
652 656
    /// \c u and \c v with inherent orientation from node \c u to
653 657
    /// node \c v.
654 658
    /// \return The new edge.
655 659
    Edge addEdge(Node u, Node v) {
656 660
      return Parent::addEdge(u, v);
657 661
    }
658 662

	
659 663
    /// \brief Node validity check
660 664
    ///
661 665
    /// This function gives back \c true if the given node is valid,
662 666
    /// i.e. it is a real node of the graph.
663 667
    ///
664 668
    /// \warning A removed node (using Snapshot) could become valid again
665 669
    /// if new nodes are added to the graph.
666 670
    bool valid(Node n) const { return Parent::valid(n); }
667 671

	
668 672
    /// \brief Edge validity check
669 673
    ///
670 674
    /// This function gives back \c true if the given edge is valid,
671 675
    /// i.e. it is a real edge of the graph.
672 676
    ///
673 677
    /// \warning A removed edge (using Snapshot) could become valid again
674 678
    /// if new edges are added to the graph.
675 679
    bool valid(Edge e) const { return Parent::valid(e); }
676 680

	
677 681
    /// \brief Arc validity check
678 682
    ///
679 683
    /// This function gives back \c true if the given arc is valid,
680 684
    /// i.e. it is a real arc of the graph.
681 685
    ///
682 686
    /// \warning A removed arc (using Snapshot) could become valid again
683 687
    /// if new edges are added to the graph.
684 688
    bool valid(Arc a) const { return Parent::valid(a); }
685 689

	
686 690
    ///Clear the graph.
687 691

	
688 692
    ///This function erases all nodes and arcs from the graph.
689 693
    ///
690 694
    void clear() {
691 695
      Parent::clear();
692 696
    }
693 697

	
694 698
    /// Reserve memory for nodes.
695 699

	
696 700
    /// Using this function, it is possible to avoid superfluous memory
697 701
    /// allocation: if you know that the graph you want to build will
698 702
    /// be large (e.g. it will contain millions of nodes and/or edges),
699 703
    /// then it is worth reserving space for this amount before starting
700 704
    /// to build the graph.
701 705
    /// \sa reserveEdge()
702 706
    void reserveNode(int n) { nodes.reserve(n); };
703 707

	
704 708
    /// Reserve memory for edges.
705 709

	
706 710
    /// Using this function, it is possible to avoid superfluous memory
707 711
    /// allocation: if you know that the graph you want to build will
708 712
    /// be large (e.g. it will contain millions of nodes and/or edges),
709 713
    /// then it is worth reserving space for this amount before starting
710 714
    /// to build the graph.
711 715
    /// \sa reserveNode()
712 716
    void reserveEdge(int m) { arcs.reserve(2 * m); };
713 717

	
714 718
  public:
715 719

	
716 720
    class Snapshot;
717 721

	
718 722
  protected:
719 723

	
720 724
    void saveSnapshot(Snapshot &s)
721 725
    {
722 726
      s._graph = this;
723 727
      s.node_num = nodes.size();
724 728
      s.arc_num = arcs.size();
725 729
    }
726 730

	
727 731
    void restoreSnapshot(const Snapshot &s)
728 732
    {
729 733
      while(s.arc_num<arcs.size()) {
730 734
        int n=arcs.size()-1;
731 735
        Edge arc=edgeFromId(n/2);
732 736
        Parent::notifier(Edge()).erase(arc);
733 737
        std::vector<Arc> dir;
734 738
        dir.push_back(arcFromId(n));
735 739
        dir.push_back(arcFromId(n-1));
736 740
        Parent::notifier(Arc()).erase(dir);
737 741
        nodes[arcs[n-1].target].first_out=arcs[n].next_out;
738 742
        nodes[arcs[n].target].first_out=arcs[n-1].next_out;
739 743
        arcs.pop_back();
740 744
        arcs.pop_back();
741 745
      }
742 746
      while(s.node_num<nodes.size()) {
743 747
        int n=nodes.size()-1;
744 748
        Node node = nodeFromId(n);
745 749
        Parent::notifier(Node()).erase(node);
746 750
        nodes.pop_back();
747 751
      }
748 752
    }
749 753

	
750 754
  public:
751 755

	
752 756
    ///Class to make a snapshot of the graph and to restore it later.
753 757

	
754 758
    ///Class to make a snapshot of the graph and to restore it later.
755 759
    ///
756 760
    ///The newly added nodes and edges can be removed using the
757 761
    ///restore() function. This is the only way for deleting nodes and/or
758 762
    ///edges from a SmartGraph structure.
759 763
    ///
760 764
    ///\note After a state is restored, you cannot restore a later state, 
761 765
    ///i.e. you cannot add the removed nodes and edges again using
762 766
    ///another Snapshot instance.
763 767
    ///
764 768
    ///\warning The validity of the snapshot is not stored due to
765 769
    ///performance reasons. If you do not use the snapshot correctly,
766 770
    ///it can cause broken program, invalid or not restored state of
767 771
    ///the graph or no change.
768 772
    class Snapshot
769 773
    {
770 774
      SmartGraph *_graph;
771 775
    protected:
772 776
      friend class SmartGraph;
773 777
      unsigned int node_num;
774 778
      unsigned int arc_num;
775 779
    public:
776 780
      ///Default constructor.
777 781

	
778 782
      ///Default constructor.
779 783
      ///You have to call save() to actually make a snapshot.
780 784
      Snapshot() : _graph(0) {}
781 785
      ///Constructor that immediately makes a snapshot
782 786

	
783 787
      /// This constructor immediately makes a snapshot of the given graph.
784 788
      ///
785 789
      Snapshot(SmartGraph &gr) {
786 790
        gr.saveSnapshot(*this);
787 791
      }
788 792

	
789 793
      ///Make a snapshot.
790 794

	
791 795
      ///This function makes a snapshot of the given graph.
792 796
      ///It can be called more than once. In case of a repeated
793 797
      ///call, the previous snapshot gets lost.
794 798
      void save(SmartGraph &gr)
795 799
      {
796 800
        gr.saveSnapshot(*this);
797 801
      }
798 802

	
799 803
      ///Undo the changes until the last snapshot.
800 804

	
801 805
      ///This function undos the changes until the last snapshot
802 806
      ///created by save() or Snapshot(SmartGraph&).
803 807
      void restore()
804 808
      {
805 809
        _graph->restoreSnapshot(*this);
806 810
      }
807 811
    };
808 812
  };
809 813

	
810 814
} //namespace lemon
811 815

	
812 816

	
813 817
#endif //LEMON_SMART_GRAPH_H
Ignore white space 6 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2008
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_STATIC_GRAPH_H
20 20
#define LEMON_STATIC_GRAPH_H
21 21

	
22 22
///\ingroup graphs
23 23
///\file
24 24
///\brief StaticDigraph class.
25 25

	
26 26
#include <lemon/core.h>
27 27
#include <lemon/bits/graph_extender.h>
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  class StaticDigraphBase {
32 32
  public:
33 33

	
34 34
    StaticDigraphBase() 
35 35
      : built(false), node_num(0), arc_num(0), 
36 36
        node_first_out(NULL), node_first_in(NULL),
37 37
        arc_source(NULL), arc_target(NULL), 
38 38
        arc_next_in(NULL), arc_next_out(NULL) {}
39 39
    
40 40
    ~StaticDigraphBase() {
41 41
      if (built) {
42 42
        delete[] node_first_out;
43 43
        delete[] node_first_in;
44 44
        delete[] arc_source;
45 45
        delete[] arc_target;
46 46
        delete[] arc_next_out;
47 47
        delete[] arc_next_in;
48 48
      }
49 49
    }
50 50

	
51 51
    class Node {
52 52
      friend class StaticDigraphBase;
53 53
    protected:
54 54
      int id;
55 55
      Node(int _id) : id(_id) {}
56 56
    public:
57 57
      Node() {}
58 58
      Node (Invalid) : id(-1) {}
59 59
      bool operator==(const Node& node) const { return id == node.id; }
60 60
      bool operator!=(const Node& node) const { return id != node.id; }
61 61
      bool operator<(const Node& node) const { return id < node.id; }
62 62
    };
63 63

	
64 64
    class Arc {
65 65
      friend class StaticDigraphBase;      
66 66
    protected:
67 67
      int id;
68 68
      Arc(int _id) : id(_id) {}
69 69
    public:
70 70
      Arc() { }
71 71
      Arc (Invalid) : id(-1) {}
72 72
      bool operator==(const Arc& arc) const { return id == arc.id; }
73 73
      bool operator!=(const Arc& arc) const { return id != arc.id; }
74 74
      bool operator<(const Arc& arc) const { return id < arc.id; }
75 75
    };
76 76

	
77 77
    Node source(const Arc& e) const { return Node(arc_source[e.id]); }
78 78
    Node target(const Arc& e) const { return Node(arc_target[e.id]); }
79 79

	
80 80
    void first(Node& n) const { n.id = node_num - 1; }
81 81
    static void next(Node& n) { --n.id; }
82 82

	
83 83
    void first(Arc& e) const { e.id = arc_num - 1; }
84 84
    static void next(Arc& e) { --e.id; }
85 85

	
86 86
    void firstOut(Arc& e, const Node& n) const { 
87 87
      e.id = node_first_out[n.id] != node_first_out[n.id + 1] ? 
88 88
        node_first_out[n.id] : -1;
89 89
    }
90 90
    void nextOut(Arc& e) const { e.id = arc_next_out[e.id]; }
91 91

	
92 92
    void firstIn(Arc& e, const Node& n) const { e.id = node_first_in[n.id]; }
93 93
    void nextIn(Arc& e) const { e.id = arc_next_in[e.id]; }
94 94

	
95 95
    static int id(const Node& n) { return n.id; }
96 96
    static Node nodeFromId(int id) { return Node(id); }
97 97
    int maxNodeId() const { return node_num - 1; }
98 98

	
99 99
    static int id(const Arc& e) { return e.id; }
100 100
    static Arc arcFromId(int id) { return Arc(id); }
101 101
    int maxArcId() const { return arc_num - 1; }
102 102

	
103 103
    typedef True NodeNumTag;
104 104
    typedef True ArcNumTag;
105 105

	
106 106
    int nodeNum() const { return node_num; }
107 107
    int arcNum() const { return arc_num; }
108 108

	
109 109
  private:
110 110

	
111 111
    template <typename Digraph, typename NodeRefMap>
112 112
    class ArcLess {
113 113
    public:
114 114
      typedef typename Digraph::Arc Arc;
115 115

	
116 116
      ArcLess(const Digraph &_graph, const NodeRefMap& _nodeRef) 
117 117
        : digraph(_graph), nodeRef(_nodeRef) {}
118 118
      
119 119
      bool operator()(const Arc& left, const Arc& right) const {
120 120
	return nodeRef[digraph.target(left)] < nodeRef[digraph.target(right)];
121 121
      }
122 122
    private:
123 123
      const Digraph& digraph;
124 124
      const NodeRefMap& nodeRef;
125 125
    };
126 126
    
127 127
  public:
128 128

	
129 129
    typedef True BuildTag;
130 130
    
131 131
    void clear() {
132 132
      if (built) {
133 133
        delete[] node_first_out;
134 134
        delete[] node_first_in;
135 135
        delete[] arc_source;
136 136
        delete[] arc_target;
137 137
        delete[] arc_next_out;
138 138
        delete[] arc_next_in;
139 139
      }
140 140
      built = false;
141 141
      node_num = 0;
142 142
      arc_num = 0;
143 143
    }
144 144
    
145 145
    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
146 146
    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
147 147
      typedef typename Digraph::Node GNode;
148 148
      typedef typename Digraph::Arc GArc;
149 149

	
150 150
      built = true;
151 151

	
152 152
      node_num = countNodes(digraph);
153 153
      arc_num = countArcs(digraph);
154 154

	
155 155
      node_first_out = new int[node_num + 1];
156 156
      node_first_in = new int[node_num];
157 157

	
158 158
      arc_source = new int[arc_num];
159 159
      arc_target = new int[arc_num];
160 160
      arc_next_out = new int[arc_num];
161 161
      arc_next_in = new int[arc_num];
162 162

	
163 163
      int node_index = 0;
164 164
      for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
165 165
        nodeRef[n] = Node(node_index);
166 166
        node_first_in[node_index] = -1;
167 167
        ++node_index;
168 168
      }
169 169

	
170 170
      ArcLess<Digraph, NodeRefMap> arcLess(digraph, nodeRef);
171 171

	
172 172
      int arc_index = 0;
173 173
      for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
174 174
        int source = nodeRef[n].id;
175 175
        std::vector<GArc> arcs;
176 176
        for (typename Digraph::OutArcIt e(digraph, n); e != INVALID; ++e) {
177 177
          arcs.push_back(e);
178 178
        }
179 179
        if (!arcs.empty()) {
180 180
          node_first_out[source] = arc_index;
181 181
          std::sort(arcs.begin(), arcs.end(), arcLess);
182 182
          for (typename std::vector<GArc>::iterator it = arcs.begin();
183 183
               it != arcs.end(); ++it) {
184 184
            int target = nodeRef[digraph.target(*it)].id;
185 185
            arcRef[*it] = Arc(arc_index);
186 186
            arc_source[arc_index] = source; 
187 187
            arc_target[arc_index] = target;
188 188
            arc_next_in[arc_index] = node_first_in[target];
189 189
            node_first_in[target] = arc_index;
190 190
            arc_next_out[arc_index] = arc_index + 1;
191 191
            ++arc_index;
192 192
          }
193 193
          arc_next_out[arc_index - 1] = -1;
194 194
        } else {
195 195
          node_first_out[source] = arc_index;
196 196
        }
197 197
      }
198 198
      node_first_out[node_num] = arc_num;
199 199
    }
200 200
    
201 201
    template <typename ArcListIterator>
202 202
    void build(int n, ArcListIterator first, ArcListIterator last) {
203 203
      built = true;
204 204

	
205 205
      node_num = n;
206 206
      arc_num = std::distance(first, last);
207 207

	
208 208
      node_first_out = new int[node_num + 1];
209 209
      node_first_in = new int[node_num];
210 210

	
211 211
      arc_source = new int[arc_num];
212 212
      arc_target = new int[arc_num];
213 213
      arc_next_out = new int[arc_num];
214 214
      arc_next_in = new int[arc_num];
215 215
      
216 216
      for (int i = 0; i != node_num; ++i) {
217 217
        node_first_in[i] = -1;
218 218
      }      
219 219
      
220 220
      int arc_index = 0;
221 221
      for (int i = 0; i != node_num; ++i) {
222 222
        node_first_out[i] = arc_index;
223 223
        for ( ; first != last && (*first).first == i; ++first) {
224 224
          int j = (*first).second;
225 225
          LEMON_ASSERT(j >= 0 && j < node_num,
226 226
            "Wrong arc list for StaticDigraph::build()");
227 227
          arc_source[arc_index] = i;
228 228
          arc_target[arc_index] = j;
229 229
          arc_next_in[arc_index] = node_first_in[j];
230 230
          node_first_in[j] = arc_index;
231 231
          arc_next_out[arc_index] = arc_index + 1;
232 232
          ++arc_index;
233 233
        }
234 234
        if (arc_index > node_first_out[i])
235 235
          arc_next_out[arc_index - 1] = -1;
236 236
      }
237 237
      LEMON_ASSERT(first == last,
238 238
        "Wrong arc list for StaticDigraph::build()");
239 239
      node_first_out[node_num] = arc_num;
240 240
    }
241 241

	
242 242
  protected:
243 243

	
244 244
    void fastFirstOut(Arc& e, const Node& n) const {
245 245
      e.id = node_first_out[n.id];
246 246
    }
247 247

	
248 248
    static void fastNextOut(Arc& e) {
249 249
      ++e.id;
250 250
    }
251 251
    void fastLastOut(Arc& e, const Node& n) const {
252 252
      e.id = node_first_out[n.id + 1];
253 253
    }
254 254

	
255 255
  protected:
256 256
    bool built;
257 257
    int node_num;
258 258
    int arc_num;
259 259
    int *node_first_out;
260 260
    int *node_first_in;
261 261
    int *arc_source;
262 262
    int *arc_target;
263 263
    int *arc_next_in;
264 264
    int *arc_next_out;
265 265
  };
266 266

	
267 267
  typedef DigraphExtender<StaticDigraphBase> ExtendedStaticDigraphBase;
268 268

	
269 269

	
270 270
  /// \ingroup graphs
271 271
  ///
272 272
  /// \brief A static directed graph class.
273 273
  ///
274 274
  /// \ref StaticDigraph is a highly efficient digraph implementation,
275 275
  /// but it is fully static.
276 276
  /// It stores only two \c int values for each node and only four \c int
277 277
  /// values for each arc. Moreover it provides faster item iteration than
278 278
  /// \ref ListDigraph and \ref SmartDigraph, especially using \c OutArcIt
279 279
  /// iterators, since its arcs are stored in an appropriate order.
280 280
  /// However it only provides build() and clear() functions and does not
281 281
  /// support any other modification of the digraph.
282 282
  ///
283 283
  /// Since this digraph structure is completely static, its nodes and arcs
284 284
  /// can be indexed with integers from the ranges <tt>[0..nodeNum()-1]</tt>
285 285
  /// and <tt>[0..arcNum()-1]</tt>, respectively. 
286 286
  /// The index of an item is the same as its ID, it can be obtained
287 287
  /// using the corresponding \ref index() or \ref concepts::Digraph::id()
288 288
  /// "id()" function. A node or arc with a certain index can be obtained
289 289
  /// using node() or arc().
290 290
  ///
291 291
  /// This type fully conforms to the \ref concepts::Digraph "Digraph concept".
292 292
  /// Most of its member functions and nested classes are documented
293 293
  /// only in the concept class.
294 294
  ///
295
  /// This class provides constant time counting for nodes and arcs.
296
  ///
295 297
  /// \sa concepts::Digraph
296 298
  class StaticDigraph : public ExtendedStaticDigraphBase {
297 299
  public:
298 300

	
299 301
    typedef ExtendedStaticDigraphBase Parent;
300 302
  
301 303
  public:
302 304
  
303 305
    /// \brief Constructor
304 306
    ///
305 307
    /// Default constructor.
306 308
    StaticDigraph() : Parent() {}
307 309

	
308 310
    /// \brief The node with the given index.
309 311
    ///
310 312
    /// This function returns the node with the given index.
311 313
    /// \sa index()
312 314
    static Node node(int ix) { return Parent::nodeFromId(ix); }
313 315

	
314 316
    /// \brief The arc with the given index.
315 317
    ///
316 318
    /// This function returns the arc with the given index.
317 319
    /// \sa index()
318 320
    static Arc arc(int ix) { return Parent::arcFromId(ix); }
319 321

	
320 322
    /// \brief The index of the given node.
321 323
    ///
322 324
    /// This function returns the index of the the given node.
323 325
    /// \sa node()
324 326
    static int index(Node node) { return Parent::id(node); }
325 327

	
326 328
    /// \brief The index of the given arc.
327 329
    ///
328 330
    /// This function returns the index of the the given arc.
329 331
    /// \sa arc()
330 332
    static int index(Arc arc) { return Parent::id(arc); }
331 333

	
332 334
    /// \brief Number of nodes.
333 335
    ///
334 336
    /// This function returns the number of nodes.
335 337
    int nodeNum() const { return node_num; }
336 338

	
337 339
    /// \brief Number of arcs.
338 340
    ///
339 341
    /// This function returns the number of arcs.
340 342
    int arcNum() const { return arc_num; }
341 343

	
342 344
    /// \brief Build the digraph copying another digraph.
343 345
    ///
344 346
    /// This function builds the digraph copying another digraph of any
345 347
    /// kind. It can be called more than once, but in such case, the whole
346 348
    /// structure and all maps will be cleared and rebuilt.
347 349
    ///
348 350
    /// This method also makes possible to copy a digraph to a StaticDigraph
349 351
    /// structure using \ref DigraphCopy.
350 352
    /// 
351 353
    /// \param digraph An existing digraph to be copied.
352 354
    /// \param nodeRef The node references will be copied into this map.
353 355
    /// Its key type must be \c Digraph::Node and its value type must be
354 356
    /// \c StaticDigraph::Node.
355 357
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
356 358
    /// concept.
357 359
    /// \param arcRef The arc references will be copied into this map.
358 360
    /// Its key type must be \c Digraph::Arc and its value type must be
359 361
    /// \c StaticDigraph::Arc.
360 362
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
361 363
    ///
362 364
    /// \note If you do not need the arc references, then you could use
363 365
    /// \ref NullMap for the last parameter. However the node references
364 366
    /// are required by the function itself, thus they must be readable
365 367
    /// from the map.
366 368
    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
367 369
    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
368 370
      if (built) Parent::clear();
369 371
      Parent::build(digraph, nodeRef, arcRef);
370 372
    }
371 373
  
372 374
    /// \brief Build the digraph from an arc list.
373 375
    ///
374 376
    /// This function builds the digraph from the given arc list.
375 377
    /// It can be called more than once, but in such case, the whole
376 378
    /// structure and all maps will be cleared and rebuilt.
377 379
    ///
378 380
    /// The list of the arcs must be given in the range <tt>[begin, end)</tt>
379 381
    /// specified by STL compatible itartors whose \c value_type must be
380 382
    /// <tt>std::pair<int,int></tt>.
381 383
    /// Each arc must be specified by a pair of integer indices
382 384
    /// from the range <tt>[0..n-1]</tt>. <i>The pairs must be in a
383 385
    /// non-decreasing order with respect to their first values.</i>
384 386
    /// If the k-th pair in the list is <tt>(i,j)</tt>, then
385 387
    /// <tt>arc(k-1)</tt> will connect <tt>node(i)</tt> to <tt>node(j)</tt>.
386 388
    ///
387 389
    /// \param n The number of nodes.
388 390
    /// \param begin An iterator pointing to the beginning of the arc list.
389 391
    /// \param end An iterator pointing to the end of the arc list.
390 392
    ///
391 393
    /// For example, a simple digraph can be constructed like this.
392 394
    /// \code
393 395
    ///   std::vector<std::pair<int,int> > arcs;
394 396
    ///   arcs.push_back(std::make_pair(0,1));
395 397
    ///   arcs.push_back(std::make_pair(0,2));
396 398
    ///   arcs.push_back(std::make_pair(1,3));
397 399
    ///   arcs.push_back(std::make_pair(1,2));
398 400
    ///   arcs.push_back(std::make_pair(3,0));
399 401
    ///   StaticDigraph gr;
400 402
    ///   gr.build(4, arcs.begin(), arcs.end());
401 403
    /// \endcode
402 404
    template <typename ArcListIterator>
403 405
    void build(int n, ArcListIterator begin, ArcListIterator end) {
404 406
      if (built) Parent::clear();
405 407
      StaticDigraphBase::build(n, begin, end);
406 408
      notifier(Node()).build();
407 409
      notifier(Arc()).build();
408 410
    }
409 411

	
410 412
    /// \brief Clear the digraph.
411 413
    ///
412 414
    /// This function erases all nodes and arcs from the digraph.
413 415
    void clear() {
414 416
      Parent::clear();
415 417
    }
416 418

	
417 419
  protected:
418 420

	
419 421
    using Parent::fastFirstOut;
420 422
    using Parent::fastNextOut;
421 423
    using Parent::fastLastOut;
422 424
    
423 425
  public:
424 426

	
425 427
    class OutArcIt : public Arc {
426 428
    public:
427 429

	
428 430
      OutArcIt() { }
429 431

	
430 432
      OutArcIt(Invalid i) : Arc(i) { }
431 433

	
432 434
      OutArcIt(const StaticDigraph& digraph, const Node& node) {
433 435
	digraph.fastFirstOut(*this, node);
434 436
	digraph.fastLastOut(last, node);
435 437
        if (last == *this) *this = INVALID;
436 438
      }
437 439

	
438 440
      OutArcIt(const StaticDigraph& digraph, const Arc& arc) : Arc(arc) {
439 441
        if (arc != INVALID) {
440 442
          digraph.fastLastOut(last, digraph.source(arc));
441 443
        }
442 444
      }
443 445

	
444 446
      OutArcIt& operator++() { 
445 447
        StaticDigraph::fastNextOut(*this);
446 448
        if (last == *this) *this = INVALID;
447 449
        return *this; 
448 450
      }
449 451

	
450 452
    private:
451 453
      Arc last;
452 454
    };
453 455

	
454 456
    Node baseNode(const OutArcIt &arc) const {
455 457
      return Parent::source(static_cast<const Arc&>(arc));
456 458
    }
457 459

	
458 460
    Node runningNode(const OutArcIt &arc) const {
459 461
      return Parent::target(static_cast<const Arc&>(arc));
460 462
    }
461 463

	
462 464
    Node baseNode(const InArcIt &arc) const {
463 465
      return Parent::target(static_cast<const Arc&>(arc));
464 466
    }
465 467

	
466 468
    Node runningNode(const InArcIt &arc) const {
467 469
      return Parent::source(static_cast<const Arc&>(arc));
468 470
    }
469 471

	
470 472
  };
471 473

	
472 474
}
473 475

	
474 476
#endif
0 comments (0 inline)