gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 4 0
merge default
1 file changed with 32 insertions and 22 deletions:
↑ Collapse diff ↑
Ignore white space 24576 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_BFS_H
20 20
#define LEMON_BFS_H
21 21

	
22 22
///\ingroup search
23 23
///\file
24 24
///\brief BFS algorithm.
25 25

	
26 26
#include <lemon/list_graph.h>
27 27
#include <lemon/bits/path_dump.h>
28 28
#include <lemon/core.h>
29 29
#include <lemon/error.h>
30 30
#include <lemon/maps.h>
31 31
#include <lemon/path.h>
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  ///Default traits class of Bfs class.
36 36

	
37 37
  ///Default traits class of Bfs class.
38 38
  ///\tparam GR Digraph type.
39 39
  template<class GR>
40 40
  struct BfsDefaultTraits
41 41
  {
42 42
    ///The type of the digraph the algorithm runs on.
43 43
    typedef GR Digraph;
44 44

	
45 45
    ///\brief The type of the map that stores the predecessor
46 46
    ///arcs of the shortest paths.
47 47
    ///
48 48
    ///The type of the map that stores the predecessor
49 49
    ///arcs of the shortest paths.
50 50
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 51
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52 52
    ///Instantiates a PredMap.
53 53

	
54
    ///This function instantiates a PredMap.
54
    ///This function instantiates a PredMap.  
55 55
    ///\param g is the digraph, to which we would like to define the
56 56
    ///PredMap.
57 57
    static PredMap *createPredMap(const Digraph &g)
58 58
    {
59 59
      return new PredMap(g);
60 60
    }
61 61

	
62 62
    ///The type of the map that indicates which nodes are processed.
63 63

	
64 64
    ///The type of the map that indicates which nodes are processed.
65 65
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
66 66
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67 67
    ///Instantiates a ProcessedMap.
68 68

	
69 69
    ///This function instantiates a ProcessedMap.
70 70
    ///\param g is the digraph, to which
71 71
    ///we would like to define the ProcessedMap
72 72
#ifdef DOXYGEN
73 73
    static ProcessedMap *createProcessedMap(const Digraph &g)
74 74
#else
75 75
    static ProcessedMap *createProcessedMap(const Digraph &)
76 76
#endif
77 77
    {
78 78
      return new ProcessedMap();
79 79
    }
80 80

	
81 81
    ///The type of the map that indicates which nodes are reached.
82 82

	
83
    ///The type of the map that indicates which nodes are reached.
84
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
83
    ///The type of the map that indicates which nodes are reached.///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
85 84
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
86 85
    ///Instantiates a ReachedMap.
87 86

	
88 87
    ///This function instantiates a ReachedMap.
89 88
    ///\param g is the digraph, to which
90 89
    ///we would like to define the ReachedMap.
91 90
    static ReachedMap *createReachedMap(const Digraph &g)
92 91
    {
93 92
      return new ReachedMap(g);
94 93
    }
95 94

	
96 95
    ///The type of the map that stores the distances of the nodes.
97 96

	
98 97
    ///The type of the map that stores the distances of the nodes.
99 98
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
100 99
    typedef typename Digraph::template NodeMap<int> DistMap;
101 100
    ///Instantiates a DistMap.
102 101

	
103 102
    ///This function instantiates a DistMap.
104 103
    ///\param g is the digraph, to which we would like to define the
105 104
    ///DistMap.
106 105
    static DistMap *createDistMap(const Digraph &g)
107 106
    {
108 107
      return new DistMap(g);
109 108
    }
110 109
  };
111 110

	
112 111
  ///%BFS algorithm class.
113 112

	
114 113
  ///\ingroup search
115 114
  ///This class provides an efficient implementation of the %BFS algorithm.
116 115
  ///
117 116
  ///There is also a \ref bfs() "function-type interface" for the BFS
118 117
  ///algorithm, which is convenient in the simplier cases and it can be
119 118
  ///used easier.
120 119
  ///
121 120
  ///\tparam GR The type of the digraph the algorithm runs on.
122 121
  ///The default value is \ref ListDigraph. The value of GR is not used
123 122
  ///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits.
124 123
  ///\tparam TR Traits class to set various data types used by the algorithm.
125 124
  ///The default traits class is
126 125
  ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
127 126
  ///See \ref BfsDefaultTraits for the documentation of
128 127
  ///a Bfs traits class.
129 128
#ifdef DOXYGEN
130 129
  template <typename GR,
131 130
            typename TR>
132 131
#else
133 132
  template <typename GR=ListDigraph,
134 133
            typename TR=BfsDefaultTraits<GR> >
135 134
#endif
136 135
  class Bfs {
137 136
  public:
138 137

	
139 138
    ///The type of the digraph the algorithm runs on.
140 139
    typedef typename TR::Digraph Digraph;
141 140

	
142 141
    ///\brief The type of the map that stores the predecessor arcs of the
143 142
    ///shortest paths.
144 143
    typedef typename TR::PredMap PredMap;
145 144
    ///The type of the map that stores the distances of the nodes.
146 145
    typedef typename TR::DistMap DistMap;
147 146
    ///The type of the map that indicates which nodes are reached.
148 147
    typedef typename TR::ReachedMap ReachedMap;
149 148
    ///The type of the map that indicates which nodes are processed.
150 149
    typedef typename TR::ProcessedMap ProcessedMap;
151 150
    ///The type of the paths.
152 151
    typedef PredMapPath<Digraph, PredMap> Path;
153 152

	
154 153
    ///The traits class.
155 154
    typedef TR Traits;
156 155

	
157 156
  private:
158 157

	
159 158
    typedef typename Digraph::Node Node;
160 159
    typedef typename Digraph::NodeIt NodeIt;
161 160
    typedef typename Digraph::Arc Arc;
162 161
    typedef typename Digraph::OutArcIt OutArcIt;
163 162

	
164 163
    //Pointer to the underlying digraph.
165 164
    const Digraph *G;
166 165
    //Pointer to the map of predecessor arcs.
167 166
    PredMap *_pred;
168 167
    //Indicates if _pred is locally allocated (true) or not.
169 168
    bool local_pred;
170 169
    //Pointer to the map of distances.
171 170
    DistMap *_dist;
172 171
    //Indicates if _dist is locally allocated (true) or not.
173 172
    bool local_dist;
174 173
    //Pointer to the map of reached status of the nodes.
175 174
    ReachedMap *_reached;
176 175
    //Indicates if _reached is locally allocated (true) or not.
177 176
    bool local_reached;
178 177
    //Pointer to the map of processed status of the nodes.
179 178
    ProcessedMap *_processed;
180 179
    //Indicates if _processed is locally allocated (true) or not.
181 180
    bool local_processed;
182 181

	
183 182
    std::vector<typename Digraph::Node> _queue;
184 183
    int _queue_head,_queue_tail,_queue_next_dist;
185 184
    int _curr_dist;
186 185

	
187 186
    //Creates the maps if necessary.
188 187
    void create_maps()
189 188
    {
190 189
      if(!_pred) {
191 190
        local_pred = true;
192 191
        _pred = Traits::createPredMap(*G);
193 192
      }
194 193
      if(!_dist) {
195 194
        local_dist = true;
196 195
        _dist = Traits::createDistMap(*G);
197 196
      }
198 197
      if(!_reached) {
199 198
        local_reached = true;
200 199
        _reached = Traits::createReachedMap(*G);
201 200
      }
202 201
      if(!_processed) {
203 202
        local_processed = true;
204 203
        _processed = Traits::createProcessedMap(*G);
205 204
      }
206 205
    }
207 206

	
208 207
  protected:
209 208

	
210 209
    Bfs() {}
211 210

	
212 211
  public:
213 212

	
214 213
    typedef Bfs Create;
215 214

	
216 215
    ///\name Named template parameters
217 216

	
218 217
    ///@{
219 218

	
220 219
    template <class T>
221 220
    struct SetPredMapTraits : public Traits {
222 221
      typedef T PredMap;
223 222
      static PredMap *createPredMap(const Digraph &)
224 223
      {
225 224
        LEMON_ASSERT(false, "PredMap is not initialized");
226 225
        return 0; // ignore warnings
227 226
      }
228 227
    };
229 228
    ///\brief \ref named-templ-param "Named parameter" for setting
230 229
    ///PredMap type.
231 230
    ///
232 231
    ///\ref named-templ-param "Named parameter" for setting
233 232
    ///PredMap type.
234 233
    template <class T>
235 234
    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
236 235
      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
237 236
    };
238 237

	
239 238
    template <class T>
240 239
    struct SetDistMapTraits : public Traits {
241 240
      typedef T DistMap;
242 241
      static DistMap *createDistMap(const Digraph &)
243 242
      {
244 243
        LEMON_ASSERT(false, "DistMap is not initialized");
245 244
        return 0; // ignore warnings
246 245
      }
247 246
    };
248 247
    ///\brief \ref named-templ-param "Named parameter" for setting
249 248
    ///DistMap type.
250 249
    ///
251 250
    ///\ref named-templ-param "Named parameter" for setting
252 251
    ///DistMap type.
253 252
    template <class T>
254 253
    struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
255 254
      typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
256 255
    };
257 256

	
258 257
    template <class T>
259 258
    struct SetReachedMapTraits : public Traits {
260 259
      typedef T ReachedMap;
261 260
      static ReachedMap *createReachedMap(const Digraph &)
262 261
      {
263 262
        LEMON_ASSERT(false, "ReachedMap is not initialized");
264 263
        return 0; // ignore warnings
265 264
      }
266 265
    };
267 266
    ///\brief \ref named-templ-param "Named parameter" for setting
268 267
    ///ReachedMap type.
269 268
    ///
270 269
    ///\ref named-templ-param "Named parameter" for setting
271 270
    ///ReachedMap type.
272 271
    template <class T>
273 272
    struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > {
274 273
      typedef Bfs< Digraph, SetReachedMapTraits<T> > Create;
275 274
    };
276 275

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

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

	
315 314
    ///@}
316 315

	
317 316
  public:
318 317

	
319 318
    ///Constructor.
320 319

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

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

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

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

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

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

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

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

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

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

	
409 408
  public:
410 409

	
411 410
    ///\name Execution control
412 411
    ///The simplest way to execute the algorithm is to use
413 412
    ///one of the member functions called \ref lemon::Bfs::run() "run()".
414 413
    ///\n
415 414
    ///If you need more control on the execution, first you must call
416 415
    ///\ref lemon::Bfs::init() "init()", then you can add several source
417 416
    ///nodes with \ref lemon::Bfs::addSource() "addSource()".
418 417
    ///Finally \ref lemon::Bfs::start() "start()" will perform the
419 418
    ///actual path computation.
420 419

	
421 420
    ///@{
422 421

	
423 422
    ///Initializes the internal data structures.
424 423

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
572 571
    ///Executes the algorithm.
573 572

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

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

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

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

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

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

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

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

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

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

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

	
731 730
    ///@}
732 731

	
733 732
    ///\name Query Functions
734 733
    ///The result of the %BFS algorithm can be obtained using these
735 734
    ///functions.\n
736 735
    ///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start()
737 736
    ///"start()" must be called before using them.
738 737

	
739 738
    ///@{
740 739

	
741 740
    ///The shortest path to a node.
742 741

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

	
751 750
    ///The distance of a node from the root(s).
752 751

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

	
762 761
    ///Returns the 'previous arc' of the shortest path tree for a node.
763 762

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

	
776 775
    ///Returns the 'previous node' of the shortest path tree for a node.
777 776

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

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

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

	
811 810
    ///Checks if a node is reachable from the root(s).
812 811

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

	
818 817
    ///@}
819 818
  };
820 819

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

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

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

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

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

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

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

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

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

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

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

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

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

	
898 897
    ///The type of the shortest paths.
899 898

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

	
905 904
  /// Default traits class used by BfsWizard
906 905

	
907 906
  /// To make it easier to use Bfs algorithm
908 907
  /// we have created a wizard class.
909 908
  /// This \ref BfsWizard class needs default traits,
910 909
  /// as well as the \ref Bfs class.
911 910
  /// The \ref BfsWizardBase is a class to be the default traits of the
912 911
  /// \ref BfsWizard class.
913 912
  template<class GR>
914 913
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
915 914
  {
916 915

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

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

	
937 936
    public:
938 937
    /// Constructor.
939 938

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

	
945 944
    /// Constructor.
946 945

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

	
954 953
  };
955 954

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

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

	
970 969
    ///The type of the digraph the algorithm runs on.
971 970
    typedef typename TR::Digraph Digraph;
972 971

	
973 972
    typedef typename Digraph::Node Node;
974 973
    typedef typename Digraph::NodeIt NodeIt;
975 974
    typedef typename Digraph::Arc Arc;
976 975
    typedef typename Digraph::OutArcIt OutArcIt;
977 976

	
978 977
    ///\brief The type of the map that stores the predecessor
979 978
    ///arcs of the shortest paths.
980 979
    typedef typename TR::PredMap PredMap;
981 980
    ///\brief The type of the map that stores the distances of the nodes.
982 981
    typedef typename TR::DistMap DistMap;
983 982
    ///\brief The type of the map that indicates which nodes are reached.
984 983
    typedef typename TR::ReachedMap ReachedMap;
985 984
    ///\brief The type of the map that indicates which nodes are processed.
986 985
    typedef typename TR::ProcessedMap ProcessedMap;
987 986
    ///The type of the shortest paths
988 987
    typedef typename TR::Path Path;
989 988

	
990 989
  public:
991 990

	
992 991
    /// Constructor.
993 992
    BfsWizard() : TR() {}
994 993

	
995 994
    /// Constructor that requires parameters.
996 995

	
997 996
    /// Constructor that requires parameters.
998 997
    /// These parameters will be the default values for the traits class.
999 998
    /// \param g The digraph the algorithm runs on.
1000 999
    BfsWizard(const Digraph &g) :
1001 1000
      TR(g) {}
1002 1001

	
1003 1002
    ///Copy constructor
1004 1003
    BfsWizard(const TR &b) : TR(b) {}
1005 1004

	
1006 1005
    ~BfsWizard() {}
1007 1006

	
1008 1007
    ///Runs BFS algorithm from the given source node.
1009 1008

	
1010 1009
    ///This method runs BFS algorithm from node \c s
1011 1010
    ///in order to compute the shortest path to each node.
1012 1011
    void run(Node s)
1013 1012
    {
1014 1013
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1015 1014
      if (Base::_pred)
1016 1015
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1017 1016
      if (Base::_dist)
1018 1017
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1019 1018
      if (Base::_reached)
1020 1019
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1021 1020
      if (Base::_processed)
1022 1021
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1023 1022
      if (s!=INVALID)
1024 1023
        alg.run(s);
1025 1024
      else
1026 1025
        alg.run();
1027 1026
    }
1028 1027

	
1029 1028
    ///Finds the shortest path between \c s and \c t.
1030 1029

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

	
1055 1054
    ///Runs BFS algorithm to visit all nodes in the digraph.
1056 1055

	
1057 1056
    ///This method runs BFS algorithm in order to compute
1058 1057
    ///the shortest path to each node.
1059 1058
    void run()
1060 1059
    {
1061 1060
      run(INVALID);
1062 1061
    }
1063 1062

	
1064 1063
    template<class T>
1065 1064
    struct SetPredMapBase : public Base {
1066 1065
      typedef T PredMap;
1067 1066
      static PredMap *createPredMap(const Digraph &) { return 0; };
1068 1067
      SetPredMapBase(const TR &b) : TR(b) {}
1069 1068
    };
1070 1069
    ///\brief \ref named-func-param "Named parameter"
1071 1070
    ///for setting PredMap object.
1072 1071
    ///
1073 1072
    ///\ref named-func-param "Named parameter"
1074 1073
    ///for setting PredMap object.
1075 1074
    template<class T>
1076 1075
    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1077 1076
    {
1078 1077
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1079 1078
      return BfsWizard<SetPredMapBase<T> >(*this);
1080 1079
    }
1081 1080

	
1082 1081
    template<class T>
1083 1082
    struct SetReachedMapBase : public Base {
1084 1083
      typedef T ReachedMap;
1085 1084
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1086 1085
      SetReachedMapBase(const TR &b) : TR(b) {}
1087 1086
    };
1088 1087
    ///\brief \ref named-func-param "Named parameter"
1089 1088
    ///for setting ReachedMap object.
1090 1089
    ///
1091 1090
    /// \ref named-func-param "Named parameter"
1092 1091
    ///for setting ReachedMap object.
1093 1092
    template<class T>
1094 1093
    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1095 1094
    {
1096 1095
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1097 1096
      return BfsWizard<SetReachedMapBase<T> >(*this);
1098 1097
    }
1099 1098

	
1100 1099
    template<class T>
1101 1100
    struct SetDistMapBase : public Base {
1102 1101
      typedef T DistMap;
1103 1102
      static DistMap *createDistMap(const Digraph &) { return 0; };
1104 1103
      SetDistMapBase(const TR &b) : TR(b) {}
1105 1104
    };
1106 1105
    ///\brief \ref named-func-param "Named parameter"
1107 1106
    ///for setting DistMap object.
1108 1107
    ///
1109 1108
    /// \ref named-func-param "Named parameter"
1110 1109
    ///for setting DistMap object.
1111 1110
    template<class T>
1112 1111
    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1113 1112
    {
1114 1113
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1115 1114
      return BfsWizard<SetDistMapBase<T> >(*this);
1116 1115
    }
1117 1116

	
1118 1117
    template<class T>
1119 1118
    struct SetProcessedMapBase : public Base {
1120 1119
      typedef T ProcessedMap;
1121 1120
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1122 1121
      SetProcessedMapBase(const TR &b) : TR(b) {}
1123 1122
    };
1124 1123
    ///\brief \ref named-func-param "Named parameter"
1125 1124
    ///for setting ProcessedMap object.
1126 1125
    ///
1127 1126
    /// \ref named-func-param "Named parameter"
1128 1127
    ///for setting ProcessedMap object.
1129 1128
    template<class T>
1130 1129
    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1131 1130
    {
1132 1131
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1133 1132
      return BfsWizard<SetProcessedMapBase<T> >(*this);
1134 1133
    }
1135 1134

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

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

	
1164 1163
  };
1165 1164

	
1166 1165
  ///Function-type interface for BFS algorithm.
1167 1166

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

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

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

	
1254 1253
  /// \brief Default traits class of BfsVisit class.
1255 1254
  ///
1256 1255
  /// Default traits class of BfsVisit class.
1257 1256
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1258 1257
  template<class _Digraph>
1259 1258
  struct BfsVisitDefaultTraits {
1260 1259

	
1261 1260
    /// \brief The type of the digraph the algorithm runs on.
1262 1261
    typedef _Digraph Digraph;
1263 1262

	
1264 1263
    /// \brief The type of the map that indicates which nodes are reached.
1265 1264
    ///
1266 1265
    /// The type of the map that indicates which nodes are reached.
1267 1266
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1268 1267
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1269 1268

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

	
1279 1278
  };
1280 1279

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

	
1320 1319
    ///The traits class.
1321 1320
    typedef _Traits Traits;
1322 1321

	
1323 1322
    ///The type of the digraph the algorithm runs on.
1324 1323
    typedef typename Traits::Digraph Digraph;
1325 1324

	
1326 1325
    ///The visitor type used by the algorithm.
1327 1326
    typedef _Visitor Visitor;
1328 1327

	
1329 1328
    ///The type of the map that indicates which nodes are reached.
1330 1329
    typedef typename Traits::ReachedMap ReachedMap;
1331 1330

	
1332 1331
  private:
1333 1332

	
1334 1333
    typedef typename Digraph::Node Node;
1335 1334
    typedef typename Digraph::NodeIt NodeIt;
1336 1335
    typedef typename Digraph::Arc Arc;
1337 1336
    typedef typename Digraph::OutArcIt OutArcIt;
1338 1337

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

	
1348 1347
    std::vector<typename Digraph::Node> _list;
1349 1348
    int _list_front, _list_back;
1350 1349

	
1351 1350
    //Creates the maps if necessary.
1352 1351
    void create_maps() {
1353 1352
      if(!_reached) {
1354 1353
        local_reached = true;
1355 1354
        _reached = Traits::createReachedMap(*_digraph);
1356 1355
      }
1357 1356
    }
1358 1357

	
1359 1358
  protected:
1360 1359

	
1361 1360
    BfsVisit() {}
1362 1361

	
1363 1362
  public:
1364 1363

	
1365 1364
    typedef BfsVisit Create;
1366 1365

	
1367 1366
    /// \name Named template parameters
1368 1367

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

	
1389 1388
  public:
1390 1389

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

	
1401 1400
    /// \brief Destructor.
1402 1401
    ~BfsVisit() {
1403 1402
      if(local_reached) delete _reached;
1404 1403
    }
1405 1404

	
1406 1405
    /// \brief Sets the map that indicates which nodes are reached.
1407 1406
    ///
1408 1407
    /// Sets the map that indicates which nodes are reached.
1409 1408
    /// If you don't use this function before calling \ref run(),
1410 1409
    /// it will allocate one. The destructor deallocates this
1411 1410
    /// automatically allocated map, of course.
1412 1411
    /// \return <tt> (*this) </tt>
1413 1412
    BfsVisit &reachedMap(ReachedMap &m) {
1414 1413
      if(local_reached) {
1415 1414
        delete _reached;
1416 1415
        local_reached = false;
1417 1416
      }
1418 1417
      _reached = &m;
1419 1418
      return *this;
1420 1419
    }
1421 1420

	
1422 1421
  public:
1423 1422

	
1424 1423
    /// \name Execution control
1425 1424
    /// The simplest way to execute the algorithm is to use
1426 1425
    /// one of the member functions called \ref lemon::BfsVisit::run()
1427 1426
    /// "run()".
1428 1427
    /// \n
1429 1428
    /// If you need more control on the execution, first you must call
1430 1429
    /// \ref lemon::BfsVisit::init() "init()", then you can add several
1431 1430
    /// source nodes with \ref lemon::BfsVisit::addSource() "addSource()".
1432 1431
    /// Finally \ref lemon::BfsVisit::start() "start()" will perform the
1433 1432
    /// actual path computation.
1434 1433

	
1435 1434
    /// @{
1436 1435

	
1437 1436
    /// \brief Initializes the internal data structures.
1438 1437
    ///
1439 1438
    /// Initializes the internal data structures.
1440 1439
    void init() {
1441 1440
      create_maps();
1442 1441
      _list.resize(countNodes(*_digraph));
1443 1442
      _list_front = _list_back = -1;
1444 1443
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1445 1444
        _reached->set(u, false);
1446 1445
      }
1447 1446
    }
1448 1447

	
1449 1448
    /// \brief Adds a new source node.
1450 1449
    ///
1451 1450
    /// Adds a new source node to the set of nodes to be processed.
1452 1451
    void addSource(Node s) {
1453 1452
      if(!(*_reached)[s]) {
1454 1453
          _reached->set(s,true);
1455 1454
          _visitor->start(s);
1456 1455
          _visitor->reach(s);
1457 1456
          _list[++_list_back] = s;
1458 1457
        }
1459 1458
    }
1460 1459

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

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

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

	
1553 1552
    /// \brief The next node to be processed.
1554 1553
    ///
1555 1554
    /// Returns the next node to be processed or \c INVALID if the queue
1556 1555
    /// is empty.
1557 1556
    Node nextNode() const {
1558 1557
      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1559 1558
    }
1560 1559

	
1561 1560
    /// \brief Returns \c false if there are nodes
1562 1561
    /// to be processed.
1563 1562
    ///
1564 1563
    /// Returns \c false if there are nodes
1565 1564
    /// to be processed in the queue.
1566 1565
    bool emptyQueue() const { return _list_front == _list_back; }
1567 1566

	
1568 1567
    /// \brief Returns the number of the nodes to be processed.
1569 1568
    ///
1570 1569
    /// Returns the number of the nodes to be processed in the queue.
1571 1570
    int queueSize() const { return _list_back - _list_front; }
1572 1571

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

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

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

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

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

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

	
1730 1729
    ///@}
1731 1730

	
1732 1731
    /// \name Query Functions
1733 1732
    /// The result of the %BFS algorithm can be obtained using these
1734 1733
    /// functions.\n
1735 1734
    /// Either \ref lemon::BfsVisit::run() "run()" or
1736 1735
    /// \ref lemon::BfsVisit::start() "start()" must be called before
1737 1736
    /// using them.
1738 1737
    ///@{
1739 1738

	
1740 1739
    /// \brief Checks if a node is reachable from the root(s).
1741 1740
    ///
1742 1741
    /// Returns \c true if \c v is reachable from the root(s).
1743 1742
    /// \pre Either \ref run() or \ref start()
1744 1743
    /// must be called before using this function.
1745 1744
    bool reached(Node v) { return (*_reached)[v]; }
1746 1745

	
1747 1746
    ///@}
1748 1747

	
1749 1748
  };
1750 1749

	
1751 1750
} //END OF NAMESPACE LEMON
1752 1751

	
1753 1752
#endif
Ignore white space 24576 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_LIST_GRAPH_H
20 20
#define LEMON_LIST_GRAPH_H
21 21

	
22 22
///\ingroup graphs
23 23
///\file
24 24
///\brief ListDigraph, 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 ListDigraphBase {
36 36

	
37 37
  protected:
38 38
    struct NodeT {
39 39
      int first_in, first_out;
40 40
      int prev, next;
41 41
    };
42 42

	
43 43
    struct ArcT {
44 44
      int target, source;
45 45
      int prev_in, prev_out;
46 46
      int next_in, next_out;
47 47
    };
48 48

	
49 49
    std::vector<NodeT> nodes;
50 50

	
51 51
    int first_node;
52 52

	
53 53
    int first_free_node;
54 54

	
55 55
    std::vector<ArcT> arcs;
56 56

	
57 57
    int first_free_arc;
58 58

	
59 59
  public:
60 60

	
61 61
    typedef ListDigraphBase Digraph;
62 62

	
63 63
    class Node {
64 64
      friend class ListDigraphBase;
65 65
    protected:
66 66

	
67 67
      int id;
68 68
      explicit Node(int pid) { id = pid;}
69 69

	
70 70
    public:
71 71
      Node() {}
72 72
      Node (Invalid) { id = -1; }
73 73
      bool operator==(const Node& node) const {return id == node.id;}
74 74
      bool operator!=(const Node& node) const {return id != node.id;}
75 75
      bool operator<(const Node& node) const {return id < node.id;}
76 76
    };
77 77

	
78 78
    class Arc {
79 79
      friend class ListDigraphBase;
80 80
    protected:
81 81

	
82 82
      int id;
83 83
      explicit Arc(int pid) { id = pid;}
84 84

	
85 85
    public:
86 86
      Arc() {}
87 87
      Arc (Invalid) { id = -1; }
88 88
      bool operator==(const Arc& arc) const {return id == arc.id;}
89 89
      bool operator!=(const Arc& arc) const {return id != arc.id;}
90 90
      bool operator<(const Arc& arc) const {return id < arc.id;}
91 91
    };
92 92

	
93 93

	
94 94

	
95 95
    ListDigraphBase()
96 96
      : nodes(), first_node(-1),
97 97
        first_free_node(-1), arcs(), first_free_arc(-1) {}
98 98

	
99 99

	
100 100
    int maxNodeId() const { return nodes.size()-1; }
101 101
    int maxArcId() const { return arcs.size()-1; }
102 102

	
103 103
    Node source(Arc e) const { return Node(arcs[e.id].source); }
104 104
    Node target(Arc e) const { return Node(arcs[e.id].target); }
105 105

	
106 106

	
107 107
    void first(Node& node) const {
108 108
      node.id = first_node;
109 109
    }
110 110

	
111 111
    void next(Node& node) const {
112 112
      node.id = nodes[node.id].next;
113 113
    }
114 114

	
115 115

	
116 116
    void first(Arc& arc) const {
117 117
      int n;
118 118
      for(n = first_node;
119 119
          n!=-1 && nodes[n].first_in == -1;
120 120
          n = nodes[n].next) {}
121 121
      arc.id = (n == -1) ? -1 : nodes[n].first_in;
122 122
    }
123 123

	
124 124
    void next(Arc& arc) const {
125 125
      if (arcs[arc.id].next_in != -1) {
126 126
        arc.id = arcs[arc.id].next_in;
127 127
      } else {
128 128
        int n;
129 129
        for(n = nodes[arcs[arc.id].target].next;
130 130
            n!=-1 && nodes[n].first_in == -1;
131 131
            n = nodes[n].next) {}
132 132
        arc.id = (n == -1) ? -1 : nodes[n].first_in;
133 133
      }
134 134
    }
135 135

	
136 136
    void firstOut(Arc &e, const Node& v) const {
137 137
      e.id = nodes[v.id].first_out;
138 138
    }
139 139
    void nextOut(Arc &e) const {
140 140
      e.id=arcs[e.id].next_out;
141 141
    }
142 142

	
143 143
    void firstIn(Arc &e, const Node& v) const {
144 144
      e.id = nodes[v.id].first_in;
145 145
    }
146 146
    void nextIn(Arc &e) const {
147 147
      e.id=arcs[e.id].next_in;
148 148
    }
149 149

	
150 150

	
151 151
    static int id(Node v) { return v.id; }
152 152
    static int id(Arc e) { return e.id; }
153 153

	
154 154
    static Node nodeFromId(int id) { return Node(id);}
155 155
    static Arc arcFromId(int id) { return Arc(id);}
156 156

	
157 157
    bool valid(Node n) const {
158 158
      return n.id >= 0 && n.id < static_cast<int>(nodes.size()) &&
159 159
        nodes[n.id].prev != -2;
160 160
    }
161 161

	
162 162
    bool valid(Arc a) const {
163 163
      return a.id >= 0 && a.id < static_cast<int>(arcs.size()) &&
164 164
        arcs[a.id].prev_in != -2;
165 165
    }
166 166

	
167 167
    Node addNode() {
168 168
      int n;
169 169

	
170 170
      if(first_free_node==-1) {
171 171
        n = nodes.size();
172 172
        nodes.push_back(NodeT());
173 173
      } else {
174 174
        n = first_free_node;
175 175
        first_free_node = nodes[n].next;
176 176
      }
177 177

	
178 178
      nodes[n].next = first_node;
179 179
      if(first_node != -1) nodes[first_node].prev = n;
180 180
      first_node = n;
181 181
      nodes[n].prev = -1;
182 182

	
183 183
      nodes[n].first_in = nodes[n].first_out = -1;
184 184

	
185 185
      return Node(n);
186 186
    }
187 187

	
188 188
    Arc addArc(Node u, Node v) {
189 189
      int n;
190 190

	
191 191
      if (first_free_arc == -1) {
192 192
        n = arcs.size();
193 193
        arcs.push_back(ArcT());
194 194
      } else {
195 195
        n = first_free_arc;
196 196
        first_free_arc = arcs[n].next_in;
197 197
      }
198 198

	
199 199
      arcs[n].source = u.id;
200 200
      arcs[n].target = v.id;
201 201

	
202 202
      arcs[n].next_out = nodes[u.id].first_out;
203 203
      if(nodes[u.id].first_out != -1) {
204 204
        arcs[nodes[u.id].first_out].prev_out = n;
205 205
      }
206 206

	
207 207
      arcs[n].next_in = nodes[v.id].first_in;
208 208
      if(nodes[v.id].first_in != -1) {
209 209
        arcs[nodes[v.id].first_in].prev_in = n;
210 210
      }
211 211

	
212 212
      arcs[n].prev_in = arcs[n].prev_out = -1;
213 213

	
214 214
      nodes[u.id].first_out = nodes[v.id].first_in = n;
215 215

	
216 216
      return Arc(n);
217 217
    }
218 218

	
219 219
    void erase(const Node& node) {
220 220
      int n = node.id;
221 221

	
222 222
      if(nodes[n].next != -1) {
223 223
        nodes[nodes[n].next].prev = nodes[n].prev;
224 224
      }
225 225

	
226 226
      if(nodes[n].prev != -1) {
227 227
        nodes[nodes[n].prev].next = nodes[n].next;
228 228
      } else {
229 229
        first_node = nodes[n].next;
230 230
      }
231 231

	
232 232
      nodes[n].next = first_free_node;
233 233
      first_free_node = n;
234 234
      nodes[n].prev = -2;
235 235

	
236 236
    }
237 237

	
238 238
    void erase(const Arc& arc) {
239 239
      int n = arc.id;
240 240

	
241 241
      if(arcs[n].next_in!=-1) {
242 242
        arcs[arcs[n].next_in].prev_in = arcs[n].prev_in;
243 243
      }
244 244

	
245 245
      if(arcs[n].prev_in!=-1) {
246 246
        arcs[arcs[n].prev_in].next_in = arcs[n].next_in;
247 247
      } else {
248 248
        nodes[arcs[n].target].first_in = arcs[n].next_in;
249 249
      }
250 250

	
251 251

	
252 252
      if(arcs[n].next_out!=-1) {
253 253
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
254 254
      }
255 255

	
256 256
      if(arcs[n].prev_out!=-1) {
257 257
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
258 258
      } else {
259 259
        nodes[arcs[n].source].first_out = arcs[n].next_out;
260 260
      }
261 261

	
262 262
      arcs[n].next_in = first_free_arc;
263 263
      first_free_arc = n;
264 264
      arcs[n].prev_in = -2;
265 265
    }
266 266

	
267 267
    void clear() {
268 268
      arcs.clear();
269 269
      nodes.clear();
270 270
      first_node = first_free_node = first_free_arc = -1;
271 271
    }
272 272

	
273 273
  protected:
274 274
    void changeTarget(Arc e, Node n)
275 275
    {
276 276
      if(arcs[e.id].next_in != -1)
277 277
        arcs[arcs[e.id].next_in].prev_in = arcs[e.id].prev_in;
278 278
      if(arcs[e.id].prev_in != -1)
279 279
        arcs[arcs[e.id].prev_in].next_in = arcs[e.id].next_in;
280 280
      else nodes[arcs[e.id].target].first_in = arcs[e.id].next_in;
281 281
      if (nodes[n.id].first_in != -1) {
282 282
        arcs[nodes[n.id].first_in].prev_in = e.id;
283 283
      }
284 284
      arcs[e.id].target = n.id;
285 285
      arcs[e.id].prev_in = -1;
286 286
      arcs[e.id].next_in = nodes[n.id].first_in;
287 287
      nodes[n.id].first_in = e.id;
288 288
    }
289 289
    void changeSource(Arc e, Node n)
290 290
    {
291 291
      if(arcs[e.id].next_out != -1)
292 292
        arcs[arcs[e.id].next_out].prev_out = arcs[e.id].prev_out;
293 293
      if(arcs[e.id].prev_out != -1)
294 294
        arcs[arcs[e.id].prev_out].next_out = arcs[e.id].next_out;
295 295
      else nodes[arcs[e.id].source].first_out = arcs[e.id].next_out;
296 296
      if (nodes[n.id].first_out != -1) {
297 297
        arcs[nodes[n.id].first_out].prev_out = e.id;
298 298
      }
299 299
      arcs[e.id].source = n.id;
300 300
      arcs[e.id].prev_out = -1;
301 301
      arcs[e.id].next_out = nodes[n.id].first_out;
302 302
      nodes[n.id].first_out = e.id;
303 303
    }
304 304

	
305 305
  };
306 306

	
307 307
  typedef DigraphExtender<ListDigraphBase> ExtendedListDigraphBase;
308 308

	
309 309
  /// \addtogroup graphs
310 310
  /// @{
311 311

	
312 312
  ///A general directed graph structure.
313 313

	
314 314
  ///\ref ListDigraph is a simple and fast <em>directed graph</em>
315 315
  ///implementation based on static linked lists that are stored in
316 316
  ///\c std::vector structures.
317 317
  ///
318 318
  ///It conforms to the \ref concepts::Digraph "Digraph concept" and it
319 319
  ///also provides several useful additional functionalities.
320 320
  ///Most of the member functions and nested classes are documented
321 321
  ///only in the concept class.
322 322
  ///
323 323
  ///An important extra feature of this digraph implementation is that
324 324
  ///its maps are real \ref concepts::ReferenceMap "reference map"s.
325 325
  ///
326 326
  ///\sa concepts::Digraph
327 327

	
328 328
  class ListDigraph : public ExtendedListDigraphBase {
329 329
  private:
330 330
    ///ListDigraph is \e not copy constructible. Use copyDigraph() instead.
331 331

	
332 332
    ///ListDigraph is \e not copy constructible. Use copyDigraph() instead.
333 333
    ///
334 334
    ListDigraph(const ListDigraph &) :ExtendedListDigraphBase() {};
335 335
    ///\brief Assignment of ListDigraph to another one is \e not allowed.
336 336
    ///Use copyDigraph() instead.
337 337

	
338 338
    ///Assignment of ListDigraph to another one is \e not allowed.
339 339
    ///Use copyDigraph() instead.
340 340
    void operator=(const ListDigraph &) {}
341 341
  public:
342 342

	
343 343
    typedef ExtendedListDigraphBase Parent;
344 344

	
345 345
    /// Constructor
346 346

	
347 347
    /// Constructor.
348 348
    ///
349 349
    ListDigraph() {}
350 350

	
351 351
    ///Add a new node to the digraph.
352 352

	
353 353
    ///Add a new node to the digraph.
354 354
    ///\return the new node.
355 355
    Node addNode() { return Parent::addNode(); }
356 356

	
357 357
    ///Add a new arc to the digraph.
358 358

	
359 359
    ///Add a new arc to the digraph with source node \c s
360 360
    ///and target node \c t.
361 361
    ///\return the new arc.
362 362
    Arc addArc(const Node& s, const Node& t) {
363 363
      return Parent::addArc(s, t);
364 364
    }
365 365

	
366 366
    ///\brief Erase a node from the digraph.
367 367
    ///
368 368
    ///Erase a node from the digraph.
369 369
    ///
370 370
    void erase(const Node& n) { Parent::erase(n); }
371 371

	
372 372
    ///\brief Erase an arc from the digraph.
373 373
    ///
374 374
    ///Erase an arc from the digraph.
375 375
    ///
376 376
    void erase(const Arc& a) { Parent::erase(a); }
377 377

	
378 378
    /// Node validity check
379 379

	
380 380
    /// This function gives back true if the given node is valid,
381 381
    /// ie. it is a real node of the graph.
382 382
    ///
383 383
    /// \warning A Node pointing to a removed item
384 384
    /// could become valid again later if new nodes are
385 385
    /// added to the graph.
386 386
    bool valid(Node n) const { return Parent::valid(n); }
387 387

	
388 388
    /// Arc validity check
389 389

	
390 390
    /// This function gives back true if the given arc is valid,
391 391
    /// ie. it is a real arc of the graph.
392 392
    ///
393 393
    /// \warning An Arc pointing to a removed item
394 394
    /// could become valid again later if new nodes are
395 395
    /// added to the graph.
396 396
    bool valid(Arc a) const { return Parent::valid(a); }
397 397

	
398 398
    /// Change the target of \c a to \c n
399 399

	
400 400
    /// Change the target of \c a to \c n
401 401
    ///
402 402
    ///\note The <tt>ArcIt</tt>s and <tt>OutArcIt</tt>s referencing
403 403
    ///the changed arc remain valid. However <tt>InArcIt</tt>s are
404 404
    ///invalidated.
405 405
    ///
406 406
    ///\warning This functionality cannot be used together with the Snapshot
407 407
    ///feature.
408 408
    void changeTarget(Arc a, Node n) {
409 409
      Parent::changeTarget(a,n);
410 410
    }
411 411
    /// Change the source of \c a to \c n
412 412

	
413 413
    /// Change the source of \c a to \c n
414 414
    ///
415 415
    ///\note The <tt>InArcIt</tt>s referencing the changed arc remain
416 416
    ///valid. However the <tt>ArcIt</tt>s and <tt>OutArcIt</tt>s are
417 417
    ///invalidated.
418 418
    ///
419 419
    ///\warning This functionality cannot be used together with the Snapshot
420 420
    ///feature.
421 421
    void changeSource(Arc a, Node n) {
422 422
      Parent::changeSource(a,n);
423 423
    }
424 424

	
425 425
    /// Invert the direction of an arc.
426 426

	
427 427
    ///\note The <tt>ArcIt</tt>s referencing the changed arc remain
428 428
    ///valid. However <tt>OutArcIt</tt>s and <tt>InArcIt</tt>s are
429 429
    ///invalidated.
430 430
    ///
431 431
    ///\warning This functionality cannot be used together with the Snapshot
432 432
    ///feature.
433 433
    void reverseArc(Arc e) {
434 434
      Node t=target(e);
435 435
      changeTarget(e,source(e));
436 436
      changeSource(e,t);
437 437
    }
438 438

	
439 439
    /// Reserve memory for nodes.
440 440

	
441 441
    /// Using this function it is possible to avoid the superfluous memory
442 442
    /// allocation: if you know that the digraph you want to build will
443 443
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
444 444
    /// then it is worth reserving space for this amount before starting
445 445
    /// to build the digraph.
446 446
    /// \sa reserveArc
447 447
    void reserveNode(int n) { nodes.reserve(n); };
448 448

	
449 449
    /// Reserve memory for arcs.
450 450

	
451 451
    /// Using this function it is possible to avoid the superfluous memory
452 452
    /// allocation: if you know that the digraph you want to build will
453 453
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
454 454
    /// then it is worth reserving space for this amount before starting
455 455
    /// to build the digraph.
456 456
    /// \sa reserveNode
457 457
    void reserveArc(int m) { arcs.reserve(m); };
458 458

	
459 459
    ///Contract two nodes.
460 460

	
461 461
    ///This function contracts two nodes.
462 462
    ///Node \p b will be removed but instead of deleting
463 463
    ///incident arcs, they will be joined to \p a.
464 464
    ///The last parameter \p r controls whether to remove loops. \c true
465 465
    ///means that loops will be removed.
466 466
    ///
467 467
    ///\note The <tt>ArcIt</tt>s referencing a moved arc remain
468 468
    ///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s
469 469
    ///may be invalidated.
470 470
    ///
471 471
    ///\warning This functionality cannot be used together with the Snapshot
472 472
    ///feature.
473 473
    void contract(Node a, Node b, bool r = true)
474 474
    {
475 475
      for(OutArcIt e(*this,b);e!=INVALID;) {
476 476
        OutArcIt f=e;
477 477
        ++f;
478 478
        if(r && target(e)==a) erase(e);
479 479
        else changeSource(e,a);
480 480
        e=f;
481 481
      }
482 482
      for(InArcIt e(*this,b);e!=INVALID;) {
483 483
        InArcIt f=e;
484 484
        ++f;
485 485
        if(r && source(e)==a) erase(e);
486 486
        else changeTarget(e,a);
487 487
        e=f;
488 488
      }
489 489
      erase(b);
490 490
    }
491 491

	
492 492
    ///Split a node.
493 493

	
494 494
    ///This function splits a node. First a new node is added to the digraph,
495 495
    ///then the source of each outgoing arc of \c n is moved to this new node.
496 496
    ///If \c connect is \c true (this is the default value), then a new arc
497 497
    ///from \c n to the newly created node is also added.
498 498
    ///\return The newly created node.
499 499
    ///
500 500
    ///\note The <tt>ArcIt</tt>s referencing a moved arc remain
501 501
    ///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s may
502 502
    ///be invalidated.
503 503
    ///
504 504
    ///\warning This functionality cannot be used in conjunction with the
505 505
    ///Snapshot feature.
506 506
    Node split(Node n, bool connect = true) {
507 507
      Node b = addNode();
508 508
      for(OutArcIt e(*this,n);e!=INVALID;) {
509 509
        OutArcIt f=e;
510 510
        ++f;
511 511
        changeSource(e,b);
512 512
        e=f;
513 513
      }
514 514
      if (connect) addArc(n,b);
515 515
      return b;
516 516
    }
517 517

	
518 518
    ///Split an arc.
519 519

	
520 520
    ///This function splits an arc. First a new node \c b is added to
521 521
    ///the digraph, then the original arc is re-targeted to \c
522 522
    ///b. Finally an arc from \c b to the original target is added.
523 523
    ///
524 524
    ///\return The newly created node.
525 525
    ///
526 526
    ///\warning This functionality cannot be used together with the
527 527
    ///Snapshot feature.
528 528
    Node split(Arc e) {
529 529
      Node b = addNode();
530 530
      addArc(b,target(e));
531 531
      changeTarget(e,b);
532 532
      return b;
533 533
    }
534 534

	
535 535
    /// \brief Class to make a snapshot of the digraph and restore
536 536
    /// it later.
537 537
    ///
538 538
    /// Class to make a snapshot of the digraph and restore it later.
539 539
    ///
540 540
    /// The newly added nodes and arcs can be removed using the
541 541
    /// restore() function.
542 542
    ///
543 543
    /// \warning Arc and node deletions and other modifications (e.g.
544 544
    /// contracting, splitting, reversing arcs or nodes) cannot be
545 545
    /// restored. These events invalidate the snapshot.
546 546
    class Snapshot {
547 547
    protected:
548 548

	
549 549
      typedef Parent::NodeNotifier NodeNotifier;
550 550

	
551 551
      class NodeObserverProxy : public NodeNotifier::ObserverBase {
552 552
      public:
553 553

	
554 554
        NodeObserverProxy(Snapshot& _snapshot)
555 555
          : snapshot(_snapshot) {}
556 556

	
557 557
        using NodeNotifier::ObserverBase::attach;
558 558
        using NodeNotifier::ObserverBase::detach;
559 559
        using NodeNotifier::ObserverBase::attached;
560 560

	
561 561
      protected:
562 562

	
563 563
        virtual void add(const Node& node) {
564 564
          snapshot.addNode(node);
565 565
        }
566 566
        virtual void add(const std::vector<Node>& nodes) {
567 567
          for (int i = nodes.size() - 1; i >= 0; ++i) {
568 568
            snapshot.addNode(nodes[i]);
569 569
          }
570 570
        }
571 571
        virtual void erase(const Node& node) {
572 572
          snapshot.eraseNode(node);
573 573
        }
574 574
        virtual void erase(const std::vector<Node>& nodes) {
575 575
          for (int i = 0; i < int(nodes.size()); ++i) {
576 576
            snapshot.eraseNode(nodes[i]);
577 577
          }
578 578
        }
579 579
        virtual void build() {
580 580
          Node node;
581 581
          std::vector<Node> nodes;
582 582
          for (notifier()->first(node); node != INVALID;
583 583
               notifier()->next(node)) {
584 584
            nodes.push_back(node);
585 585
          }
586 586
          for (int i = nodes.size() - 1; i >= 0; --i) {
587 587
            snapshot.addNode(nodes[i]);
588 588
          }
589 589
        }
590 590
        virtual void clear() {
591 591
          Node node;
592 592
          for (notifier()->first(node); node != INVALID;
593 593
               notifier()->next(node)) {
594 594
            snapshot.eraseNode(node);
595 595
          }
596 596
        }
597 597

	
598 598
        Snapshot& snapshot;
599 599
      };
600 600

	
601 601
      class ArcObserverProxy : public ArcNotifier::ObserverBase {
602 602
      public:
603 603

	
604 604
        ArcObserverProxy(Snapshot& _snapshot)
605 605
          : snapshot(_snapshot) {}
606 606

	
607 607
        using ArcNotifier::ObserverBase::attach;
608 608
        using ArcNotifier::ObserverBase::detach;
609 609
        using ArcNotifier::ObserverBase::attached;
610 610

	
611 611
      protected:
612 612

	
613 613
        virtual void add(const Arc& arc) {
614 614
          snapshot.addArc(arc);
615 615
        }
616 616
        virtual void add(const std::vector<Arc>& arcs) {
617 617
          for (int i = arcs.size() - 1; i >= 0; ++i) {
618 618
            snapshot.addArc(arcs[i]);
619 619
          }
620 620
        }
621 621
        virtual void erase(const Arc& arc) {
622 622
          snapshot.eraseArc(arc);
623 623
        }
624 624
        virtual void erase(const std::vector<Arc>& arcs) {
625 625
          for (int i = 0; i < int(arcs.size()); ++i) {
626 626
            snapshot.eraseArc(arcs[i]);
627 627
          }
628 628
        }
629 629
        virtual void build() {
630 630
          Arc arc;
631 631
          std::vector<Arc> arcs;
632 632
          for (notifier()->first(arc); arc != INVALID;
633 633
               notifier()->next(arc)) {
634 634
            arcs.push_back(arc);
635 635
          }
636 636
          for (int i = arcs.size() - 1; i >= 0; --i) {
637 637
            snapshot.addArc(arcs[i]);
638 638
          }
639 639
        }
640 640
        virtual void clear() {
641 641
          Arc arc;
642 642
          for (notifier()->first(arc); arc != INVALID;
643 643
               notifier()->next(arc)) {
644 644
            snapshot.eraseArc(arc);
645 645
          }
646 646
        }
647 647

	
648 648
        Snapshot& snapshot;
649 649
      };
650 650

	
651 651
      ListDigraph *digraph;
652 652

	
653 653
      NodeObserverProxy node_observer_proxy;
654 654
      ArcObserverProxy arc_observer_proxy;
655 655

	
656 656
      std::list<Node> added_nodes;
657 657
      std::list<Arc> added_arcs;
658 658

	
659 659

	
660 660
      void addNode(const Node& node) {
661 661
        added_nodes.push_front(node);
662 662
      }
663 663
      void eraseNode(const Node& node) {
664 664
        std::list<Node>::iterator it =
665 665
          std::find(added_nodes.begin(), added_nodes.end(), node);
666 666
        if (it == added_nodes.end()) {
667 667
          clear();
668 668
          arc_observer_proxy.detach();
669 669
          throw NodeNotifier::ImmediateDetach();
670 670
        } else {
671 671
          added_nodes.erase(it);
672 672
        }
673 673
      }
674 674

	
675 675
      void addArc(const Arc& arc) {
676 676
        added_arcs.push_front(arc);
677 677
      }
678 678
      void eraseArc(const Arc& arc) {
679 679
        std::list<Arc>::iterator it =
680 680
          std::find(added_arcs.begin(), added_arcs.end(), arc);
681 681
        if (it == added_arcs.end()) {
682 682
          clear();
683 683
          node_observer_proxy.detach();
684 684
          throw ArcNotifier::ImmediateDetach();
685 685
        } else {
686 686
          added_arcs.erase(it);
687 687
        }
688 688
      }
689 689

	
690 690
      void attach(ListDigraph &_digraph) {
691 691
        digraph = &_digraph;
692 692
        node_observer_proxy.attach(digraph->notifier(Node()));
693 693
        arc_observer_proxy.attach(digraph->notifier(Arc()));
694 694
      }
695 695

	
696 696
      void detach() {
697 697
        node_observer_proxy.detach();
698 698
        arc_observer_proxy.detach();
699 699
      }
700 700

	
701 701
      bool attached() const {
702 702
        return node_observer_proxy.attached();
703 703
      }
704 704

	
705 705
      void clear() {
706 706
        added_nodes.clear();
707 707
        added_arcs.clear();
708 708
      }
709 709

	
710 710
    public:
711 711

	
712 712
      /// \brief Default constructor.
713 713
      ///
714 714
      /// Default constructor.
715 715
      /// To actually make a snapshot you must call save().
716 716
      Snapshot()
717 717
        : digraph(0), node_observer_proxy(*this),
718 718
          arc_observer_proxy(*this) {}
719 719

	
720 720
      /// \brief Constructor that immediately makes a snapshot.
721 721
      ///
722 722
      /// This constructor immediately makes a snapshot of the digraph.
723 723
      /// \param _digraph The digraph we make a snapshot of.
724 724
      Snapshot(ListDigraph &_digraph)
725 725
        : node_observer_proxy(*this),
726 726
          arc_observer_proxy(*this) {
727 727
        attach(_digraph);
728 728
      }
729 729

	
730 730
      /// \brief Make a snapshot.
731 731
      ///
732 732
      /// Make a snapshot of the digraph.
733 733
      ///
734 734
      /// This function can be called more than once. In case of a repeated
735 735
      /// call, the previous snapshot gets lost.
736 736
      /// \param _digraph The digraph we make the snapshot of.
737 737
      void save(ListDigraph &_digraph) {
738 738
        if (attached()) {
739 739
          detach();
740 740
          clear();
741 741
        }
742 742
        attach(_digraph);
743 743
      }
744 744

	
745 745
      /// \brief Undo the changes until the last snapshot.
746 746
      //
747 747
      /// Undo the changes until the last snapshot created by save().
748 748
      void restore() {
749 749
        detach();
750 750
        for(std::list<Arc>::iterator it = added_arcs.begin();
751 751
            it != added_arcs.end(); ++it) {
752 752
          digraph->erase(*it);
753 753
        }
754 754
        for(std::list<Node>::iterator it = added_nodes.begin();
755 755
            it != added_nodes.end(); ++it) {
756 756
          digraph->erase(*it);
757 757
        }
758 758
        clear();
759 759
      }
760 760

	
761 761
      /// \brief Gives back true when the snapshot is valid.
762 762
      ///
763 763
      /// Gives back true when the snapshot is valid.
764 764
      bool valid() const {
765 765
        return attached();
766 766
      }
767 767
    };
768 768

	
769 769
  };
770 770

	
771 771
  ///@}
772 772

	
773 773
  class ListGraphBase {
774 774

	
775 775
  protected:
776 776

	
777 777
    struct NodeT {
778 778
      int first_out;
779 779
      int prev, next;
780 780
    };
781 781

	
782 782
    struct ArcT {
783 783
      int target;
784 784
      int prev_out, next_out;
785 785
    };
786 786

	
787 787
    std::vector<NodeT> nodes;
788 788

	
789 789
    int first_node;
790 790

	
791 791
    int first_free_node;
792 792

	
793 793
    std::vector<ArcT> arcs;
794 794

	
795 795
    int first_free_arc;
796 796

	
797 797
  public:
798 798

	
799 799
    typedef ListGraphBase Digraph;
800 800

	
801 801
    class Node;
802 802
    class Arc;
803 803
    class Edge;
804 804

	
805 805
    class Node {
806 806
      friend class ListGraphBase;
807 807
    protected:
808 808

	
809 809
      int id;
810 810
      explicit Node(int pid) { id = pid;}
811 811

	
812 812
    public:
813 813
      Node() {}
814 814
      Node (Invalid) { id = -1; }
815 815
      bool operator==(const Node& node) const {return id == node.id;}
816 816
      bool operator!=(const Node& node) const {return id != node.id;}
817 817
      bool operator<(const Node& node) const {return id < node.id;}
818 818
    };
819 819

	
820 820
    class Edge {
821 821
      friend class ListGraphBase;
822 822
    protected:
823 823

	
824 824
      int id;
825 825
      explicit Edge(int pid) { id = pid;}
826 826

	
827 827
    public:
828 828
      Edge() {}
829 829
      Edge (Invalid) { id = -1; }
830 830
      bool operator==(const Edge& edge) const {return id == edge.id;}
831 831
      bool operator!=(const Edge& edge) const {return id != edge.id;}
832 832
      bool operator<(const Edge& edge) const {return id < edge.id;}
833 833
    };
834 834

	
835 835
    class Arc {
836 836
      friend class ListGraphBase;
837 837
    protected:
838 838

	
839 839
      int id;
840 840
      explicit Arc(int pid) { id = pid;}
841 841

	
842 842
    public:
843
      operator Edge() const { 
844
        return id != -1 ? edgeFromId(id / 2) : INVALID; 
843
      operator Edge() const {
844
        return id != -1 ? edgeFromId(id / 2) : INVALID;
845 845
      }
846 846

	
847 847
      Arc() {}
848 848
      Arc (Invalid) { id = -1; }
849 849
      bool operator==(const Arc& arc) const {return id == arc.id;}
850 850
      bool operator!=(const Arc& arc) const {return id != arc.id;}
851 851
      bool operator<(const Arc& arc) const {return id < arc.id;}
852 852
    };
853 853

	
854 854

	
855 855

	
856 856
    ListGraphBase()
857 857
      : nodes(), first_node(-1),
858 858
        first_free_node(-1), arcs(), first_free_arc(-1) {}
859 859

	
860 860

	
861 861
    int maxNodeId() const { return nodes.size()-1; }
862 862
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
863 863
    int maxArcId() const { return arcs.size()-1; }
864 864

	
865 865
    Node source(Arc e) const { return Node(arcs[e.id ^ 1].target); }
866 866
    Node target(Arc e) const { return Node(arcs[e.id].target); }
867 867

	
868 868
    Node u(Edge e) const { return Node(arcs[2 * e.id].target); }
869 869
    Node v(Edge e) const { return Node(arcs[2 * e.id + 1].target); }
870 870

	
871 871
    static bool direction(Arc e) {
872 872
      return (e.id & 1) == 1;
873 873
    }
874 874

	
875 875
    static Arc direct(Edge e, bool d) {
876 876
      return Arc(e.id * 2 + (d ? 1 : 0));
877 877
    }
878 878

	
879 879
    void first(Node& node) const {
880 880
      node.id = first_node;
881 881
    }
882 882

	
883 883
    void next(Node& node) const {
884 884
      node.id = nodes[node.id].next;
885 885
    }
886 886

	
887 887
    void first(Arc& e) const {
888 888
      int n = first_node;
889 889
      while (n != -1 && nodes[n].first_out == -1) {
890 890
        n = nodes[n].next;
891 891
      }
892 892
      e.id = (n == -1) ? -1 : nodes[n].first_out;
893 893
    }
894 894

	
895 895
    void next(Arc& e) const {
896 896
      if (arcs[e.id].next_out != -1) {
897 897
        e.id = arcs[e.id].next_out;
898 898
      } else {
899 899
        int n = nodes[arcs[e.id ^ 1].target].next;
900 900
        while(n != -1 && nodes[n].first_out == -1) {
901 901
          n = nodes[n].next;
902 902
        }
903 903
        e.id = (n == -1) ? -1 : nodes[n].first_out;
904 904
      }
905 905
    }
906 906

	
907 907
    void first(Edge& e) const {
908 908
      int n = first_node;
909 909
      while (n != -1) {
910 910
        e.id = nodes[n].first_out;
911 911
        while ((e.id & 1) != 1) {
912 912
          e.id = arcs[e.id].next_out;
913 913
        }
914 914
        if (e.id != -1) {
915 915
          e.id /= 2;
916 916
          return;
917 917
        }
918 918
        n = nodes[n].next;
919 919
      }
920 920
      e.id = -1;
921 921
    }
922 922

	
923 923
    void next(Edge& e) const {
924 924
      int n = arcs[e.id * 2].target;
925 925
      e.id = arcs[(e.id * 2) | 1].next_out;
926 926
      while ((e.id & 1) != 1) {
927 927
        e.id = arcs[e.id].next_out;
928 928
      }
929 929
      if (e.id != -1) {
930 930
        e.id /= 2;
931 931
        return;
932 932
      }
933 933
      n = nodes[n].next;
934 934
      while (n != -1) {
935 935
        e.id = nodes[n].first_out;
936 936
        while ((e.id & 1) != 1) {
937 937
          e.id = arcs[e.id].next_out;
938 938
        }
939 939
        if (e.id != -1) {
940 940
          e.id /= 2;
941 941
          return;
942 942
        }
943 943
        n = nodes[n].next;
944 944
      }
945 945
      e.id = -1;
946 946
    }
947 947

	
948 948
    void firstOut(Arc &e, const Node& v) const {
949 949
      e.id = nodes[v.id].first_out;
950 950
    }
951 951
    void nextOut(Arc &e) const {
952 952
      e.id = arcs[e.id].next_out;
953 953
    }
954 954

	
955 955
    void firstIn(Arc &e, const Node& v) const {
956 956
      e.id = ((nodes[v.id].first_out) ^ 1);
957 957
      if (e.id == -2) e.id = -1;
958 958
    }
959 959
    void nextIn(Arc &e) const {
960 960
      e.id = ((arcs[e.id ^ 1].next_out) ^ 1);
961 961
      if (e.id == -2) e.id = -1;
962 962
    }
963 963

	
964 964
    void firstInc(Edge &e, bool& d, const Node& v) const {
965 965
      int a = nodes[v.id].first_out;
966 966
      if (a != -1 ) {
967 967
        e.id = a / 2;
968 968
        d = ((a & 1) == 1);
969 969
      } else {
970 970
        e.id = -1;
971 971
        d = true;
972 972
      }
973 973
    }
974 974
    void nextInc(Edge &e, bool& d) const {
975 975
      int a = (arcs[(e.id * 2) | (d ? 1 : 0)].next_out);
976 976
      if (a != -1 ) {
977 977
        e.id = a / 2;
978 978
        d = ((a & 1) == 1);
979 979
      } else {
980 980
        e.id = -1;
981 981
        d = true;
982 982
      }
983 983
    }
984 984

	
985 985
    static int id(Node v) { return v.id; }
986 986
    static int id(Arc e) { return e.id; }
987 987
    static int id(Edge e) { return e.id; }
988 988

	
989 989
    static Node nodeFromId(int id) { return Node(id);}
990 990
    static Arc arcFromId(int id) { return Arc(id);}
991 991
    static Edge edgeFromId(int id) { return Edge(id);}
992 992

	
993 993
    bool valid(Node n) const {
994 994
      return n.id >= 0 && n.id < static_cast<int>(nodes.size()) &&
995 995
        nodes[n.id].prev != -2;
996 996
    }
997 997

	
998 998
    bool valid(Arc a) const {
999 999
      return a.id >= 0 && a.id < static_cast<int>(arcs.size()) &&
1000 1000
        arcs[a.id].prev_out != -2;
1001 1001
    }
1002 1002

	
1003 1003
    bool valid(Edge e) const {
1004 1004
      return e.id >= 0 && 2 * e.id < static_cast<int>(arcs.size()) &&
1005 1005
        arcs[2 * e.id].prev_out != -2;
1006 1006
    }
1007 1007

	
1008 1008
    Node addNode() {
1009 1009
      int n;
1010 1010

	
1011 1011
      if(first_free_node==-1) {
1012 1012
        n = nodes.size();
1013 1013
        nodes.push_back(NodeT());
1014 1014
      } else {
1015 1015
        n = first_free_node;
1016 1016
        first_free_node = nodes[n].next;
1017 1017
      }
1018 1018

	
1019 1019
      nodes[n].next = first_node;
1020 1020
      if (first_node != -1) nodes[first_node].prev = n;
1021 1021
      first_node = n;
1022 1022
      nodes[n].prev = -1;
1023 1023

	
1024 1024
      nodes[n].first_out = -1;
1025 1025

	
1026 1026
      return Node(n);
1027 1027
    }
1028 1028

	
1029 1029
    Edge addEdge(Node u, Node v) {
1030 1030
      int n;
1031 1031

	
1032 1032
      if (first_free_arc == -1) {
1033 1033
        n = arcs.size();
1034 1034
        arcs.push_back(ArcT());
1035 1035
        arcs.push_back(ArcT());
1036 1036
      } else {
1037 1037
        n = first_free_arc;
1038 1038
        first_free_arc = arcs[n].next_out;
1039 1039
      }
1040 1040

	
1041 1041
      arcs[n].target = u.id;
1042 1042
      arcs[n | 1].target = v.id;
1043 1043

	
1044 1044
      arcs[n].next_out = nodes[v.id].first_out;
1045 1045
      if (nodes[v.id].first_out != -1) {
1046 1046
        arcs[nodes[v.id].first_out].prev_out = n;
1047 1047
      }
1048 1048
      arcs[n].prev_out = -1;
1049 1049
      nodes[v.id].first_out = n;
1050 1050

	
1051 1051
      arcs[n | 1].next_out = nodes[u.id].first_out;
1052 1052
      if (nodes[u.id].first_out != -1) {
1053 1053
        arcs[nodes[u.id].first_out].prev_out = (n | 1);
1054 1054
      }
1055 1055
      arcs[n | 1].prev_out = -1;
1056 1056
      nodes[u.id].first_out = (n | 1);
1057 1057

	
1058 1058
      return Edge(n / 2);
1059 1059
    }
1060 1060

	
1061 1061
    void erase(const Node& node) {
1062 1062
      int n = node.id;
1063 1063

	
1064 1064
      if(nodes[n].next != -1) {
1065 1065
        nodes[nodes[n].next].prev = nodes[n].prev;
1066 1066
      }
1067 1067

	
1068 1068
      if(nodes[n].prev != -1) {
1069 1069
        nodes[nodes[n].prev].next = nodes[n].next;
1070 1070
      } else {
1071 1071
        first_node = nodes[n].next;
1072 1072
      }
1073 1073

	
1074 1074
      nodes[n].next = first_free_node;
1075 1075
      first_free_node = n;
1076 1076
      nodes[n].prev = -2;
1077 1077
    }
1078 1078

	
1079 1079
    void erase(const Edge& edge) {
1080 1080
      int n = edge.id * 2;
1081 1081

	
1082 1082
      if (arcs[n].next_out != -1) {
1083 1083
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
1084 1084
      }
1085 1085

	
1086 1086
      if (arcs[n].prev_out != -1) {
1087 1087
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
1088 1088
      } else {
1089 1089
        nodes[arcs[n | 1].target].first_out = arcs[n].next_out;
1090 1090
      }
1091 1091

	
1092 1092
      if (arcs[n | 1].next_out != -1) {
1093 1093
        arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out;
1094 1094
      }
1095 1095

	
1096 1096
      if (arcs[n | 1].prev_out != -1) {
1097 1097
        arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out;
1098 1098
      } else {
1099 1099
        nodes[arcs[n].target].first_out = arcs[n | 1].next_out;
1100 1100
      }
1101 1101

	
1102 1102
      arcs[n].next_out = first_free_arc;
1103 1103
      first_free_arc = n;
1104 1104
      arcs[n].prev_out = -2;
1105 1105
      arcs[n | 1].prev_out = -2;
1106 1106

	
1107 1107
    }
1108 1108

	
1109 1109
    void clear() {
1110 1110
      arcs.clear();
1111 1111
      nodes.clear();
1112 1112
      first_node = first_free_node = first_free_arc = -1;
1113 1113
    }
1114 1114

	
1115 1115
  protected:
1116 1116

	
1117 1117
    void changeV(Edge e, Node n) {
1118 1118
      if(arcs[2 * e.id].next_out != -1) {
1119 1119
        arcs[arcs[2 * e.id].next_out].prev_out = arcs[2 * e.id].prev_out;
1120 1120
      }
1121 1121
      if(arcs[2 * e.id].prev_out != -1) {
1122 1122
        arcs[arcs[2 * e.id].prev_out].next_out =
1123 1123
          arcs[2 * e.id].next_out;
1124 1124
      } else {
1125 1125
        nodes[arcs[(2 * e.id) | 1].target].first_out =
1126 1126
          arcs[2 * e.id].next_out;
1127 1127
      }
1128 1128

	
1129 1129
      if (nodes[n.id].first_out != -1) {
1130 1130
        arcs[nodes[n.id].first_out].prev_out = 2 * e.id;
1131 1131
      }
1132 1132
      arcs[(2 * e.id) | 1].target = n.id;
1133 1133
      arcs[2 * e.id].prev_out = -1;
1134 1134
      arcs[2 * e.id].next_out = nodes[n.id].first_out;
1135 1135
      nodes[n.id].first_out = 2 * e.id;
1136 1136
    }
1137 1137

	
1138 1138
    void changeU(Edge e, Node n) {
1139 1139
      if(arcs[(2 * e.id) | 1].next_out != -1) {
1140 1140
        arcs[arcs[(2 * e.id) | 1].next_out].prev_out =
1141 1141
          arcs[(2 * e.id) | 1].prev_out;
1142 1142
      }
1143 1143
      if(arcs[(2 * e.id) | 1].prev_out != -1) {
1144 1144
        arcs[arcs[(2 * e.id) | 1].prev_out].next_out =
1145 1145
          arcs[(2 * e.id) | 1].next_out;
1146 1146
      } else {
1147 1147
        nodes[arcs[2 * e.id].target].first_out =
1148 1148
          arcs[(2 * e.id) | 1].next_out;
1149 1149
      }
1150 1150

	
1151 1151
      if (nodes[n.id].first_out != -1) {
1152 1152
        arcs[nodes[n.id].first_out].prev_out = ((2 * e.id) | 1);
1153 1153
      }
1154 1154
      arcs[2 * e.id].target = n.id;
1155 1155
      arcs[(2 * e.id) | 1].prev_out = -1;
1156 1156
      arcs[(2 * e.id) | 1].next_out = nodes[n.id].first_out;
1157 1157
      nodes[n.id].first_out = ((2 * e.id) | 1);
1158 1158
    }
1159 1159

	
1160 1160
  };
1161 1161

	
1162 1162
  typedef GraphExtender<ListGraphBase> ExtendedListGraphBase;
1163 1163

	
1164 1164

	
1165 1165
  /// \addtogroup graphs
1166 1166
  /// @{
1167 1167

	
1168 1168
  ///A general undirected graph structure.
1169 1169

	
1170 1170
  ///\ref ListGraph is a simple and fast <em>undirected graph</em>
1171 1171
  ///implementation based on static linked lists that are stored in
1172 1172
  ///\c std::vector structures.
1173 1173
  ///
1174 1174
  ///It conforms to the \ref concepts::Graph "Graph concept" and it
1175 1175
  ///also provides several useful additional functionalities.
1176 1176
  ///Most of the member functions and nested classes are documented
1177 1177
  ///only in the concept class.
1178 1178
  ///
1179 1179
  ///An important extra feature of this graph implementation is that
1180 1180
  ///its maps are real \ref concepts::ReferenceMap "reference map"s.
1181 1181
  ///
1182 1182
  ///\sa concepts::Graph
1183 1183

	
1184 1184
  class ListGraph : public ExtendedListGraphBase {
1185 1185
  private:
1186 1186
    ///ListGraph is \e not copy constructible. Use copyGraph() instead.
1187 1187

	
1188 1188
    ///ListGraph is \e not copy constructible. Use copyGraph() instead.
1189 1189
    ///
1190 1190
    ListGraph(const ListGraph &) :ExtendedListGraphBase()  {};
1191 1191
    ///\brief Assignment of ListGraph to another one is \e not allowed.
1192 1192
    ///Use copyGraph() instead.
1193 1193

	
1194 1194
    ///Assignment of ListGraph to another one is \e not allowed.
1195 1195
    ///Use copyGraph() instead.
1196 1196
    void operator=(const ListGraph &) {}
1197 1197
  public:
1198 1198
    /// Constructor
1199 1199

	
1200 1200
    /// Constructor.
1201 1201
    ///
1202 1202
    ListGraph() {}
1203 1203

	
1204 1204
    typedef ExtendedListGraphBase Parent;
1205 1205

	
1206 1206
    typedef Parent::OutArcIt IncEdgeIt;
1207 1207

	
1208 1208
    /// \brief Add a new node to the graph.
1209 1209
    ///
1210 1210
    /// Add a new node to the graph.
1211 1211
    /// \return the new node.
1212 1212
    Node addNode() { return Parent::addNode(); }
1213 1213

	
1214 1214
    /// \brief Add a new edge to the graph.
1215 1215
    ///
1216 1216
    /// Add a new edge to the graph with source node \c s
1217 1217
    /// and target node \c t.
1218 1218
    /// \return the new edge.
1219 1219
    Edge addEdge(const Node& s, const Node& t) {
1220 1220
      return Parent::addEdge(s, t);
1221 1221
    }
1222 1222

	
1223 1223
    /// \brief Erase a node from the graph.
1224 1224
    ///
1225 1225
    /// Erase a node from the graph.
1226 1226
    ///
1227 1227
    void erase(const Node& n) { Parent::erase(n); }
1228 1228

	
1229 1229
    /// \brief Erase an edge from the graph.
1230 1230
    ///
1231 1231
    /// Erase an edge from the graph.
1232 1232
    ///
1233 1233
    void erase(const Edge& e) { Parent::erase(e); }
1234 1234
    /// Node validity check
1235 1235

	
1236 1236
    /// This function gives back true if the given node is valid,
1237 1237
    /// ie. it is a real node of the graph.
1238 1238
    ///
1239 1239
    /// \warning A Node pointing to a removed item
1240 1240
    /// could become valid again later if new nodes are
1241 1241
    /// added to the graph.
1242 1242
    bool valid(Node n) const { return Parent::valid(n); }
1243 1243
    /// Arc validity check
1244 1244

	
1245 1245
    /// This function gives back true if the given arc is valid,
1246 1246
    /// ie. it is a real arc of the graph.
1247 1247
    ///
1248 1248
    /// \warning An Arc pointing to a removed item
1249 1249
    /// could become valid again later if new edges are
1250 1250
    /// added to the graph.
1251 1251
    bool valid(Arc a) const { return Parent::valid(a); }
1252 1252
    /// Edge validity check
1253 1253

	
1254 1254
    /// This function gives back true if the given edge is valid,
1255 1255
    /// ie. it is a real arc of the graph.
1256 1256
    ///
1257 1257
    /// \warning A Edge pointing to a removed item
1258 1258
    /// could become valid again later if new edges are
1259 1259
    /// added to the graph.
1260 1260
    bool valid(Edge e) const { return Parent::valid(e); }
1261 1261
    /// \brief Change the end \c u of \c e to \c n
1262 1262
    ///
1263 1263
    /// This function changes the end \c u of \c e to node \c n.
1264 1264
    ///
1265 1265
    ///\note The <tt>EdgeIt</tt>s and <tt>ArcIt</tt>s referencing the
1266 1266
    ///changed edge are invalidated and if the changed node is the
1267 1267
    ///base node of an iterator then this iterator is also
1268 1268
    ///invalidated.
1269 1269
    ///
1270 1270
    ///\warning This functionality cannot be used together with the
1271 1271
    ///Snapshot feature.
1272 1272
    void changeU(Edge e, Node n) {
1273 1273
      Parent::changeU(e,n);
1274 1274
    }
1275 1275
    /// \brief Change the end \c v of \c e to \c n
1276 1276
    ///
1277 1277
    /// This function changes the end \c v of \c e to \c n.
1278 1278
    ///
1279 1279
    ///\note The <tt>EdgeIt</tt>s referencing the changed edge remain
1280 1280
    ///valid, however <tt>ArcIt</tt>s and if the changed node is the
1281 1281
    ///base node of an iterator then this iterator is invalidated.
1282 1282
    ///
1283 1283
    ///\warning This functionality cannot be used together with the
1284 1284
    ///Snapshot feature.
1285 1285
    void changeV(Edge e, Node n) {
1286 1286
      Parent::changeV(e,n);
1287 1287
    }
1288 1288
    /// \brief Contract two nodes.
1289 1289
    ///
1290 1290
    /// This function contracts two nodes.
1291 1291
    /// Node \p b will be removed but instead of deleting
1292 1292
    /// its neighboring arcs, they will be joined to \p a.
1293 1293
    /// The last parameter \p r controls whether to remove loops. \c true
1294 1294
    /// means that loops will be removed.
1295 1295
    ///
1296 1296
    /// \note The <tt>ArcIt</tt>s referencing a moved arc remain
1297 1297
    /// valid.
1298 1298
    ///
1299 1299
    ///\warning This functionality cannot be used together with the
1300 1300
    ///Snapshot feature.
1301 1301
    void contract(Node a, Node b, bool r = true) {
1302 1302
      for(IncEdgeIt e(*this, b); e!=INVALID;) {
1303 1303
        IncEdgeIt f = e; ++f;
1304 1304
        if (r && runningNode(e) == a) {
1305 1305
          erase(e);
1306 1306
        } else if (u(e) == b) {
1307 1307
          changeU(e, a);
1308 1308
        } else {
1309 1309
          changeV(e, a);
1310 1310
        }
1311 1311
        e = f;
1312 1312
      }
1313 1313
      erase(b);
1314 1314
    }
1315 1315

	
1316 1316

	
1317 1317
    /// \brief Class to make a snapshot of the graph and restore
1318 1318
    /// it later.
1319 1319
    ///
1320 1320
    /// Class to make a snapshot of the graph and restore it later.
1321 1321
    ///
1322 1322
    /// The newly added nodes and edges can be removed
1323 1323
    /// using the restore() function.
1324 1324
    ///
1325 1325
    /// \warning Edge and node deletions and other modifications
1326 1326
    /// (e.g. changing nodes of edges, contracting nodes) cannot be
1327 1327
    /// restored. These events invalidate the snapshot.
1328 1328
    class Snapshot {
1329 1329
    protected:
1330 1330

	
1331 1331
      typedef Parent::NodeNotifier NodeNotifier;
1332 1332

	
1333 1333
      class NodeObserverProxy : public NodeNotifier::ObserverBase {
1334 1334
      public:
1335 1335

	
1336 1336
        NodeObserverProxy(Snapshot& _snapshot)
1337 1337
          : snapshot(_snapshot) {}
1338 1338

	
1339 1339
        using NodeNotifier::ObserverBase::attach;
1340 1340
        using NodeNotifier::ObserverBase::detach;
1341 1341
        using NodeNotifier::ObserverBase::attached;
1342 1342

	
1343 1343
      protected:
1344 1344

	
1345 1345
        virtual void add(const Node& node) {
1346 1346
          snapshot.addNode(node);
1347 1347
        }
1348 1348
        virtual void add(const std::vector<Node>& nodes) {
1349 1349
          for (int i = nodes.size() - 1; i >= 0; ++i) {
1350 1350
            snapshot.addNode(nodes[i]);
1351 1351
          }
1352 1352
        }
1353 1353
        virtual void erase(const Node& node) {
1354 1354
          snapshot.eraseNode(node);
1355 1355
        }
1356 1356
        virtual void erase(const std::vector<Node>& nodes) {
1357 1357
          for (int i = 0; i < int(nodes.size()); ++i) {
1358 1358
            snapshot.eraseNode(nodes[i]);
1359 1359
          }
1360 1360
        }
1361 1361
        virtual void build() {
1362 1362
          Node node;
1363 1363
          std::vector<Node> nodes;
1364 1364
          for (notifier()->first(node); node != INVALID;
1365 1365
               notifier()->next(node)) {
1366 1366
            nodes.push_back(node);
1367 1367
          }
1368 1368
          for (int i = nodes.size() - 1; i >= 0; --i) {
1369 1369
            snapshot.addNode(nodes[i]);
1370 1370
          }
1371 1371
        }
1372 1372
        virtual void clear() {
1373 1373
          Node node;
1374 1374
          for (notifier()->first(node); node != INVALID;
1375 1375
               notifier()->next(node)) {
1376 1376
            snapshot.eraseNode(node);
1377 1377
          }
1378 1378
        }
1379 1379

	
1380 1380
        Snapshot& snapshot;
1381 1381
      };
1382 1382

	
1383 1383
      class EdgeObserverProxy : public EdgeNotifier::ObserverBase {
1384 1384
      public:
1385 1385

	
1386 1386
        EdgeObserverProxy(Snapshot& _snapshot)
1387 1387
          : snapshot(_snapshot) {}
1388 1388

	
1389 1389
        using EdgeNotifier::ObserverBase::attach;
1390 1390
        using EdgeNotifier::ObserverBase::detach;
1391 1391
        using EdgeNotifier::ObserverBase::attached;
1392 1392

	
1393 1393
      protected:
1394 1394

	
1395 1395
        virtual void add(const Edge& edge) {
1396 1396
          snapshot.addEdge(edge);
1397 1397
        }
1398 1398
        virtual void add(const std::vector<Edge>& edges) {
1399 1399
          for (int i = edges.size() - 1; i >= 0; ++i) {
1400 1400
            snapshot.addEdge(edges[i]);
1401 1401
          }
1402 1402
        }
1403 1403
        virtual void erase(const Edge& edge) {
1404 1404
          snapshot.eraseEdge(edge);
1405 1405
        }
1406 1406
        virtual void erase(const std::vector<Edge>& edges) {
1407 1407
          for (int i = 0; i < int(edges.size()); ++i) {
1408 1408
            snapshot.eraseEdge(edges[i]);
1409 1409
          }
1410 1410
        }
1411 1411
        virtual void build() {
1412 1412
          Edge edge;
1413 1413
          std::vector<Edge> edges;
1414 1414
          for (notifier()->first(edge); edge != INVALID;
1415 1415
               notifier()->next(edge)) {
1416 1416
            edges.push_back(edge);
1417 1417
          }
1418 1418
          for (int i = edges.size() - 1; i >= 0; --i) {
1419 1419
            snapshot.addEdge(edges[i]);
1420 1420
          }
1421 1421
        }
1422 1422
        virtual void clear() {
1423 1423
          Edge edge;
1424 1424
          for (notifier()->first(edge); edge != INVALID;
1425 1425
               notifier()->next(edge)) {
1426 1426
            snapshot.eraseEdge(edge);
1427 1427
          }
1428 1428
        }
1429 1429

	
1430 1430
        Snapshot& snapshot;
1431 1431
      };
1432 1432

	
1433 1433
      ListGraph *graph;
1434 1434

	
1435 1435
      NodeObserverProxy node_observer_proxy;
1436 1436
      EdgeObserverProxy edge_observer_proxy;
1437 1437

	
1438 1438
      std::list<Node> added_nodes;
1439 1439
      std::list<Edge> added_edges;
1440 1440

	
1441 1441

	
1442 1442
      void addNode(const Node& node) {
1443 1443
        added_nodes.push_front(node);
1444 1444
      }
1445 1445
      void eraseNode(const Node& node) {
1446 1446
        std::list<Node>::iterator it =
1447 1447
          std::find(added_nodes.begin(), added_nodes.end(), node);
1448 1448
        if (it == added_nodes.end()) {
1449 1449
          clear();
1450 1450
          edge_observer_proxy.detach();
1451 1451
          throw NodeNotifier::ImmediateDetach();
1452 1452
        } else {
1453 1453
          added_nodes.erase(it);
1454 1454
        }
1455 1455
      }
1456 1456

	
1457 1457
      void addEdge(const Edge& edge) {
1458 1458
        added_edges.push_front(edge);
1459 1459
      }
1460 1460
      void eraseEdge(const Edge& edge) {
1461 1461
        std::list<Edge>::iterator it =
1462 1462
          std::find(added_edges.begin(), added_edges.end(), edge);
1463 1463
        if (it == added_edges.end()) {
1464 1464
          clear();
1465 1465
          node_observer_proxy.detach();
1466 1466
          throw EdgeNotifier::ImmediateDetach();
1467 1467
        } else {
1468 1468
          added_edges.erase(it);
1469 1469
        }
1470 1470
      }
1471 1471

	
1472 1472
      void attach(ListGraph &_graph) {
1473 1473
        graph = &_graph;
1474 1474
        node_observer_proxy.attach(graph->notifier(Node()));
1475 1475
        edge_observer_proxy.attach(graph->notifier(Edge()));
1476 1476
      }
1477 1477

	
1478 1478
      void detach() {
1479 1479
        node_observer_proxy.detach();
1480 1480
        edge_observer_proxy.detach();
1481 1481
      }
1482 1482

	
1483 1483
      bool attached() const {
1484 1484
        return node_observer_proxy.attached();
1485 1485
      }
1486 1486

	
1487 1487
      void clear() {
1488 1488
        added_nodes.clear();
1489 1489
        added_edges.clear();
1490 1490
      }
1491 1491

	
1492 1492
    public:
1493 1493

	
1494 1494
      /// \brief Default constructor.
1495 1495
      ///
1496 1496
      /// Default constructor.
1497 1497
      /// To actually make a snapshot you must call save().
1498 1498
      Snapshot()
1499 1499
        : graph(0), node_observer_proxy(*this),
1500 1500
          edge_observer_proxy(*this) {}
1501 1501

	
1502 1502
      /// \brief Constructor that immediately makes a snapshot.
1503 1503
      ///
1504 1504
      /// This constructor immediately makes a snapshot of the graph.
1505 1505
      /// \param _graph The graph we make a snapshot of.
1506 1506
      Snapshot(ListGraph &_graph)
1507 1507
        : node_observer_proxy(*this),
1508 1508
          edge_observer_proxy(*this) {
1509 1509
        attach(_graph);
1510 1510
      }
1511 1511

	
1512 1512
      /// \brief Make a snapshot.
1513 1513
      ///
1514 1514
      /// Make a snapshot of the graph.
1515 1515
      ///
1516 1516
      /// This function can be called more than once. In case of a repeated
1517 1517
      /// call, the previous snapshot gets lost.
1518 1518
      /// \param _graph The graph we make the snapshot of.
1519 1519
      void save(ListGraph &_graph) {
1520 1520
        if (attached()) {
1521 1521
          detach();
1522 1522
          clear();
1523 1523
        }
1524 1524
        attach(_graph);
1525 1525
      }
1526 1526

	
1527 1527
      /// \brief Undo the changes until the last snapshot.
1528 1528
      //
1529 1529
      /// Undo the changes until the last snapshot created by save().
1530 1530
      void restore() {
1531 1531
        detach();
1532 1532
        for(std::list<Edge>::iterator it = added_edges.begin();
1533 1533
            it != added_edges.end(); ++it) {
1534 1534
          graph->erase(*it);
1535 1535
        }
1536 1536
        for(std::list<Node>::iterator it = added_nodes.begin();
1537 1537
            it != added_nodes.end(); ++it) {
1538 1538
          graph->erase(*it);
1539 1539
        }
1540 1540
        clear();
1541 1541
      }
1542 1542

	
1543 1543
      /// \brief Gives back true when the snapshot is valid.
1544 1544
      ///
1545 1545
      /// Gives back true when the snapshot is valid.
1546 1546
      bool valid() const {
1547 1547
        return attached();
1548 1548
      }
1549 1549
    };
1550 1550
  };
1551 1551

	
1552 1552
  /// @}
1553 1553
} //namespace lemon
1554 1554

	
1555 1555

	
1556 1556
#endif
Ignore white space 24576 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_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
  ///Base of SmartDigraph
36 36

	
37 37
  ///Base of SmartDigraph
38 38
  ///
39 39
  class SmartDigraphBase {
40 40
  protected:
41 41

	
42 42
    struct NodeT
43 43
    {
44 44
      int first_in, first_out;
45 45
      NodeT() {}
46 46
    };
47 47
    struct ArcT
48 48
    {
49 49
      int target, source, next_in, next_out;
50 50
      ArcT() {}
51 51
    };
52 52

	
53 53
    std::vector<NodeT> nodes;
54 54
    std::vector<ArcT> arcs;
55 55

	
56 56
  public:
57 57

	
58 58
    typedef SmartDigraphBase Graph;
59 59

	
60 60
    class Node;
61 61
    class Arc;
62 62

	
63 63
  public:
64 64

	
65 65
    SmartDigraphBase() : nodes(), arcs() { }
66 66
    SmartDigraphBase(const SmartDigraphBase &_g)
67 67
      : nodes(_g.nodes), arcs(_g.arcs) { }
68 68

	
69 69
    typedef True NodeNumTag;
70 70
    typedef True EdgeNumTag;
71 71

	
72 72
    int nodeNum() const { return nodes.size(); }
73 73
    int arcNum() const { return arcs.size(); }
74 74

	
75 75
    int maxNodeId() const { return nodes.size()-1; }
76 76
    int maxArcId() const { return arcs.size()-1; }
77 77

	
78 78
    Node addNode() {
79 79
      int n = nodes.size();
80 80
      nodes.push_back(NodeT());
81 81
      nodes[n].first_in = -1;
82 82
      nodes[n].first_out = -1;
83 83
      return Node(n);
84 84
    }
85 85

	
86 86
    Arc addArc(Node u, Node v) {
87 87
      int n = arcs.size();
88 88
      arcs.push_back(ArcT());
89 89
      arcs[n].source = u._id;
90 90
      arcs[n].target = v._id;
91 91
      arcs[n].next_out = nodes[u._id].first_out;
92 92
      arcs[n].next_in = nodes[v._id].first_in;
93 93
      nodes[u._id].first_out = nodes[v._id].first_in = n;
94 94

	
95 95
      return Arc(n);
96 96
    }
97 97

	
98 98
    void clear() {
99 99
      arcs.clear();
100 100
      nodes.clear();
101 101
    }
102 102

	
103 103
    Node source(Arc a) const { return Node(arcs[a._id].source); }
104 104
    Node target(Arc a) const { return Node(arcs[a._id].target); }
105 105

	
106 106
    static int id(Node v) { return v._id; }
107 107
    static int id(Arc a) { return a._id; }
108 108

	
109 109
    static Node nodeFromId(int id) { return Node(id);}
110 110
    static Arc arcFromId(int id) { return Arc(id);}
111 111

	
112 112
    bool valid(Node n) const {
113 113
      return n._id >= 0 && n._id < static_cast<int>(nodes.size());
114 114
    }
115 115
    bool valid(Arc a) const {
116 116
      return a._id >= 0 && a._id < static_cast<int>(arcs.size());
117 117
    }
118 118

	
119 119
    class Node {
120 120
      friend class SmartDigraphBase;
121 121
      friend class SmartDigraph;
122 122

	
123 123
    protected:
124 124
      int _id;
125 125
      explicit Node(int id) : _id(id) {}
126 126
    public:
127 127
      Node() {}
128 128
      Node (Invalid) : _id(-1) {}
129 129
      bool operator==(const Node i) const {return _id == i._id;}
130 130
      bool operator!=(const Node i) const {return _id != i._id;}
131 131
      bool operator<(const Node i) const {return _id < i._id;}
132 132
    };
133 133

	
134 134

	
135 135
    class Arc {
136 136
      friend class SmartDigraphBase;
137 137
      friend class SmartDigraph;
138 138

	
139 139
    protected:
140 140
      int _id;
141 141
      explicit Arc(int id) : _id(id) {}
142 142
    public:
143 143
      Arc() { }
144 144
      Arc (Invalid) : _id(-1) {}
145 145
      bool operator==(const Arc i) const {return _id == i._id;}
146 146
      bool operator!=(const Arc i) const {return _id != i._id;}
147 147
      bool operator<(const Arc i) const {return _id < i._id;}
148 148
    };
149 149

	
150 150
    void first(Node& node) const {
151 151
      node._id = nodes.size() - 1;
152 152
    }
153 153

	
154 154
    static void next(Node& node) {
155 155
      --node._id;
156 156
    }
157 157

	
158 158
    void first(Arc& arc) const {
159 159
      arc._id = arcs.size() - 1;
160 160
    }
161 161

	
162 162
    static void next(Arc& arc) {
163 163
      --arc._id;
164 164
    }
165 165

	
166 166
    void firstOut(Arc& arc, const Node& node) const {
167 167
      arc._id = nodes[node._id].first_out;
168 168
    }
169 169

	
170 170
    void nextOut(Arc& arc) const {
171 171
      arc._id = arcs[arc._id].next_out;
172 172
    }
173 173

	
174 174
    void firstIn(Arc& arc, const Node& node) const {
175 175
      arc._id = nodes[node._id].first_in;
176 176
    }
177 177

	
178 178
    void nextIn(Arc& arc) const {
179 179
      arc._id = arcs[arc._id].next_in;
180 180
    }
181 181

	
182 182
  };
183 183

	
184 184
  typedef DigraphExtender<SmartDigraphBase> ExtendedSmartDigraphBase;
185 185

	
186 186
  ///\ingroup graphs
187 187
  ///
188 188
  ///\brief A smart directed graph class.
189 189
  ///
190 190
  ///This is a simple and fast digraph implementation.
191 191
  ///It is also quite memory efficient, but at the price
192 192
  ///that <b> it does support only limited (only stack-like)
193 193
  ///node and arc deletions</b>.
194 194
  ///It conforms to the \ref concepts::Digraph "Digraph concept" with
195 195
  ///an important extra feature that its maps are real \ref
196 196
  ///concepts::ReferenceMap "reference map"s.
197 197
  ///
198 198
  ///\sa concepts::Digraph.
199 199
  class SmartDigraph : public ExtendedSmartDigraphBase {
200 200
  public:
201 201

	
202 202
    typedef ExtendedSmartDigraphBase Parent;
203 203

	
204 204
  private:
205 205

	
206 206
    ///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead.
207 207

	
208 208
    ///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead.
209 209
    ///
210 210
    SmartDigraph(const SmartDigraph &) : ExtendedSmartDigraphBase() {};
211 211
    ///\brief Assignment of SmartDigraph to another one is \e not allowed.
212 212
    ///Use DigraphCopy() instead.
213 213

	
214 214
    ///Assignment of SmartDigraph to another one is \e not allowed.
215 215
    ///Use DigraphCopy() instead.
216 216
    void operator=(const SmartDigraph &) {}
217 217

	
218 218
  public:
219 219

	
220 220
    /// Constructor
221 221

	
222 222
    /// Constructor.
223 223
    ///
224 224
    SmartDigraph() {};
225 225

	
226 226
    ///Add a new node to the digraph.
227 227

	
228 228
    /// \return the new node.
229 229
    ///
230 230
    Node addNode() { return Parent::addNode(); }
231 231

	
232 232
    ///Add a new arc to the digraph.
233 233

	
234 234
    ///Add a new arc to the digraph with source node \c s
235 235
    ///and target node \c t.
236 236
    ///\return the new arc.
237 237
    Arc addArc(const Node& s, const Node& t) {
238 238
      return Parent::addArc(s, t);
239 239
    }
240 240

	
241 241
    /// \brief Using this it is possible to avoid the superfluous memory
242 242
    /// allocation.
243 243

	
244 244
    /// Using this it is possible to avoid the superfluous memory
245 245
    /// allocation: if you know that the digraph you want to build will
246 246
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
247 247
    /// then it is worth reserving space for this amount before starting
248 248
    /// to build the digraph.
249 249
    /// \sa reserveArc
250 250
    void reserveNode(int n) { nodes.reserve(n); };
251 251

	
252 252
    /// \brief Using this it is possible to avoid the superfluous memory
253 253
    /// allocation.
254 254

	
255 255
    /// Using this it is possible to avoid the superfluous memory
256 256
    /// allocation: if you know that the digraph you want to build will
257 257
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
258 258
    /// then it is worth reserving space for this amount before starting
259 259
    /// to build the digraph.
260 260
    /// \sa reserveNode
261 261
    void reserveArc(int m) { arcs.reserve(m); };
262 262

	
263 263
    /// \brief Node validity check
264 264
    ///
265 265
    /// This function gives back true if the given node is valid,
266 266
    /// ie. it is a real node of the graph.
267 267
    ///
268 268
    /// \warning A removed node (using Snapshot) could become valid again
269 269
    /// when new nodes are added to the graph.
270 270
    bool valid(Node n) const { return Parent::valid(n); }
271 271

	
272 272
    /// \brief Arc validity check
273 273
    ///
274 274
    /// This function gives back true if the given arc is valid,
275 275
    /// ie. it is a real arc of the graph.
276 276
    ///
277 277
    /// \warning A removed arc (using Snapshot) could become valid again
278 278
    /// when new arcs are added to the graph.
279 279
    bool valid(Arc a) const { return Parent::valid(a); }
280 280

	
281 281
    ///Clear the digraph.
282 282

	
283 283
    ///Erase all the nodes and arcs from the digraph.
284 284
    ///
285 285
    void clear() {
286 286
      Parent::clear();
287 287
    }
288 288

	
289 289
    ///Split a node.
290 290

	
291 291
    ///This function splits a node. First a new node is added to the digraph,
292 292
    ///then the source of each outgoing arc of \c n is moved to this new node.
293 293
    ///If \c connect is \c true (this is the default value), then a new arc
294 294
    ///from \c n to the newly created node is also added.
295 295
    ///\return The newly created node.
296 296
    ///
297 297
    ///\note The <tt>Arc</tt>s
298 298
    ///referencing a moved arc remain
299 299
    ///valid. However <tt>InArc</tt>'s and <tt>OutArc</tt>'s
300 300
    ///may be invalidated.
301 301
    ///\warning This functionality cannot be used together with the Snapshot
302 302
    ///feature.
303 303
    Node split(Node n, bool connect = true)
304 304
    {
305 305
      Node b = addNode();
306 306
      nodes[b._id].first_out=nodes[n._id].first_out;
307 307
      nodes[n._id].first_out=-1;
308 308
      for(int i=nodes[b._id].first_out;i!=-1;i++) arcs[i].source=b._id;
309 309
      if(connect) addArc(n,b);
310 310
      return b;
311 311
    }
312 312

	
313 313
  public:
314 314

	
315 315
    class Snapshot;
316 316

	
317 317
  protected:
318 318

	
319 319
    void restoreSnapshot(const Snapshot &s)
320 320
    {
321 321
      while(s.arc_num<arcs.size()) {
322 322
        Arc arc = arcFromId(arcs.size()-1);
323 323
        Parent::notifier(Arc()).erase(arc);
324 324
        nodes[arcs.back().source].first_out=arcs.back().next_out;
325 325
        nodes[arcs.back().target].first_in=arcs.back().next_in;
326 326
        arcs.pop_back();
327 327
      }
328 328
      while(s.node_num<nodes.size()) {
329 329
        Node node = nodeFromId(nodes.size()-1);
330 330
        Parent::notifier(Node()).erase(node);
331 331
        nodes.pop_back();
332 332
      }
333 333
    }
334 334

	
335 335
  public:
336 336

	
337 337
    ///Class to make a snapshot of the digraph and to restrore to it later.
338 338

	
339 339
    ///Class to make a snapshot of the digraph and to restrore to it later.
340 340
    ///
341 341
    ///The newly added nodes and arcs can be removed using the
342 342
    ///restore() function.
343 343
    ///\note After you restore a state, you cannot restore
344 344
    ///a later state, in other word you cannot add again the arcs deleted
345 345
    ///by restore() using another one Snapshot instance.
346 346
    ///
347 347
    ///\warning If you do not use correctly the snapshot that can cause
348 348
    ///either broken program, invalid state of the digraph, valid but
349 349
    ///not the restored digraph or no change. Because the runtime performance
350 350
    ///the validity of the snapshot is not stored.
351 351
    class Snapshot
352 352
    {
353 353
      SmartDigraph *_graph;
354 354
    protected:
355 355
      friend class SmartDigraph;
356 356
      unsigned int node_num;
357 357
      unsigned int arc_num;
358 358
    public:
359 359
      ///Default constructor.
360 360

	
361 361
      ///Default constructor.
362 362
      ///To actually make a snapshot you must call save().
363 363
      ///
364 364
      Snapshot() : _graph(0) {}
365 365
      ///Constructor that immediately makes a snapshot
366 366

	
367 367
      ///This constructor immediately makes a snapshot of the digraph.
368 368
      ///\param graph The digraph we make a snapshot of.
369 369
      Snapshot(SmartDigraph &graph) : _graph(&graph) {
370 370
        node_num=_graph->nodes.size();
371 371
        arc_num=_graph->arcs.size();
372 372
      }
373 373

	
374 374
      ///Make a snapshot.
375 375

	
376 376
      ///Make a snapshot of the digraph.
377 377
      ///
378 378
      ///This function can be called more than once. In case of a repeated
379 379
      ///call, the previous snapshot gets lost.
380 380
      ///\param graph The digraph we make the snapshot of.
381 381
      void save(SmartDigraph &graph)
382 382
      {
383 383
        _graph=&graph;
384 384
        node_num=_graph->nodes.size();
385 385
        arc_num=_graph->arcs.size();
386 386
      }
387 387

	
388 388
      ///Undo the changes until a snapshot.
389 389

	
390 390
      ///Undo the changes until a snapshot created by save().
391 391
      ///
392 392
      ///\note After you restored a state, you cannot restore
393 393
      ///a later state, in other word you cannot add again the arcs deleted
394 394
      ///by restore().
395 395
      void restore()
396 396
      {
397 397
        _graph->restoreSnapshot(*this);
398 398
      }
399 399
    };
400 400
  };
401 401

	
402 402

	
403 403
  class SmartGraphBase {
404 404

	
405 405
  protected:
406 406

	
407 407
    struct NodeT {
408 408
      int first_out;
409 409
    };
410 410

	
411 411
    struct ArcT {
412 412
      int target;
413 413
      int next_out;
414 414
    };
415 415

	
416 416
    std::vector<NodeT> nodes;
417 417
    std::vector<ArcT> arcs;
418 418

	
419 419
    int first_free_arc;
420 420

	
421 421
  public:
422 422

	
423 423
    typedef SmartGraphBase Digraph;
424 424

	
425 425
    class Node;
426 426
    class Arc;
427 427
    class Edge;
428 428

	
429 429
    class Node {
430 430
      friend class SmartGraphBase;
431 431
    protected:
432 432

	
433 433
      int _id;
434 434
      explicit Node(int id) { _id = id;}
435 435

	
436 436
    public:
437 437
      Node() {}
438 438
      Node (Invalid) { _id = -1; }
439 439
      bool operator==(const Node& node) const {return _id == node._id;}
440 440
      bool operator!=(const Node& node) const {return _id != node._id;}
441 441
      bool operator<(const Node& node) const {return _id < node._id;}
442 442
    };
443 443

	
444 444
    class Edge {
445 445
      friend class SmartGraphBase;
446 446
    protected:
447 447

	
448 448
      int _id;
449 449
      explicit Edge(int id) { _id = id;}
450 450

	
451 451
    public:
452 452
      Edge() {}
453 453
      Edge (Invalid) { _id = -1; }
454 454
      bool operator==(const Edge& arc) const {return _id == arc._id;}
455 455
      bool operator!=(const Edge& arc) const {return _id != arc._id;}
456 456
      bool operator<(const Edge& arc) const {return _id < arc._id;}
457 457
    };
458 458

	
459 459
    class Arc {
460 460
      friend class SmartGraphBase;
461 461
    protected:
462 462

	
463 463
      int _id;
464 464
      explicit Arc(int id) { _id = id;}
465 465

	
466 466
    public:
467
      operator Edge() const { 
468
        return _id != -1 ? edgeFromId(_id / 2) : INVALID; 
467
      operator Edge() const {
468
        return _id != -1 ? edgeFromId(_id / 2) : INVALID;
469 469
      }
470 470

	
471 471
      Arc() {}
472 472
      Arc (Invalid) { _id = -1; }
473 473
      bool operator==(const Arc& arc) const {return _id == arc._id;}
474 474
      bool operator!=(const Arc& arc) const {return _id != arc._id;}
475 475
      bool operator<(const Arc& arc) const {return _id < arc._id;}
476 476
    };
477 477

	
478 478

	
479 479

	
480 480
    SmartGraphBase()
481 481
      : nodes(), arcs() {}
482 482

	
483 483

	
484 484
    int maxNodeId() const { return nodes.size()-1; }
485 485
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
486 486
    int maxArcId() const { return arcs.size()-1; }
487 487

	
488 488
    Node source(Arc e) const { return Node(arcs[e._id ^ 1].target); }
489 489
    Node target(Arc e) const { return Node(arcs[e._id].target); }
490 490

	
491 491
    Node u(Edge e) const { return Node(arcs[2 * e._id].target); }
492 492
    Node v(Edge e) const { return Node(arcs[2 * e._id + 1].target); }
493 493

	
494 494
    static bool direction(Arc e) {
495 495
      return (e._id & 1) == 1;
496 496
    }
497 497

	
498 498
    static Arc direct(Edge e, bool d) {
499 499
      return Arc(e._id * 2 + (d ? 1 : 0));
500 500
    }
501 501

	
502 502
    void first(Node& node) const {
503 503
      node._id = nodes.size() - 1;
504 504
    }
505 505

	
506 506
    void next(Node& node) const {
507 507
      --node._id;
508 508
    }
509 509

	
510 510
    void first(Arc& arc) const {
511 511
      arc._id = arcs.size() - 1;
512 512
    }
513 513

	
514 514
    void next(Arc& arc) const {
515 515
      --arc._id;
516 516
    }
517 517

	
518 518
    void first(Edge& arc) const {
519 519
      arc._id = arcs.size() / 2 - 1;
520 520
    }
521 521

	
522 522
    void next(Edge& arc) const {
523 523
      --arc._id;
524 524
    }
525 525

	
526 526
    void firstOut(Arc &arc, const Node& v) const {
527 527
      arc._id = nodes[v._id].first_out;
528 528
    }
529 529
    void nextOut(Arc &arc) const {
530 530
      arc._id = arcs[arc._id].next_out;
531 531
    }
532 532

	
533 533
    void firstIn(Arc &arc, const Node& v) const {
534 534
      arc._id = ((nodes[v._id].first_out) ^ 1);
535 535
      if (arc._id == -2) arc._id = -1;
536 536
    }
537 537
    void nextIn(Arc &arc) const {
538 538
      arc._id = ((arcs[arc._id ^ 1].next_out) ^ 1);
539 539
      if (arc._id == -2) arc._id = -1;
540 540
    }
541 541

	
542 542
    void firstInc(Edge &arc, bool& d, const Node& v) const {
543 543
      int de = nodes[v._id].first_out;
544 544
      if (de != -1) {
545 545
        arc._id = de / 2;
546 546
        d = ((de & 1) == 1);
547 547
      } else {
548 548
        arc._id = -1;
549 549
        d = true;
550 550
      }
551 551
    }
552 552
    void nextInc(Edge &arc, bool& d) const {
553 553
      int de = (arcs[(arc._id * 2) | (d ? 1 : 0)].next_out);
554 554
      if (de != -1) {
555 555
        arc._id = de / 2;
556 556
        d = ((de & 1) == 1);
557 557
      } else {
558 558
        arc._id = -1;
559 559
        d = true;
560 560
      }
561 561
    }
562 562

	
563 563
    static int id(Node v) { return v._id; }
564 564
    static int id(Arc e) { return e._id; }
565 565
    static int id(Edge e) { return e._id; }
566 566

	
567 567
    static Node nodeFromId(int id) { return Node(id);}
568 568
    static Arc arcFromId(int id) { return Arc(id);}
569 569
    static Edge edgeFromId(int id) { return Edge(id);}
570 570

	
571 571
    bool valid(Node n) const {
572 572
      return n._id >= 0 && n._id < static_cast<int>(nodes.size());
573 573
    }
574 574
    bool valid(Arc a) const {
575 575
      return a._id >= 0 && a._id < static_cast<int>(arcs.size());
576 576
    }
577 577
    bool valid(Edge e) const {
578 578
      return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size());
579 579
    }
580 580

	
581 581
    Node addNode() {
582 582
      int n = nodes.size();
583 583
      nodes.push_back(NodeT());
584 584
      nodes[n].first_out = -1;
585 585

	
586 586
      return Node(n);
587 587
    }
588 588

	
589 589
    Edge addEdge(Node u, Node v) {
590 590
      int n = arcs.size();
591 591
      arcs.push_back(ArcT());
592 592
      arcs.push_back(ArcT());
593 593

	
594 594
      arcs[n].target = u._id;
595 595
      arcs[n | 1].target = v._id;
596 596

	
597 597
      arcs[n].next_out = nodes[v._id].first_out;
598 598
      nodes[v._id].first_out = n;
599 599

	
600 600
      arcs[n | 1].next_out = nodes[u._id].first_out;
601 601
      nodes[u._id].first_out = (n | 1);
602 602

	
603 603
      return Edge(n / 2);
604 604
    }
605 605

	
606 606
    void clear() {
607 607
      arcs.clear();
608 608
      nodes.clear();
609 609
    }
610 610

	
611 611
  };
612 612

	
613 613
  typedef GraphExtender<SmartGraphBase> ExtendedSmartGraphBase;
614 614

	
615 615
  /// \ingroup graphs
616 616
  ///
617 617
  /// \brief A smart undirected graph class.
618 618
  ///
619 619
  /// This is a simple and fast graph implementation.
620 620
  /// It is also quite memory efficient, but at the price
621 621
  /// that <b> it does support only limited (only stack-like)
622 622
  /// node and arc deletions</b>.
623 623
  /// Except from this it conforms to
624 624
  /// the \ref concepts::Graph "Graph concept".
625 625
  ///
626 626
  /// It also has an
627 627
  /// important extra feature that
628 628
  /// its maps are real \ref concepts::ReferenceMap "reference map"s.
629 629
  ///
630 630
  /// \sa concepts::Graph.
631 631
  ///
632 632
  class SmartGraph : public ExtendedSmartGraphBase {
633 633
  private:
634 634

	
635 635
    ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
636 636

	
637 637
    ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
638 638
    ///
639 639
    SmartGraph(const SmartGraph &) : ExtendedSmartGraphBase() {};
640 640

	
641 641
    ///\brief Assignment of SmartGraph to another one is \e not allowed.
642 642
    ///Use GraphCopy() instead.
643 643

	
644 644
    ///Assignment of SmartGraph to another one is \e not allowed.
645 645
    ///Use GraphCopy() instead.
646 646
    void operator=(const SmartGraph &) {}
647 647

	
648 648
  public:
649 649

	
650 650
    typedef ExtendedSmartGraphBase Parent;
651 651

	
652 652
    /// Constructor
653 653

	
654 654
    /// Constructor.
655 655
    ///
656 656
    SmartGraph() {}
657 657

	
658 658
    ///Add a new node to the graph.
659 659

	
660 660
    /// \return the new node.
661 661
    ///
662 662
    Node addNode() { return Parent::addNode(); }
663 663

	
664 664
    ///Add a new edge to the graph.
665 665

	
666 666
    ///Add a new edge to the graph with node \c s
667 667
    ///and \c t.
668 668
    ///\return the new edge.
669 669
    Edge addEdge(const Node& s, const Node& t) {
670 670
      return Parent::addEdge(s, t);
671 671
    }
672 672

	
673 673
    /// \brief Node validity check
674 674
    ///
675 675
    /// This function gives back true if the given node is valid,
676 676
    /// ie. it is a real node of the graph.
677 677
    ///
678 678
    /// \warning A removed node (using Snapshot) could become valid again
679 679
    /// when new nodes are added to the graph.
680 680
    bool valid(Node n) const { return Parent::valid(n); }
681 681

	
682 682
    /// \brief Arc validity check
683 683
    ///
684 684
    /// This function gives back true if the given arc is valid,
685 685
    /// ie. it is a real arc of the graph.
686 686
    ///
687 687
    /// \warning A removed arc (using Snapshot) could become valid again
688 688
    /// when new edges are added to the graph.
689 689
    bool valid(Arc a) const { return Parent::valid(a); }
690 690

	
691 691
    /// \brief Edge validity check
692 692
    ///
693 693
    /// This function gives back true if the given edge is valid,
694 694
    /// ie. it is a real edge of the graph.
695 695
    ///
696 696
    /// \warning A removed edge (using Snapshot) could become valid again
697 697
    /// when new edges are added to the graph.
698 698
    bool valid(Edge e) const { return Parent::valid(e); }
699 699

	
700 700
    ///Clear the graph.
701 701

	
702 702
    ///Erase all the nodes and edges from the graph.
703 703
    ///
704 704
    void clear() {
705 705
      Parent::clear();
706 706
    }
707 707

	
708 708
  public:
709 709

	
710 710
    class Snapshot;
711 711

	
712 712
  protected:
713 713

	
714 714
    void saveSnapshot(Snapshot &s)
715 715
    {
716 716
      s._graph = this;
717 717
      s.node_num = nodes.size();
718 718
      s.arc_num = arcs.size();
719 719
    }
720 720

	
721 721
    void restoreSnapshot(const Snapshot &s)
722 722
    {
723 723
      while(s.arc_num<arcs.size()) {
724 724
        int n=arcs.size()-1;
725 725
        Edge arc=edgeFromId(n/2);
726 726
        Parent::notifier(Edge()).erase(arc);
727 727
        std::vector<Arc> dir;
728 728
        dir.push_back(arcFromId(n));
729 729
        dir.push_back(arcFromId(n-1));
730 730
        Parent::notifier(Arc()).erase(dir);
731 731
        nodes[arcs[n].target].first_out=arcs[n].next_out;
732 732
        nodes[arcs[n-1].target].first_out=arcs[n-1].next_out;
733 733
        arcs.pop_back();
734 734
        arcs.pop_back();
735 735
      }
736 736
      while(s.node_num<nodes.size()) {
737 737
        int n=nodes.size()-1;
738 738
        Node node = nodeFromId(n);
739 739
        Parent::notifier(Node()).erase(node);
740 740
        nodes.pop_back();
741 741
      }
742 742
    }
743 743

	
744 744
  public:
745 745

	
746 746
    ///Class to make a snapshot of the digraph and to restrore to it later.
747 747

	
748 748
    ///Class to make a snapshot of the digraph and to restrore to it later.
749 749
    ///
750 750
    ///The newly added nodes and arcs can be removed using the
751 751
    ///restore() function.
752 752
    ///
753 753
    ///\note After you restore a state, you cannot restore
754 754
    ///a later state, in other word you cannot add again the arcs deleted
755 755
    ///by restore() using another one Snapshot instance.
756 756
    ///
757 757
    ///\warning If you do not use correctly the snapshot that can cause
758 758
    ///either broken program, invalid state of the digraph, valid but
759 759
    ///not the restored digraph or no change. Because the runtime performance
760 760
    ///the validity of the snapshot is not stored.
761 761
    class Snapshot
762 762
    {
763 763
      SmartGraph *_graph;
764 764
    protected:
765 765
      friend class SmartGraph;
766 766
      unsigned int node_num;
767 767
      unsigned int arc_num;
768 768
    public:
769 769
      ///Default constructor.
770 770

	
771 771
      ///Default constructor.
772 772
      ///To actually make a snapshot you must call save().
773 773
      ///
774 774
      Snapshot() : _graph(0) {}
775 775
      ///Constructor that immediately makes a snapshot
776 776

	
777 777
      ///This constructor immediately makes a snapshot of the digraph.
778 778
      ///\param graph The digraph we make a snapshot of.
779 779
      Snapshot(SmartGraph &graph) {
780 780
        graph.saveSnapshot(*this);
781 781
      }
782 782

	
783 783
      ///Make a snapshot.
784 784

	
785 785
      ///Make a snapshot of the graph.
786 786
      ///
787 787
      ///This function can be called more than once. In case of a repeated
788 788
      ///call, the previous snapshot gets lost.
789 789
      ///\param graph The digraph we make the snapshot of.
790 790
      void save(SmartGraph &graph)
791 791
      {
792 792
        graph.saveSnapshot(*this);
793 793
      }
794 794

	
795 795
      ///Undo the changes until a snapshot.
796 796

	
797 797
      ///Undo the changes until a snapshot created by save().
798 798
      ///
799 799
      ///\note After you restored a state, you cannot restore
800 800
      ///a later state, in other word you cannot add again the arcs deleted
801 801
      ///by restore().
802 802
      void restore()
803 803
      {
804 804
        _graph->restoreSnapshot(*this);
805 805
      }
806 806
    };
807 807
  };
808 808

	
809 809
} //namespace lemon
810 810

	
811 811

	
812 812
#endif //LEMON_SMART_GRAPH_H
Ignore white space 24576 line context
1 1
#!/bin/bash
2 2

	
3 3
YEAR=`date +2003-%Y`
4 4
HGROOT=`hg root`
5 5

	
6 6
# file enumaration modes
7 7

	
8 8
function all_files() {
9 9
    hg status -a -m -c |
10 10
    cut -d ' ' -f 2 | grep -E '(\.(cc|h|dox)$|Makefile\.am$)' |
11 11
    while read file; do echo $HGROOT/$file; done
12 12
}
13 13

	
14 14
function modified_files() {
15 15
    hg status -a -m |
16 16
    cut -d ' ' -f 2 | grep -E  '(\.(cc|h|dox)$|Makefile\.am$)' |
17 17
    while read file; do echo $HGROOT/$file; done
18 18
}
19 19

	
20 20
function changed_files() {
21 21
    {
22 22
        if [ -n "$HG_PARENT1" ]
23 23
        then
24 24
            hg status --rev $HG_PARENT1:$HG_NODE -a -m
25 25
        fi
26 26
        if [ -n "$HG_PARENT2" ]
27 27
        then
28 28
            hg status --rev $HG_PARENT2:$HG_NODE -a -m
29 29
        fi
30 30
    } | cut -d ' ' -f 2 | grep -E '(\.(cc|h|dox)$|Makefile\.am$)' | 
31 31
    sort | uniq |
32 32
    while read file; do echo $HGROOT/$file; done
33 33
}
34 34

	
35 35
function given_files() {
36 36
    for file in $GIVEN_FILES
37 37
    do
38 38
	echo $file
39 39
    done
40 40
}
41 41

	
42 42
# actions
43 43

	
44 44
function update_action() {
45 45
    if ! diff -q $1 $2 >/dev/null
46 46
    then
47 47
	echo -n " [$3 updated]"
48 48
	rm $2
49 49
	mv $1 $2
50 50
	CHANGED=YES
51 51
    fi
52 52
}
53 53

	
54 54
function update_warning() {
55 55
    echo -n " [$2 warning]"
56 56
    WARNED=YES
57 57
}
58 58

	
59 59
function update_init() {
60 60
    echo Update source files...
61 61
    TOTAL_FILES=0
62 62
    CHANGED_FILES=0
63 63
    WARNED_FILES=0
64 64
}
65 65

	
66 66
function update_done() {
67 67
    echo $CHANGED_FILES out of $TOTAL_FILES files has been changed.
68 68
    echo $WARNED_FILES out of $TOTAL_FILES files triggered warnings.
69 69
}
70 70

	
71 71
function update_begin() {
72 72
    ((TOTAL_FILES++))
73 73
    CHANGED=NO
74 74
    WARNED=NO
75 75
}
76 76

	
77 77
function update_end() {
78 78
    if [ $CHANGED == YES ]
79 79
    then
80 80
	((++CHANGED_FILES))
81 81
    fi
82 82
    if [ $WARNED == YES ]
83 83
    then
84 84
	((++WARNED_FILES))
85 85
    fi
86 86
}
87 87

	
88 88
function check_action() {
89 89
    if ! diff -q $1 $2 >/dev/null
90 90
    then
91
	echo -n " [$3 failed]"
91
	echo
92
	echo -n "      $3 failed at line(s): "
93
	echo -n $(diff $1 $2 | grep '^[0-9]' | sed "s/^\(.*\)c.*$/ \1/g" | 
94
	          sed "s/,/-/g" | paste -s -d',')
92 95
	FAILED=YES
93 96
    fi
94 97
}
95 98

	
96 99
function check_warning() {
97
    echo -n " [$2 warning]"
100
    echo
101
    if [ "$2" == 'long lines' ]
102
    then
103
        echo -n "      $2 warning at line(s): "
104
        echo -n $(grep -n -E '.{81,}' $1 | sed "s/^\([0-9]*\)/ \1\t/g" | 
105
                  cut -f 1 | paste -s -d',')
106
    else
107
        echo -n "      $2 warning"
108
    fi
98 109
    WARNED=YES
99 110
}
100 111

	
101 112
function check_init() {
102 113
    echo Check source files...
103 114
    FAILED_FILES=0
104 115
    WARNED_FILES=0
105 116
    TOTAL_FILES=0
106 117
}
107 118

	
108 119
function check_done() {
109 120
    echo $FAILED_FILES out of $TOTAL_FILES files has been failed.
110 121
    echo $WARNED_FILES out of $TOTAL_FILES files triggered warnings.
111 122

	
112 123
    if [ $FAILED_FILES -gt 0 ]
113 124
    then
114 125
	return 1
115 126
    elif [ $WARNED_FILES -gt 0 ]
116 127
    then
117 128
	if [ "$WARNING" == 'INTERACTIVE' ]
118 129
	then
119 130
	    echo -n "Are the files with warnings acceptable? (yes/no) "
120 131
	    while read answer
121 132
	    do
122 133
		if [ "$answer" == 'yes' ]
123 134
		then
124 135
		    return 0
125 136
		elif [ "$answer" == 'no' ]
126 137
		then
127 138
		    return 1
128 139
		fi
129 140
		echo -n "Are the files with warnings acceptable? (yes/no) "
130 141
	    done
131 142
	elif [ "$WARNING" == 'WERROR' ]
132 143
	then
133 144
	    return 1
134 145
	fi
135 146
    fi
136 147
}
137 148

	
138 149
function check_begin() {
139 150
    ((TOTAL_FILES++))
140 151
    FAILED=NO
141 152
    WARNED=NO
142 153
}
143 154

	
144 155
function check_end() {
145 156
    if [ $FAILED == YES ]
146 157
    then
147 158
	((++FAILED_FILES))
148 159
    fi
149 160
    if [ $WARNED == YES ]
150 161
    then
151 162
	((++WARNED_FILES))
152 163
    fi
153 164
}
154 165

	
155 166

	
156 167

	
157 168
# checks
158 169

	
159 170
function header_check() {
160 171
    if echo $1 | grep -q -E 'Makefile\.am$'
161 172
    then
162 173
	return
163 174
    fi
164 175

	
165 176
    TMP_FILE=`mktemp`
166 177

	
167 178
    (echo "/* -*- mode: C++; indent-tabs-mode: nil; -*-
168 179
 *
169 180
 * This file is a part of LEMON, a generic C++ optimization library.
170 181
 *
171 182
 * Copyright (C) "$YEAR"
172 183
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
173 184
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
174 185
 *
175 186
 * Permission to use, modify and distribute this software is granted
176 187
 * provided that this copyright notice appears in all copies. For
177 188
 * precise terms see the accompanying LICENSE file.
178 189
 *
179 190
 * This software is provided \"AS IS\" with no warranty of any kind,
180 191
 * express or implied, and with no claim as to its suitability for any
181 192
 * purpose.
182 193
 *
183 194
 */
184 195
"
185 196
    awk 'BEGIN { pm=0; }
186 197
     pm==3 { print }
187 198
     /\/\* / && pm==0 { pm=1;}
188 199
     /[^:blank:]/ && (pm==0 || pm==2) { pm=3; print;}
189 200
     /\*\// && pm==1 { pm=2;}
190 201
    ' $1
191 202
    ) >$TMP_FILE
192 203

	
193 204
    "$ACTION"_action "$TMP_FILE" "$1" header
194 205
}
195 206

	
196 207
function tabs_check() {
197 208
    if echo $1 | grep -q -v -E 'Makefile\.am$'
198 209
    then
199 210
        OLD_PATTERN=$(echo -e '\t')
200 211
        NEW_PATTERN='        '
201 212
    else
202 213
        OLD_PATTERN='        '
203 214
        NEW_PATTERN=$(echo -e '\t')
204 215
    fi
205 216
    TMP_FILE=`mktemp`
206 217
    cat $1 | sed -e "s/$OLD_PATTERN/$NEW_PATTERN/g" >$TMP_FILE
207 218

	
208 219
    "$ACTION"_action "$TMP_FILE" "$1" 'tabs'
209 220
}
210 221

	
211 222
function spaces_check() {
212 223
    TMP_FILE=`mktemp`
213 224
    cat $1 | sed -e 's/ \+$//g' >$TMP_FILE
214 225

	
215
    "$ACTION"_action "$TMP_FILE" "$1" 'spaces'
226
    "$ACTION"_action "$TMP_FILE" "$1" 'trailing spaces'
216 227
}
217 228

	
218 229
function long_lines_check() {
219 230
    if cat $1 | grep -q -E '.{81,}'
220 231
    then
221 232
	"$ACTION"_warning $1 'long lines'
222 233
    fi
223 234
}
224 235

	
225 236
# process the file
226 237

	
227 238
function process_file() {
228
    echo -n "    $ACTION " $1...
239
    echo -n "    $ACTION $1..."
229 240

	
230 241
    CHECKING="header tabs spaces long_lines"
231 242

	
232 243
    "$ACTION"_begin $1
233 244
    for check in $CHECKING
234 245
    do
235 246
	"$check"_check $1
236 247
    done
237 248
    "$ACTION"_end $1
238 249
    echo
239 250
}
240 251

	
241 252
function process_all {
242 253
    "$ACTION"_init
243 254
    while read file
244 255
    do
245 256
	process_file $file
246 257
    done < <($FILES)
247 258
    "$ACTION"_done
248 259
}
249 260

	
250 261
while [ $# -gt 0 ]
251 262
do
252 263
    
253 264
    if [ "$1" == '--help' ] || [ "$1" == '-h' ]
254 265
    then
255 266
	echo -n \
256 267
"Usage:
257 268
  $0 [OPTIONS] [files]
258 269
Options:
259 270
  --dry-run|-n
260 271
     Check the files, but do not modify them.
261 272
  --interactive|-i
262 273
     If --dry-run is specified and the checker emits warnings,
263 274
     then the user is asked if the warnings should be considered
264 275
     errors.
265 276
  --werror|-w
266 277
     Make all warnings into errors.
267 278
  --all|-a
268
     All files in the repository will be checked.
279
     Check all source files in the repository.
269 280
  --modified|-m
270 281
     Check only the modified (and new) source files. This option is
271 282
     useful to check the modification before making a commit.
272 283
  --changed|-c
273 284
     Check only the changed source files compared to the parent(s) of
274 285
     the current hg node.  This option is useful as hg hook script.
275 286
     To automatically check all your changes before making a commit,
276 287
     add the following section to the appropriate .hg/hgrc file.
277 288

	
278 289
       [hooks]
279 290
       pretxncommit.checksources = scripts/unify-sources.sh -c -n -i
280 291

	
281 292
  --help|-h
282 293
     Print this help message.
283 294
  files
284
     The files to check/unify. If no file names are given, the
285
     modified source will be checked/unified
286

	
295
     The files to check/unify. If no file names are given, the modified
296
     source files will be checked/unified (just like using the
297
     --modified|-m option).
287 298
"
288 299
        exit 0
289 300
    elif [ "$1" == '--dry-run' ] || [ "$1" == '-n' ]
290 301
    then
291
	[ -n "$ACTION" ] && echo "Invalid option $1" >&2 && exit 1
302
	[ -n "$ACTION" ] && echo "Conflicting action options" >&2 && exit 1
292 303
	ACTION=check
293 304
    elif [ "$1" == "--all" ] || [ "$1" == '-a' ]
294 305
    then
295
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
306
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
296 307
	FILES=all_files
297 308
    elif [ "$1" == "--changed" ] || [ "$1" == '-c' ]
298 309
    then
299
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
310
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
300 311
	FILES=changed_files
301 312
    elif [ "$1" == "--modified" ] || [ "$1" == '-m' ]
302 313
    then
303
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
314
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
304 315
	FILES=modified_files
305 316
    elif [ "$1" == "--interactive" ] || [ "$1" == "-i" ]
306 317
    then
307
	[ -n "$WARNING" ] && echo "Invalid option $1" >&2 && exit 1
318
	[ -n "$WARNING" ] && echo "Conflicting warning options" >&2 && exit 1
308 319
	WARNING='INTERACTIVE'
309 320
    elif [ "$1" == "--werror" ] || [ "$1" == "-w" ]
310 321
    then
311
	[ -n "$WARNING" ] && echo "Invalid option $1" >&2 && exit 1
322
	[ -n "$WARNING" ] && echo "Conflicting warning options" >&2 && exit 1
312 323
	WARNING='WERROR'
313
    elif [ $(echo $1 | cut -c 1) == '-' ]
324
    elif [ $(echo x$1 | cut -c 2) == '-' ]
314 325
    then
315 326
	echo "Invalid option $1" >&2 && exit 1
316 327
    else
317 328
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
318 329
	GIVEN_FILES=$@
319 330
	FILES=given_files
320 331
	break
321 332
    fi
322 333
    
323 334
    shift
324 335
done
325 336

	
326 337
if [ -z $FILES ]
327 338
then
328 339
    FILES=modified_files
329 340
fi
330 341

	
331 342
if [ -z $ACTION ]
332 343
then
333 344
    ACTION=update
334 345
fi
335 346

	
336 347
process_all
0 comments (0 inline)