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

	
19
// This file contains a modified version of the enable_if library from BOOST.
20
// See the appropriate copyright notice below.
21

	
22
// Boost enable_if library
23

	
24
// Copyright 2003 (c) The Trustees of Indiana University.
25

	
26
// Use, modification, and distribution is subject to the Boost Software
27
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
28
// http://www.boost.org/LICENSE_1_0.txt)
29

	
30
//    Authors: Jaakko Jarvi (jajarvi at osl.iu.edu)
31
//             Jeremiah Willcock (jewillco at osl.iu.edu)
32
//             Andrew Lumsdaine (lums at osl.iu.edu)
33

	
34

	
35
#ifndef LEMON_BITS_ENABLE_IF_H
36
#define LEMON_BITS_ENABLE_IF_H
37

	
38
///\file
39
///\brief Miscellaneous basic utilities
40

	
41
namespace lemon
42
{
43

	
44
  /// Basic type for defining "tags". A "YES" condition for \c enable_if.
45

	
46
  /// Basic type for defining "tags". A "YES" condition for \c enable_if.
47
  ///
48
  ///\sa False
49
  struct True {
50
    ///\e
51
    static const bool value = true;
52
  };
53

	
54
  /// Basic type for defining "tags". A "NO" condition for \c enable_if.
55

	
56
  /// Basic type for defining "tags". A "NO" condition for \c enable_if.
57
  ///
58
  ///\sa True
59
  struct False {
60
    ///\e
61
    static const bool value = false;
62
  };
63

	
64

	
65

	
66
  template <typename T>
67
  struct Wrap {
68
    const T &value;
69
    Wrap(const T &t) : value(t) {}
70
  };
71

	
72
  /**************** dummy class to avoid ambiguity ****************/
73

	
74
  template<int T> struct dummy { dummy(int) {} };
75

	
76
  /**************** enable_if from BOOST ****************/
77

	
78
  template <typename Type, typename T = void>
79
  struct exists {
80
    typedef T type;
81
  };
82

	
83

	
84
  template <bool B, class T = void>
85
  struct enable_if_c {
86
    typedef T type;
87
  };
88

	
89
  template <class T>
90
  struct enable_if_c<false, T> {};
91

	
92
  template <class Cond, class T = void>
93
  struct enable_if : public enable_if_c<Cond::value, T> {};
94

	
95
  template <bool B, class T>
96
  struct lazy_enable_if_c {
97
    typedef typename T::type type;
98
  };
99

	
100
  template <class T>
101
  struct lazy_enable_if_c<false, T> {};
102

	
103
  template <class Cond, class T>
104
  struct lazy_enable_if : public lazy_enable_if_c<Cond::value, T> {};
105

	
106

	
107
  template <bool B, class T = void>
108
  struct disable_if_c {
109
    typedef T type;
110
  };
111

	
112
  template <class T>
113
  struct disable_if_c<true, T> {};
114

	
115
  template <class Cond, class T = void>
116
  struct disable_if : public disable_if_c<Cond::value, T> {};
117

	
118
  template <bool B, class T>
119
  struct lazy_disable_if_c {
120
    typedef typename T::type type;
121
  };
122

	
123
  template <class T>
124
  struct lazy_disable_if_c<true, T> {};
125

	
126
  template <class Cond, class T>
127
  struct lazy_disable_if : public lazy_disable_if_c<Cond::value, T> {};
128

	
129
} // namespace lemon
130

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

	
19
#ifndef LEMON_CORE_H
20
#define LEMON_CORE_H
21

	
22
#include <vector>
23
#include <algorithm>
24

	
25
#include <lemon/bits/enable_if.h>
26
#include <lemon/bits/traits.h>
27

	
28
///\file
29
///\brief LEMON core utilities.
30

	
31
namespace lemon {
32

	
33
  /// \brief Dummy type to make it easier to create invalid iterators.
34
  ///
35
  /// Dummy type to make it easier to create invalid iterators.
36
  /// See \ref INVALID for the usage.
37
  struct Invalid {
38
  public:
39
    bool operator==(Invalid) { return true;  }
40
    bool operator!=(Invalid) { return false; }
41
    bool operator< (Invalid) { return false; }
42
  };
43

	
44
  /// \brief Invalid iterators.
45
  ///
46
  /// \ref Invalid is a global type that converts to each iterator
47
  /// in such a way that the value of the target iterator will be invalid.
48
#ifdef LEMON_ONLY_TEMPLATES
49
  const Invalid INVALID = Invalid();
50
#else
51
  extern const Invalid INVALID;
52
#endif
53

	
54
  /// \addtogroup gutils
55
  /// @{
56

	
57
  ///Creates convenience typedefs for the digraph types and iterators
58

	
59
  ///This \c \#define creates convenience typedefs for the following types
60
  ///of \c Digraph: \c Node,  \c NodeIt, \c Arc, \c ArcIt, \c InArcIt,
61
  ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap,
62
  ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap.
63
  ///
64
  ///\note If the graph type is a dependent type, ie. the graph type depend
65
  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
66
  ///macro.
67
#define DIGRAPH_TYPEDEFS(Digraph)                                       \
68
  typedef Digraph::Node Node;                                           \
69
  typedef Digraph::NodeIt NodeIt;                                       \
70
  typedef Digraph::Arc Arc;                                             \
71
  typedef Digraph::ArcIt ArcIt;                                         \
72
  typedef Digraph::InArcIt InArcIt;                                     \
73
  typedef Digraph::OutArcIt OutArcIt;                                   \
74
  typedef Digraph::NodeMap<bool> BoolNodeMap;                           \
75
  typedef Digraph::NodeMap<int> IntNodeMap;                             \
76
  typedef Digraph::NodeMap<double> DoubleNodeMap;                       \
77
  typedef Digraph::ArcMap<bool> BoolArcMap;                             \
78
  typedef Digraph::ArcMap<int> IntArcMap;                               \
79
  typedef Digraph::ArcMap<double> DoubleArcMap
80

	
81
  ///Creates convenience typedefs for the digraph types and iterators
82

	
83
  ///\see DIGRAPH_TYPEDEFS
84
  ///
85
  ///\note Use this macro, if the graph type is a dependent type,
86
  ///ie. the graph type depend on a template parameter.
87
#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph)                              \
88
  typedef typename Digraph::Node Node;                                  \
89
  typedef typename Digraph::NodeIt NodeIt;                              \
90
  typedef typename Digraph::Arc Arc;                                    \
91
  typedef typename Digraph::ArcIt ArcIt;                                \
92
  typedef typename Digraph::InArcIt InArcIt;                            \
93
  typedef typename Digraph::OutArcIt OutArcIt;                          \
94
  typedef typename Digraph::template NodeMap<bool> BoolNodeMap;         \
95
  typedef typename Digraph::template NodeMap<int> IntNodeMap;           \
96
  typedef typename Digraph::template NodeMap<double> DoubleNodeMap;     \
97
  typedef typename Digraph::template ArcMap<bool> BoolArcMap;           \
98
  typedef typename Digraph::template ArcMap<int> IntArcMap;             \
99
  typedef typename Digraph::template ArcMap<double> DoubleArcMap
100

	
101
  ///Creates convenience typedefs for the graph types and iterators
102

	
103
  ///This \c \#define creates the same convenience typedefs as defined
104
  ///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates
105
  ///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap,
106
  ///\c DoubleEdgeMap.
107
  ///
108
  ///\note If the graph type is a dependent type, ie. the graph type depend
109
  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
110
  ///macro.
111
#define GRAPH_TYPEDEFS(Graph)                                           \
112
  DIGRAPH_TYPEDEFS(Graph);                                              \
113
  typedef Graph::Edge Edge;                                             \
114
  typedef Graph::EdgeIt EdgeIt;                                         \
115
  typedef Graph::IncEdgeIt IncEdgeIt;                                   \
116
  typedef Graph::EdgeMap<bool> BoolEdgeMap;                             \
117
  typedef Graph::EdgeMap<int> IntEdgeMap;                               \
118
  typedef Graph::EdgeMap<double> DoubleEdgeMap
119

	
120
  ///Creates convenience typedefs for the graph types and iterators
121

	
122
  ///\see GRAPH_TYPEDEFS
123
  ///
124
  ///\note Use this macro, if the graph type is a dependent type,
125
  ///ie. the graph type depend on a template parameter.
126
#define TEMPLATE_GRAPH_TYPEDEFS(Graph)                                  \
127
  TEMPLATE_DIGRAPH_TYPEDEFS(Graph);                                     \
128
  typedef typename Graph::Edge Edge;                                    \
129
  typedef typename Graph::EdgeIt EdgeIt;                                \
130
  typedef typename Graph::IncEdgeIt IncEdgeIt;                          \
131
  typedef typename Graph::template EdgeMap<bool> BoolEdgeMap;           \
132
  typedef typename Graph::template EdgeMap<int> IntEdgeMap;             \
133
  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
134

	
135
  /// \brief Function to count the items in the graph.
136
  ///
137
  /// This function counts the items (nodes, arcs etc) in the graph.
138
  /// The complexity of the function is O(n) because
139
  /// it iterates on all of the items.
140
  template <typename Graph, typename Item>
141
  inline int countItems(const Graph& g) {
142
    typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt;
143
    int num = 0;
144
    for (ItemIt it(g); it != INVALID; ++it) {
145
      ++num;
146
    }
147
    return num;
148
  }
149

	
150
  // Node counting:
151

	
152
  namespace _core_bits {
153

	
154
    template <typename Graph, typename Enable = void>
155
    struct CountNodesSelector {
156
      static int count(const Graph &g) {
157
        return countItems<Graph, typename Graph::Node>(g);
158
      }
159
    };
160

	
161
    template <typename Graph>
162
    struct CountNodesSelector<
163
      Graph, typename
164
      enable_if<typename Graph::NodeNumTag, void>::type>
165
    {
166
      static int count(const Graph &g) {
167
        return g.nodeNum();
168
      }
169
    };
170
  }
171

	
172
  /// \brief Function to count the nodes in the graph.
173
  ///
174
  /// This function counts the nodes in the graph.
175
  /// The complexity of the function is O(n) but for some
176
  /// graph structures it is specialized to run in O(1).
177
  ///
178
  /// If the graph contains a \e nodeNum() member function and a
179
  /// \e NodeNumTag tag then this function calls directly the member
180
  /// function to query the cardinality of the node set.
181
  template <typename Graph>
182
  inline int countNodes(const Graph& g) {
183
    return _core_bits::CountNodesSelector<Graph>::count(g);
184
  }
185

	
186
  // Arc counting:
187

	
188
  namespace _core_bits {
189

	
190
    template <typename Graph, typename Enable = void>
191
    struct CountArcsSelector {
192
      static int count(const Graph &g) {
193
        return countItems<Graph, typename Graph::Arc>(g);
194
      }
195
    };
196

	
197
    template <typename Graph>
198
    struct CountArcsSelector<
199
      Graph,
200
      typename enable_if<typename Graph::ArcNumTag, void>::type>
201
    {
202
      static int count(const Graph &g) {
203
        return g.arcNum();
204
      }
205
    };
206
  }
207

	
208
  /// \brief Function to count the arcs in the graph.
209
  ///
210
  /// This function counts the arcs in the graph.
211
  /// The complexity of the function is O(e) but for some
212
  /// graph structures it is specialized to run in O(1).
213
  ///
214
  /// If the graph contains a \e arcNum() member function and a
215
  /// \e EdgeNumTag tag then this function calls directly the member
216
  /// function to query the cardinality of the arc set.
217
  template <typename Graph>
218
  inline int countArcs(const Graph& g) {
219
    return _core_bits::CountArcsSelector<Graph>::count(g);
220
  }
221

	
222
  // Edge counting:
223
  namespace _core_bits {
224

	
225
    template <typename Graph, typename Enable = void>
226
    struct CountEdgesSelector {
227
      static int count(const Graph &g) {
228
        return countItems<Graph, typename Graph::Edge>(g);
229
      }
230
    };
231

	
232
    template <typename Graph>
233
    struct CountEdgesSelector<
234
      Graph,
235
      typename enable_if<typename Graph::EdgeNumTag, void>::type>
236
    {
237
      static int count(const Graph &g) {
238
        return g.edgeNum();
239
      }
240
    };
241
  }
242

	
243
  /// \brief Function to count the edges in the graph.
244
  ///
245
  /// This function counts the edges in the graph.
246
  /// The complexity of the function is O(m) but for some
247
  /// graph structures it is specialized to run in O(1).
248
  ///
249
  /// If the graph contains a \e edgeNum() member function and a
250
  /// \e EdgeNumTag tag then this function calls directly the member
251
  /// function to query the cardinality of the edge set.
252
  template <typename Graph>
253
  inline int countEdges(const Graph& g) {
254
    return _core_bits::CountEdgesSelector<Graph>::count(g);
255

	
256
  }
257

	
258

	
259
  template <typename Graph, typename DegIt>
260
  inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
261
    int num = 0;
262
    for (DegIt it(_g, _n); it != INVALID; ++it) {
263
      ++num;
264
    }
265
    return num;
266
  }
267

	
268
  /// \brief Function to count the number of the out-arcs from node \c n.
269
  ///
270
  /// This function counts the number of the out-arcs from node \c n
271
  /// in the graph.
272
  template <typename Graph>
273
  inline int countOutArcs(const Graph& _g,  const typename Graph::Node& _n) {
274
    return countNodeDegree<Graph, typename Graph::OutArcIt>(_g, _n);
275
  }
276

	
277
  /// \brief Function to count the number of the in-arcs to node \c n.
278
  ///
279
  /// This function counts the number of the in-arcs to node \c n
280
  /// in the graph.
281
  template <typename Graph>
282
  inline int countInArcs(const Graph& _g,  const typename Graph::Node& _n) {
283
    return countNodeDegree<Graph, typename Graph::InArcIt>(_g, _n);
284
  }
285

	
286
  /// \brief Function to count the number of the inc-edges to node \c n.
287
  ///
288
  /// This function counts the number of the inc-edges to node \c n
289
  /// in the graph.
290
  template <typename Graph>
291
  inline int countIncEdges(const Graph& _g,  const typename Graph::Node& _n) {
292
    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(_g, _n);
293
  }
294

	
295
  namespace _core_bits {
296

	
297
    template <typename Digraph, typename Item, typename RefMap>
298
    class MapCopyBase {
299
    public:
300
      virtual void copy(const Digraph& from, const RefMap& refMap) = 0;
301

	
302
      virtual ~MapCopyBase() {}
303
    };
304

	
305
    template <typename Digraph, typename Item, typename RefMap,
306
              typename ToMap, typename FromMap>
307
    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
308
    public:
309

	
310
      MapCopy(ToMap& tmap, const FromMap& map)
311
        : _tmap(tmap), _map(map) {}
312

	
313
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
314
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
315
        for (ItemIt it(digraph); it != INVALID; ++it) {
316
          _tmap.set(refMap[it], _map[it]);
317
        }
318
      }
319

	
320
    private:
321
      ToMap& _tmap;
322
      const FromMap& _map;
323
    };
324

	
325
    template <typename Digraph, typename Item, typename RefMap, typename It>
326
    class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> {
327
    public:
328

	
329
      ItemCopy(It& it, const Item& item) : _it(it), _item(item) {}
330

	
331
      virtual void copy(const Digraph&, const RefMap& refMap) {
332
        _it = refMap[_item];
333
      }
334

	
335
    private:
336
      It& _it;
337
      Item _item;
338
    };
339

	
340
    template <typename Digraph, typename Item, typename RefMap, typename Ref>
341
    class RefCopy : public MapCopyBase<Digraph, Item, RefMap> {
342
    public:
343

	
344
      RefCopy(Ref& map) : _map(map) {}
345

	
346
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
347
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
348
        for (ItemIt it(digraph); it != INVALID; ++it) {
349
          _map.set(it, refMap[it]);
350
        }
351
      }
352

	
353
    private:
354
      Ref& _map;
355
    };
356

	
357
    template <typename Digraph, typename Item, typename RefMap,
358
              typename CrossRef>
359
    class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> {
360
    public:
361

	
362
      CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {}
363

	
364
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
365
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
366
        for (ItemIt it(digraph); it != INVALID; ++it) {
367
          _cmap.set(refMap[it], it);
368
        }
369
      }
370

	
371
    private:
372
      CrossRef& _cmap;
373
    };
374

	
375
    template <typename Digraph, typename Enable = void>
376
    struct DigraphCopySelector {
377
      template <typename From, typename NodeRefMap, typename ArcRefMap>
378
      static void copy(Digraph &to, const From& from,
379
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
380
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
381
          nodeRefMap[it] = to.addNode();
382
        }
383
        for (typename From::ArcIt it(from); it != INVALID; ++it) {
384
          arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)],
385
                                    nodeRefMap[from.target(it)]);
386
        }
387
      }
388
    };
389

	
390
    template <typename Digraph>
391
    struct DigraphCopySelector<
392
      Digraph,
393
      typename enable_if<typename Digraph::BuildTag, void>::type>
394
    {
395
      template <typename From, typename NodeRefMap, typename ArcRefMap>
396
      static void copy(Digraph &to, const From& from,
397
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
398
        to.build(from, nodeRefMap, arcRefMap);
399
      }
400
    };
401

	
402
    template <typename Graph, typename Enable = void>
403
    struct GraphCopySelector {
404
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
405
      static void copy(Graph &to, const From& from,
406
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
407
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
408
          nodeRefMap[it] = to.addNode();
409
        }
410
        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
411
          edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)],
412
                                      nodeRefMap[from.v(it)]);
413
        }
414
      }
415
    };
416

	
417
    template <typename Graph>
418
    struct GraphCopySelector<
419
      Graph,
420
      typename enable_if<typename Graph::BuildTag, void>::type>
421
    {
422
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
423
      static void copy(Graph &to, const From& from,
424
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
425
        to.build(from, nodeRefMap, edgeRefMap);
426
      }
427
    };
428

	
429
  }
430

	
431
  /// \brief Class to copy a digraph.
432
  ///
433
  /// Class to copy a digraph to another digraph (duplicate a digraph). The
434
  /// simplest way of using it is through the \c copyDigraph() function.
435
  ///
436
  /// This class not just make a copy of a graph, but it can create
437
  /// references and cross references between the nodes and arcs of
438
  /// the two graphs, it can copy maps for use with the newly created
439
  /// graph and copy nodes and arcs.
440
  ///
441
  /// To make a copy from a graph, first an instance of DigraphCopy
442
  /// should be created, then the data belongs to the graph should
443
  /// assigned to copy. In the end, the \c run() member should be
444
  /// called.
445
  ///
446
  /// The next code copies a graph with several data:
447
  ///\code
448
  ///  DigraphCopy<NewGraph, OrigGraph> dc(new_graph, orig_graph);
449
  ///  // create a reference for the nodes
450
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
451
  ///  dc.nodeRef(nr);
452
  ///  // create a cross reference (inverse) for the arcs
453
  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
454
  ///  dc.arcCrossRef(acr);
455
  ///  // copy an arc map
456
  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
457
  ///  NewGraph::ArcMap<double> namap(new_graph);
458
  ///  dc.arcMap(namap, oamap);
459
  ///  // copy a node
460
  ///  OrigGraph::Node on;
461
  ///  NewGraph::Node nn;
462
  ///  dc.node(nn, on);
463
  ///  // Executions of copy
464
  ///  dc.run();
465
  ///\endcode
466
  template <typename To, typename From>
467
  class DigraphCopy {
468
  private:
469

	
470
    typedef typename From::Node Node;
471
    typedef typename From::NodeIt NodeIt;
472
    typedef typename From::Arc Arc;
473
    typedef typename From::ArcIt ArcIt;
474

	
475
    typedef typename To::Node TNode;
476
    typedef typename To::Arc TArc;
477

	
478
    typedef typename From::template NodeMap<TNode> NodeRefMap;
479
    typedef typename From::template ArcMap<TArc> ArcRefMap;
480

	
481

	
482
  public:
483

	
484

	
485
    /// \brief Constructor for the DigraphCopy.
486
    ///
487
    /// It copies the content of the \c _from digraph into the
488
    /// \c _to digraph.
489
    DigraphCopy(To& to, const From& from)
490
      : _from(from), _to(to) {}
491

	
492
    /// \brief Destructor of the DigraphCopy
493
    ///
494
    /// Destructor of the DigraphCopy
495
    ~DigraphCopy() {
496
      for (int i = 0; i < int(_node_maps.size()); ++i) {
497
        delete _node_maps[i];
498
      }
499
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
500
        delete _arc_maps[i];
501
      }
502

	
503
    }
504

	
505
    /// \brief Copies the node references into the given map.
506
    ///
507
    /// Copies the node references into the given map. The parameter
508
    /// should be a map, which key type is the Node type of the source
509
    /// graph, while the value type is the Node type of the
510
    /// destination graph.
511
    template <typename NodeRef>
512
    DigraphCopy& nodeRef(NodeRef& map) {
513
      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
514
                           NodeRefMap, NodeRef>(map));
515
      return *this;
516
    }
517

	
518
    /// \brief Copies the node cross references into the given map.
519
    ///
520
    ///  Copies the node cross references (reverse references) into
521
    ///  the given map. The parameter should be a map, which key type
522
    ///  is the Node type of the destination graph, while the value type is
523
    ///  the Node type of the source graph.
524
    template <typename NodeCrossRef>
525
    DigraphCopy& nodeCrossRef(NodeCrossRef& map) {
526
      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
527
                           NodeRefMap, NodeCrossRef>(map));
528
      return *this;
529
    }
530

	
531
    /// \brief Make copy of the given map.
532
    ///
533
    /// Makes copy of the given map for the newly created digraph.
534
    /// The new map's key type is the destination graph's node type,
535
    /// and the copied map's key type is the source graph's node type.
536
    template <typename ToMap, typename FromMap>
537
    DigraphCopy& nodeMap(ToMap& tmap, const FromMap& map) {
538
      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
539
                           NodeRefMap, ToMap, FromMap>(tmap, map));
540
      return *this;
541
    }
542

	
543
    /// \brief Make a copy of the given node.
544
    ///
545
    /// Make a copy of the given node.
546
    DigraphCopy& node(TNode& tnode, const Node& snode) {
547
      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
548
                           NodeRefMap, TNode>(tnode, snode));
549
      return *this;
550
    }
551

	
552
    /// \brief Copies the arc references into the given map.
553
    ///
554
    /// Copies the arc references into the given map.
555
    template <typename ArcRef>
556
    DigraphCopy& arcRef(ArcRef& map) {
557
      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
558
                          ArcRefMap, ArcRef>(map));
559
      return *this;
560
    }
561

	
562
    /// \brief Copies the arc cross references into the given map.
563
    ///
564
    ///  Copies the arc cross references (reverse references) into
565
    ///  the given map.
566
    template <typename ArcCrossRef>
567
    DigraphCopy& arcCrossRef(ArcCrossRef& map) {
568
      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
569
                          ArcRefMap, ArcCrossRef>(map));
570
      return *this;
571
    }
572

	
573
    /// \brief Make copy of the given map.
574
    ///
575
    /// Makes copy of the given map for the newly created digraph.
576
    /// The new map's key type is the to digraph's arc type,
577
    /// and the copied map's key type is the from digraph's arc
578
    /// type.
579
    template <typename ToMap, typename FromMap>
580
    DigraphCopy& arcMap(ToMap& tmap, const FromMap& map) {
581
      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
582
                          ArcRefMap, ToMap, FromMap>(tmap, map));
583
      return *this;
584
    }
585

	
586
    /// \brief Make a copy of the given arc.
587
    ///
588
    /// Make a copy of the given arc.
589
    DigraphCopy& arc(TArc& tarc, const Arc& sarc) {
590
      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
591
                          ArcRefMap, TArc>(tarc, sarc));
592
      return *this;
593
    }
594

	
595
    /// \brief Executes the copies.
596
    ///
597
    /// Executes the copies.
598
    void run() {
599
      NodeRefMap nodeRefMap(_from);
600
      ArcRefMap arcRefMap(_from);
601
      _core_bits::DigraphCopySelector<To>::
602
        copy(_to, _from, nodeRefMap, arcRefMap);
603
      for (int i = 0; i < int(_node_maps.size()); ++i) {
604
        _node_maps[i]->copy(_from, nodeRefMap);
605
      }
606
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
607
        _arc_maps[i]->copy(_from, arcRefMap);
608
      }
609
    }
610

	
611
  protected:
612

	
613

	
614
    const From& _from;
615
    To& _to;
616

	
617
    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
618
    _node_maps;
619

	
620
    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
621
    _arc_maps;
622

	
623
  };
624

	
625
  /// \brief Copy a digraph to another digraph.
626
  ///
627
  /// Copy a digraph to another digraph. The complete usage of the
628
  /// function is detailed in the DigraphCopy class, but a short
629
  /// example shows a basic work:
630
  ///\code
631
  /// copyDigraph(trg, src).nodeRef(nr).arcCrossRef(ecr).run();
632
  ///\endcode
633
  ///
634
  /// After the copy the \c nr map will contain the mapping from the
635
  /// nodes of the \c from digraph to the nodes of the \c to digraph and
636
  /// \c ecr will contain the mapping from the arcs of the \c to digraph
637
  /// to the arcs of the \c from digraph.
638
  ///
639
  /// \see DigraphCopy
640
  template <typename To, typename From>
641
  DigraphCopy<To, From> copyDigraph(To& to, const From& from) {
642
    return DigraphCopy<To, From>(to, from);
643
  }
644

	
645
  /// \brief Class to copy a graph.
646
  ///
647
  /// Class to copy a graph to another graph (duplicate a graph). The
648
  /// simplest way of using it is through the \c copyGraph() function.
649
  ///
650
  /// This class not just make a copy of a graph, but it can create
651
  /// references and cross references between the nodes, edges and arcs of
652
  /// the two graphs, it can copy maps for use with the newly created
653
  /// graph and copy nodes, edges and arcs.
654
  ///
655
  /// To make a copy from a graph, first an instance of GraphCopy
656
  /// should be created, then the data belongs to the graph should
657
  /// assigned to copy. In the end, the \c run() member should be
658
  /// called.
659
  ///
660
  /// The next code copies a graph with several data:
661
  ///\code
662
  ///  GraphCopy<NewGraph, OrigGraph> dc(new_graph, orig_graph);
663
  ///  // create a reference for the nodes
664
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
665
  ///  dc.nodeRef(nr);
666
  ///  // create a cross reference (inverse) for the edges
667
  ///  NewGraph::EdgeMap<OrigGraph::Arc> ecr(new_graph);
668
  ///  dc.edgeCrossRef(ecr);
669
  ///  // copy an arc map
670
  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
671
  ///  NewGraph::ArcMap<double> namap(new_graph);
672
  ///  dc.arcMap(namap, oamap);
673
  ///  // copy a node
674
  ///  OrigGraph::Node on;
675
  ///  NewGraph::Node nn;
676
  ///  dc.node(nn, on);
677
  ///  // Executions of copy
678
  ///  dc.run();
679
  ///\endcode
680
  template <typename To, typename From>
681
  class GraphCopy {
682
  private:
683

	
684
    typedef typename From::Node Node;
685
    typedef typename From::NodeIt NodeIt;
686
    typedef typename From::Arc Arc;
687
    typedef typename From::ArcIt ArcIt;
688
    typedef typename From::Edge Edge;
689
    typedef typename From::EdgeIt EdgeIt;
690

	
691
    typedef typename To::Node TNode;
692
    typedef typename To::Arc TArc;
693
    typedef typename To::Edge TEdge;
694

	
695
    typedef typename From::template NodeMap<TNode> NodeRefMap;
696
    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
697

	
698
    struct ArcRefMap {
699
      ArcRefMap(const To& to, const From& from,
700
                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
701
        : _to(to), _from(from),
702
          _edge_ref(edge_ref), _node_ref(node_ref) {}
703

	
704
      typedef typename From::Arc Key;
705
      typedef typename To::Arc Value;
706

	
707
      Value operator[](const Key& key) const {
708
        bool forward = _from.u(key) != _from.v(key) ?
709
          _node_ref[_from.source(key)] ==
710
          _to.source(_to.direct(_edge_ref[key], true)) :
711
          _from.direction(key);
712
        return _to.direct(_edge_ref[key], forward);
713
      }
714

	
715
      const To& _to;
716
      const From& _from;
717
      const EdgeRefMap& _edge_ref;
718
      const NodeRefMap& _node_ref;
719
    };
720

	
721

	
722
  public:
723

	
724

	
725
    /// \brief Constructor for the GraphCopy.
726
    ///
727
    /// It copies the content of the \c _from graph into the
728
    /// \c _to graph.
729
    GraphCopy(To& to, const From& from)
730
      : _from(from), _to(to) {}
731

	
732
    /// \brief Destructor of the GraphCopy
733
    ///
734
    /// Destructor of the GraphCopy
735
    ~GraphCopy() {
736
      for (int i = 0; i < int(_node_maps.size()); ++i) {
737
        delete _node_maps[i];
738
      }
739
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
740
        delete _arc_maps[i];
741
      }
742
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
743
        delete _edge_maps[i];
744
      }
745

	
746
    }
747

	
748
    /// \brief Copies the node references into the given map.
749
    ///
750
    /// Copies the node references into the given map.
751
    template <typename NodeRef>
752
    GraphCopy& nodeRef(NodeRef& map) {
753
      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
754
                           NodeRefMap, NodeRef>(map));
755
      return *this;
756
    }
757

	
758
    /// \brief Copies the node cross references into the given map.
759
    ///
760
    ///  Copies the node cross references (reverse references) into
761
    ///  the given map.
762
    template <typename NodeCrossRef>
763
    GraphCopy& nodeCrossRef(NodeCrossRef& map) {
764
      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
765
                           NodeRefMap, NodeCrossRef>(map));
766
      return *this;
767
    }
768

	
769
    /// \brief Make copy of the given map.
770
    ///
771
    /// Makes copy of the given map for the newly created graph.
772
    /// The new map's key type is the to graph's node type,
773
    /// and the copied map's key type is the from graph's node
774
    /// type.
775
    template <typename ToMap, typename FromMap>
776
    GraphCopy& nodeMap(ToMap& tmap, const FromMap& map) {
777
      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
778
                           NodeRefMap, ToMap, FromMap>(tmap, map));
779
      return *this;
780
    }
781

	
782
    /// \brief Make a copy of the given node.
783
    ///
784
    /// Make a copy of the given node.
785
    GraphCopy& node(TNode& tnode, const Node& snode) {
786
      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
787
                           NodeRefMap, TNode>(tnode, snode));
788
      return *this;
789
    }
790

	
791
    /// \brief Copies the arc references into the given map.
792
    ///
793
    /// Copies the arc references into the given map.
794
    template <typename ArcRef>
795
    GraphCopy& arcRef(ArcRef& map) {
796
      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
797
                          ArcRefMap, ArcRef>(map));
798
      return *this;
799
    }
800

	
801
    /// \brief Copies the arc cross references into the given map.
802
    ///
803
    ///  Copies the arc cross references (reverse references) into
804
    ///  the given map.
805
    template <typename ArcCrossRef>
806
    GraphCopy& arcCrossRef(ArcCrossRef& map) {
807
      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
808
                          ArcRefMap, ArcCrossRef>(map));
809
      return *this;
810
    }
811

	
812
    /// \brief Make copy of the given map.
813
    ///
814
    /// Makes copy of the given map for the newly created graph.
815
    /// The new map's key type is the to graph's arc type,
816
    /// and the copied map's key type is the from graph's arc
817
    /// type.
818
    template <typename ToMap, typename FromMap>
819
    GraphCopy& arcMap(ToMap& tmap, const FromMap& map) {
820
      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
821
                          ArcRefMap, ToMap, FromMap>(tmap, map));
822
      return *this;
823
    }
824

	
825
    /// \brief Make a copy of the given arc.
826
    ///
827
    /// Make a copy of the given arc.
828
    GraphCopy& arc(TArc& tarc, const Arc& sarc) {
829
      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
830
                          ArcRefMap, TArc>(tarc, sarc));
831
      return *this;
832
    }
833

	
834
    /// \brief Copies the edge references into the given map.
835
    ///
836
    /// Copies the edge references into the given map.
837
    template <typename EdgeRef>
838
    GraphCopy& edgeRef(EdgeRef& map) {
839
      _edge_maps.push_back(new _core_bits::RefCopy<From, Edge,
840
                           EdgeRefMap, EdgeRef>(map));
841
      return *this;
842
    }
843

	
844
    /// \brief Copies the edge cross references into the given map.
845
    ///
846
    /// Copies the edge cross references (reverse
847
    /// references) into the given map.
848
    template <typename EdgeCrossRef>
849
    GraphCopy& edgeCrossRef(EdgeCrossRef& map) {
850
      _edge_maps.push_back(new _core_bits::CrossRefCopy<From,
851
                           Edge, EdgeRefMap, EdgeCrossRef>(map));
852
      return *this;
853
    }
854

	
855
    /// \brief Make copy of the given map.
856
    ///
857
    /// Makes copy of the given map for the newly created graph.
858
    /// The new map's key type is the to graph's edge type,
859
    /// and the copied map's key type is the from graph's edge
860
    /// type.
861
    template <typename ToMap, typename FromMap>
862
    GraphCopy& edgeMap(ToMap& tmap, const FromMap& map) {
863
      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
864
                           EdgeRefMap, ToMap, FromMap>(tmap, map));
865
      return *this;
866
    }
867

	
868
    /// \brief Make a copy of the given edge.
869
    ///
870
    /// Make a copy of the given edge.
871
    GraphCopy& edge(TEdge& tedge, const Edge& sedge) {
872
      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
873
                           EdgeRefMap, TEdge>(tedge, sedge));
874
      return *this;
875
    }
876

	
877
    /// \brief Executes the copies.
878
    ///
879
    /// Executes the copies.
880
    void run() {
881
      NodeRefMap nodeRefMap(_from);
882
      EdgeRefMap edgeRefMap(_from);
883
      ArcRefMap arcRefMap(_to, _from, edgeRefMap, nodeRefMap);
884
      _core_bits::GraphCopySelector<To>::
885
        copy(_to, _from, nodeRefMap, edgeRefMap);
886
      for (int i = 0; i < int(_node_maps.size()); ++i) {
887
        _node_maps[i]->copy(_from, nodeRefMap);
888
      }
889
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
890
        _edge_maps[i]->copy(_from, edgeRefMap);
891
      }
892
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
893
        _arc_maps[i]->copy(_from, arcRefMap);
894
      }
895
    }
896

	
897
  private:
898

	
899
    const From& _from;
900
    To& _to;
901

	
902
    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
903
    _node_maps;
904

	
905
    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
906
    _arc_maps;
907

	
908
    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
909
    _edge_maps;
910

	
911
  };
912

	
913
  /// \brief Copy a graph to another graph.
914
  ///
915
  /// Copy a graph to another graph. The complete usage of the
916
  /// function is detailed in the GraphCopy class, but a short
917
  /// example shows a basic work:
918
  ///\code
919
  /// copyGraph(trg, src).nodeRef(nr).arcCrossRef(ecr).run();
920
  ///\endcode
921
  ///
922
  /// After the copy the \c nr map will contain the mapping from the
923
  /// nodes of the \c from graph to the nodes of the \c to graph and
924
  /// \c ecr will contain the mapping from the arcs of the \c to graph
925
  /// to the arcs of the \c from graph.
926
  ///
927
  /// \see GraphCopy
928
  template <typename To, typename From>
929
  GraphCopy<To, From>
930
  copyGraph(To& to, const From& from) {
931
    return GraphCopy<To, From>(to, from);
932
  }
933

	
934
  namespace _core_bits {
935

	
936
    template <typename Graph, typename Enable = void>
937
    struct FindArcSelector {
938
      typedef typename Graph::Node Node;
939
      typedef typename Graph::Arc Arc;
940
      static Arc find(const Graph &g, Node u, Node v, Arc e) {
941
        if (e == INVALID) {
942
          g.firstOut(e, u);
943
        } else {
944
          g.nextOut(e);
945
        }
946
        while (e != INVALID && g.target(e) != v) {
947
          g.nextOut(e);
948
        }
949
        return e;
950
      }
951
    };
952

	
953
    template <typename Graph>
954
    struct FindArcSelector<
955
      Graph,
956
      typename enable_if<typename Graph::FindEdgeTag, void>::type>
957
    {
958
      typedef typename Graph::Node Node;
959
      typedef typename Graph::Arc Arc;
960
      static Arc find(const Graph &g, Node u, Node v, Arc prev) {
961
        return g.findArc(u, v, prev);
962
      }
963
    };
964
  }
965

	
966
  /// \brief Finds an arc between two nodes of a graph.
967
  ///
968
  /// Finds an arc from node \c u to node \c v in graph \c g.
969
  ///
970
  /// If \c prev is \ref INVALID (this is the default value), then
971
  /// it finds the first arc from \c u to \c v. Otherwise it looks for
972
  /// the next arc from \c u to \c v after \c prev.
973
  /// \return The found arc or \ref INVALID if there is no such an arc.
974
  ///
975
  /// Thus you can iterate through each arc from \c u to \c v as it follows.
976
  ///\code
977
  /// for(Arc e=findArc(g,u,v);e!=INVALID;e=findArc(g,u,v,e)) {
978
  ///   ...
979
  /// }
980
  ///\endcode
981
  ///
982
  ///\sa ArcLookUp
983
  ///\sa AllArcLookUp
984
  ///\sa DynArcLookUp
985
  ///\sa ConArcIt
986
  template <typename Graph>
987
  inline typename Graph::Arc
988
  findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v,
989
          typename Graph::Arc prev = INVALID) {
990
    return _core_bits::FindArcSelector<Graph>::find(g, u, v, prev);
991
  }
992

	
993
  /// \brief Iterator for iterating on arcs connected the same nodes.
994
  ///
995
  /// Iterator for iterating on arcs connected the same nodes. It is
996
  /// higher level interface for the findArc() function. You can
997
  /// use it the following way:
998
  ///\code
999
  /// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) {
1000
  ///   ...
1001
  /// }
1002
  ///\endcode
1003
  ///
1004
  ///\sa findArc()
1005
  ///\sa ArcLookUp
1006
  ///\sa AllArcLookUp
1007
  ///\sa DynArcLookUp
1008
  template <typename _Graph>
1009
  class ConArcIt : public _Graph::Arc {
1010
  public:
1011

	
1012
    typedef _Graph Graph;
1013
    typedef typename Graph::Arc Parent;
1014

	
1015
    typedef typename Graph::Arc Arc;
1016
    typedef typename Graph::Node Node;
1017

	
1018
    /// \brief Constructor.
1019
    ///
1020
    /// Construct a new ConArcIt iterating on the arcs which
1021
    /// connects the \c u and \c v node.
1022
    ConArcIt(const Graph& g, Node u, Node v) : _graph(g) {
1023
      Parent::operator=(findArc(_graph, u, v));
1024
    }
1025

	
1026
    /// \brief Constructor.
1027
    ///
1028
    /// Construct a new ConArcIt which continues the iterating from
1029
    /// the \c e arc.
1030
    ConArcIt(const Graph& g, Arc a) : Parent(a), _graph(g) {}
1031

	
1032
    /// \brief Increment operator.
1033
    ///
1034
    /// It increments the iterator and gives back the next arc.
1035
    ConArcIt& operator++() {
1036
      Parent::operator=(findArc(_graph, _graph.source(*this),
1037
                                _graph.target(*this), *this));
1038
      return *this;
1039
    }
1040
  private:
1041
    const Graph& _graph;
1042
  };
1043

	
1044
  namespace _core_bits {
1045

	
1046
    template <typename Graph, typename Enable = void>
1047
    struct FindEdgeSelector {
1048
      typedef typename Graph::Node Node;
1049
      typedef typename Graph::Edge Edge;
1050
      static Edge find(const Graph &g, Node u, Node v, Edge e) {
1051
        bool b;
1052
        if (u != v) {
1053
          if (e == INVALID) {
1054
            g.firstInc(e, b, u);
1055
          } else {
1056
            b = g.u(e) == u;
1057
            g.nextInc(e, b);
1058
          }
1059
          while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) {
1060
            g.nextInc(e, b);
1061
          }
1062
        } else {
1063
          if (e == INVALID) {
1064
            g.firstInc(e, b, u);
1065
          } else {
1066
            b = true;
1067
            g.nextInc(e, b);
1068
          }
1069
          while (e != INVALID && (!b || g.v(e) != v)) {
1070
            g.nextInc(e, b);
1071
          }
1072
        }
1073
        return e;
1074
      }
1075
    };
1076

	
1077
    template <typename Graph>
1078
    struct FindEdgeSelector<
1079
      Graph,
1080
      typename enable_if<typename Graph::FindEdgeTag, void>::type>
1081
    {
1082
      typedef typename Graph::Node Node;
1083
      typedef typename Graph::Edge Edge;
1084
      static Edge find(const Graph &g, Node u, Node v, Edge prev) {
1085
        return g.findEdge(u, v, prev);
1086
      }
1087
    };
1088
  }
1089

	
1090
  /// \brief Finds an edge between two nodes of a graph.
1091
  ///
1092
  /// Finds an edge from node \c u to node \c v in graph \c g.
1093
  /// If the node \c u and node \c v is equal then each loop edge
1094
  /// will be enumerated once.
1095
  ///
1096
  /// If \c prev is \ref INVALID (this is the default value), then
1097
  /// it finds the first arc from \c u to \c v. Otherwise it looks for
1098
  /// the next arc from \c u to \c v after \c prev.
1099
  /// \return The found arc or \ref INVALID if there is no such an arc.
1100
  ///
1101
  /// Thus you can iterate through each arc from \c u to \c v as it follows.
1102
  ///\code
1103
  /// for(Edge e = findEdge(g,u,v); e != INVALID;
1104
  ///     e = findEdge(g,u,v,e)) {
1105
  ///   ...
1106
  /// }
1107
  ///\endcode
1108
  ///
1109
  ///\sa ConEdgeIt
1110

	
1111
  template <typename Graph>
1112
  inline typename Graph::Edge
1113
  findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1114
            typename Graph::Edge p = INVALID) {
1115
    return _core_bits::FindEdgeSelector<Graph>::find(g, u, v, p);
1116
  }
1117

	
1118
  /// \brief Iterator for iterating on edges connected the same nodes.
1119
  ///
1120
  /// Iterator for iterating on edges connected the same nodes. It is
1121
  /// higher level interface for the findEdge() function. You can
1122
  /// use it the following way:
1123
  ///\code
1124
  /// for (ConEdgeIt<Graph> it(g, src, trg); it != INVALID; ++it) {
1125
  ///   ...
1126
  /// }
1127
  ///\endcode
1128
  ///
1129
  ///\sa findEdge()
1130
  template <typename _Graph>
1131
  class ConEdgeIt : public _Graph::Edge {
1132
  public:
1133

	
1134
    typedef _Graph Graph;
1135
    typedef typename Graph::Edge Parent;
1136

	
1137
    typedef typename Graph::Edge Edge;
1138
    typedef typename Graph::Node Node;
1139

	
1140
    /// \brief Constructor.
1141
    ///
1142
    /// Construct a new ConEdgeIt iterating on the edges which
1143
    /// connects the \c u and \c v node.
1144
    ConEdgeIt(const Graph& g, Node u, Node v) : _graph(g) {
1145
      Parent::operator=(findEdge(_graph, u, v));
1146
    }
1147

	
1148
    /// \brief Constructor.
1149
    ///
1150
    /// Construct a new ConEdgeIt which continues the iterating from
1151
    /// the \c e edge.
1152
    ConEdgeIt(const Graph& g, Edge e) : Parent(e), _graph(g) {}
1153

	
1154
    /// \brief Increment operator.
1155
    ///
1156
    /// It increments the iterator and gives back the next edge.
1157
    ConEdgeIt& operator++() {
1158
      Parent::operator=(findEdge(_graph, _graph.u(*this),
1159
                                 _graph.v(*this), *this));
1160
      return *this;
1161
    }
1162
  private:
1163
    const Graph& _graph;
1164
  };
1165

	
1166

	
1167
  ///Dynamic arc look up between given endpoints.
1168

	
1169
  ///Using this class, you can find an arc in a digraph from a given
1170
  ///source to a given target in amortized time <em>O(log d)</em>,
1171
  ///where <em>d</em> is the out-degree of the source node.
1172
  ///
1173
  ///It is possible to find \e all parallel arcs between two nodes with
1174
  ///the \c findFirst() and \c findNext() members.
1175
  ///
1176
  ///See the \ref ArcLookUp and \ref AllArcLookUp classes if your
1177
  ///digraph is not changed so frequently.
1178
  ///
1179
  ///This class uses a self-adjusting binary search tree, Sleator's
1180
  ///and Tarjan's Splay tree for guarantee the logarithmic amortized
1181
  ///time bound for arc lookups. This class also guarantees the
1182
  ///optimal time bound in a constant factor for any distribution of
1183
  ///queries.
1184
  ///
1185
  ///\tparam G The type of the underlying digraph.
1186
  ///
1187
  ///\sa ArcLookUp
1188
  ///\sa AllArcLookUp
1189
  template<class G>
1190
  class DynArcLookUp
1191
    : protected ItemSetTraits<G, typename G::Arc>::ItemNotifier::ObserverBase
1192
  {
1193
  public:
1194
    typedef typename ItemSetTraits<G, typename G::Arc>
1195
    ::ItemNotifier::ObserverBase Parent;
1196

	
1197
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
1198
    typedef G Digraph;
1199

	
1200
  protected:
1201

	
1202
    class AutoNodeMap : public ItemSetTraits<G, Node>::template Map<Arc>::Type {
1203
    public:
1204

	
1205
      typedef typename ItemSetTraits<G, Node>::template Map<Arc>::Type Parent;
1206

	
1207
      AutoNodeMap(const G& digraph) : Parent(digraph, INVALID) {}
1208

	
1209
      virtual void add(const Node& node) {
1210
        Parent::add(node);
1211
        Parent::set(node, INVALID);
1212
      }
1213

	
1214
      virtual void add(const std::vector<Node>& nodes) {
1215
        Parent::add(nodes);
1216
        for (int i = 0; i < int(nodes.size()); ++i) {
1217
          Parent::set(nodes[i], INVALID);
1218
        }
1219
      }
1220

	
1221
      virtual void build() {
1222
        Parent::build();
1223
        Node it;
1224
        typename Parent::Notifier* nf = Parent::notifier();
1225
        for (nf->first(it); it != INVALID; nf->next(it)) {
1226
          Parent::set(it, INVALID);
1227
        }
1228
      }
1229
    };
1230

	
1231
    const Digraph &_g;
1232
    AutoNodeMap _head;
1233
    typename Digraph::template ArcMap<Arc> _parent;
1234
    typename Digraph::template ArcMap<Arc> _left;
1235
    typename Digraph::template ArcMap<Arc> _right;
1236

	
1237
    class ArcLess {
1238
      const Digraph &g;
1239
    public:
1240
      ArcLess(const Digraph &_g) : g(_g) {}
1241
      bool operator()(Arc a,Arc b) const
1242
      {
1243
        return g.target(a)<g.target(b);
1244
      }
1245
    };
1246

	
1247
  public:
1248

	
1249
    ///Constructor
1250

	
1251
    ///Constructor.
1252
    ///
1253
    ///It builds up the search database.
1254
    DynArcLookUp(const Digraph &g)
1255
      : _g(g),_head(g),_parent(g),_left(g),_right(g)
1256
    {
1257
      Parent::attach(_g.notifier(typename Digraph::Arc()));
1258
      refresh();
1259
    }
1260

	
1261
  protected:
1262

	
1263
    virtual void add(const Arc& arc) {
1264
      insert(arc);
1265
    }
1266

	
1267
    virtual void add(const std::vector<Arc>& arcs) {
1268
      for (int i = 0; i < int(arcs.size()); ++i) {
1269
        insert(arcs[i]);
1270
      }
1271
    }
1272

	
1273
    virtual void erase(const Arc& arc) {
1274
      remove(arc);
1275
    }
1276

	
1277
    virtual void erase(const std::vector<Arc>& arcs) {
1278
      for (int i = 0; i < int(arcs.size()); ++i) {
1279
        remove(arcs[i]);
1280
      }
1281
    }
1282

	
1283
    virtual void build() {
1284
      refresh();
1285
    }
1286

	
1287
    virtual void clear() {
1288
      for(NodeIt n(_g);n!=INVALID;++n) {
1289
        _head.set(n, INVALID);
1290
      }
1291
    }
1292

	
1293
    void insert(Arc arc) {
1294
      Node s = _g.source(arc);
1295
      Node t = _g.target(arc);
1296
      _left.set(arc, INVALID);
1297
      _right.set(arc, INVALID);
1298

	
1299
      Arc e = _head[s];
1300
      if (e == INVALID) {
1301
        _head.set(s, arc);
1302
        _parent.set(arc, INVALID);
1303
        return;
1304
      }
1305
      while (true) {
1306
        if (t < _g.target(e)) {
1307
          if (_left[e] == INVALID) {
1308
            _left.set(e, arc);
1309
            _parent.set(arc, e);
1310
            splay(arc);
1311
            return;
1312
          } else {
1313
            e = _left[e];
1314
          }
1315
        } else {
1316
          if (_right[e] == INVALID) {
1317
            _right.set(e, arc);
1318
            _parent.set(arc, e);
1319
            splay(arc);
1320
            return;
1321
          } else {
1322
            e = _right[e];
1323
          }
1324
        }
1325
      }
1326
    }
1327

	
1328
    void remove(Arc arc) {
1329
      if (_left[arc] == INVALID) {
1330
        if (_right[arc] != INVALID) {
1331
          _parent.set(_right[arc], _parent[arc]);
1332
        }
1333
        if (_parent[arc] != INVALID) {
1334
          if (_left[_parent[arc]] == arc) {
1335
            _left.set(_parent[arc], _right[arc]);
1336
          } else {
1337
            _right.set(_parent[arc], _right[arc]);
1338
          }
1339
        } else {
1340
          _head.set(_g.source(arc), _right[arc]);
1341
        }
1342
      } else if (_right[arc] == INVALID) {
1343
        _parent.set(_left[arc], _parent[arc]);
1344
        if (_parent[arc] != INVALID) {
1345
          if (_left[_parent[arc]] == arc) {
1346
            _left.set(_parent[arc], _left[arc]);
1347
          } else {
1348
            _right.set(_parent[arc], _left[arc]);
1349
          }
1350
        } else {
1351
          _head.set(_g.source(arc), _left[arc]);
1352
        }
1353
      } else {
1354
        Arc e = _left[arc];
1355
        if (_right[e] != INVALID) {
1356
          e = _right[e];
1357
          while (_right[e] != INVALID) {
1358
            e = _right[e];
1359
          }
1360
          Arc s = _parent[e];
1361
          _right.set(_parent[e], _left[e]);
1362
          if (_left[e] != INVALID) {
1363
            _parent.set(_left[e], _parent[e]);
1364
          }
1365

	
1366
          _left.set(e, _left[arc]);
1367
          _parent.set(_left[arc], e);
1368
          _right.set(e, _right[arc]);
1369
          _parent.set(_right[arc], e);
1370

	
1371
          _parent.set(e, _parent[arc]);
1372
          if (_parent[arc] != INVALID) {
1373
            if (_left[_parent[arc]] == arc) {
1374
              _left.set(_parent[arc], e);
1375
            } else {
1376
              _right.set(_parent[arc], e);
1377
            }
1378
          }
1379
          splay(s);
1380
        } else {
1381
          _right.set(e, _right[arc]);
1382
          _parent.set(_right[arc], e);
1383

	
1384
          if (_parent[arc] != INVALID) {
1385
            if (_left[_parent[arc]] == arc) {
1386
              _left.set(_parent[arc], e);
1387
            } else {
1388
              _right.set(_parent[arc], e);
1389
            }
1390
          } else {
1391
            _head.set(_g.source(arc), e);
1392
          }
1393
        }
1394
      }
1395
    }
1396

	
1397
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1398
    {
1399
      int m=(a+b)/2;
1400
      Arc me=v[m];
1401
      if (a < m) {
1402
        Arc left = refreshRec(v,a,m-1);
1403
        _left.set(me, left);
1404
        _parent.set(left, me);
1405
      } else {
1406
        _left.set(me, INVALID);
1407
      }
1408
      if (m < b) {
1409
        Arc right = refreshRec(v,m+1,b);
1410
        _right.set(me, right);
1411
        _parent.set(right, me);
1412
      } else {
1413
        _right.set(me, INVALID);
1414
      }
1415
      return me;
1416
    }
1417

	
1418
    void refresh() {
1419
      for(NodeIt n(_g);n!=INVALID;++n) {
1420
        std::vector<Arc> v;
1421
        for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
1422
        if(v.size()) {
1423
          std::sort(v.begin(),v.end(),ArcLess(_g));
1424
          Arc head = refreshRec(v,0,v.size()-1);
1425
          _head.set(n, head);
1426
          _parent.set(head, INVALID);
1427
        }
1428
        else _head.set(n, INVALID);
1429
      }
1430
    }
1431

	
1432
    void zig(Arc v) {
1433
      Arc w = _parent[v];
1434
      _parent.set(v, _parent[w]);
1435
      _parent.set(w, v);
1436
      _left.set(w, _right[v]);
1437
      _right.set(v, w);
1438
      if (_parent[v] != INVALID) {
1439
        if (_right[_parent[v]] == w) {
1440
          _right.set(_parent[v], v);
1441
        } else {
1442
          _left.set(_parent[v], v);
1443
        }
1444
      }
1445
      if (_left[w] != INVALID){
1446
        _parent.set(_left[w], w);
1447
      }
1448
    }
1449

	
1450
    void zag(Arc v) {
1451
      Arc w = _parent[v];
1452
      _parent.set(v, _parent[w]);
1453
      _parent.set(w, v);
1454
      _right.set(w, _left[v]);
1455
      _left.set(v, w);
1456
      if (_parent[v] != INVALID){
1457
        if (_left[_parent[v]] == w) {
1458
          _left.set(_parent[v], v);
1459
        } else {
1460
          _right.set(_parent[v], v);
1461
        }
1462
      }
1463
      if (_right[w] != INVALID){
1464
        _parent.set(_right[w], w);
1465
      }
1466
    }
1467

	
1468
    void splay(Arc v) {
1469
      while (_parent[v] != INVALID) {
1470
        if (v == _left[_parent[v]]) {
1471
          if (_parent[_parent[v]] == INVALID) {
1472
            zig(v);
1473
          } else {
1474
            if (_parent[v] == _left[_parent[_parent[v]]]) {
1475
              zig(_parent[v]);
1476
              zig(v);
1477
            } else {
1478
              zig(v);
1479
              zag(v);
1480
            }
1481
          }
1482
        } else {
1483
          if (_parent[_parent[v]] == INVALID) {
1484
            zag(v);
1485
          } else {
1486
            if (_parent[v] == _left[_parent[_parent[v]]]) {
1487
              zag(v);
1488
              zig(v);
1489
            } else {
1490
              zag(_parent[v]);
1491
              zag(v);
1492
            }
1493
          }
1494
        }
1495
      }
1496
      _head[_g.source(v)] = v;
1497
    }
1498

	
1499

	
1500
  public:
1501

	
1502
    ///Find an arc between two nodes.
1503

	
1504
    ///Find an arc between two nodes in time <em>O(</em>log<em>d)</em>, where
1505
    /// <em>d</em> is the number of outgoing arcs of \c s.
1506
    ///\param s The source node
1507
    ///\param t The target node
1508
    ///\return An arc from \c s to \c t if there exists,
1509
    ///\ref INVALID otherwise.
1510
    Arc operator()(Node s, Node t) const
1511
    {
1512
      Arc a = _head[s];
1513
      while (true) {
1514
        if (_g.target(a) == t) {
1515
          const_cast<DynArcLookUp&>(*this).splay(a);
1516
          return a;
1517
        } else if (t < _g.target(a)) {
1518
          if (_left[a] == INVALID) {
1519
            const_cast<DynArcLookUp&>(*this).splay(a);
1520
            return INVALID;
1521
          } else {
1522
            a = _left[a];
1523
          }
1524
        } else  {
1525
          if (_right[a] == INVALID) {
1526
            const_cast<DynArcLookUp&>(*this).splay(a);
1527
            return INVALID;
1528
          } else {
1529
            a = _right[a];
1530
          }
1531
        }
1532
      }
1533
    }
1534

	
1535
    ///Find the first arc between two nodes.
1536

	
1537
    ///Find the first arc between two nodes in time
1538
    /// <em>O(</em>log<em>d)</em>, where <em>d</em> is the number of
1539
    /// outgoing arcs of \c s.
1540
    ///\param s The source node
1541
    ///\param t The target node
1542
    ///\return An arc from \c s to \c t if there exists, \ref INVALID
1543
    /// otherwise.
1544
    Arc findFirst(Node s, Node t) const
1545
    {
1546
      Arc a = _head[s];
1547
      Arc r = INVALID;
1548
      while (true) {
1549
        if (_g.target(a) < t) {
1550
          if (_right[a] == INVALID) {
1551
            const_cast<DynArcLookUp&>(*this).splay(a);
1552
            return r;
1553
          } else {
1554
            a = _right[a];
1555
          }
1556
        } else {
1557
          if (_g.target(a) == t) {
1558
            r = a;
1559
          }
1560
          if (_left[a] == INVALID) {
1561
            const_cast<DynArcLookUp&>(*this).splay(a);
1562
            return r;
1563
          } else {
1564
            a = _left[a];
1565
          }
1566
        }
1567
      }
1568
    }
1569

	
1570
    ///Find the next arc between two nodes.
1571

	
1572
    ///Find the next arc between two nodes in time
1573
    /// <em>O(</em>log<em>d)</em>, where <em>d</em> is the number of
1574
    /// outgoing arcs of \c s.
1575
    ///\param s The source node
1576
    ///\param t The target node
1577
    ///\return An arc from \c s to \c t if there exists, \ref INVALID
1578
    /// otherwise.
1579

	
1580
    ///\note If \c e is not the result of the previous \c findFirst()
1581
    ///operation then the amorized time bound can not be guaranteed.
1582
#ifdef DOXYGEN
1583
    Arc findNext(Node s, Node t, Arc a) const
1584
#else
1585
    Arc findNext(Node, Node t, Arc a) const
1586
#endif
1587
    {
1588
      if (_right[a] != INVALID) {
1589
        a = _right[a];
1590
        while (_left[a] != INVALID) {
1591
          a = _left[a];
1592
        }
1593
        const_cast<DynArcLookUp&>(*this).splay(a);
1594
      } else {
1595
        while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
1596
          a = _parent[a];
1597
        }
1598
        if (_parent[a] == INVALID) {
1599
          return INVALID;
1600
        } else {
1601
          a = _parent[a];
1602
          const_cast<DynArcLookUp&>(*this).splay(a);
1603
        }
1604
      }
1605
      if (_g.target(a) == t) return a;
1606
      else return INVALID;
1607
    }
1608

	
1609
  };
1610

	
1611
  ///Fast arc look up between given endpoints.
1612

	
1613
  ///Using this class, you can find an arc in a digraph from a given
1614
  ///source to a given target in time <em>O(log d)</em>,
1615
  ///where <em>d</em> is the out-degree of the source node.
1616
  ///
1617
  ///It is not possible to find \e all parallel arcs between two nodes.
1618
  ///Use \ref AllArcLookUp for this purpose.
1619
  ///
1620
  ///\warning This class is static, so you should refresh() (or at least
1621
  ///refresh(Node)) this data structure
1622
  ///whenever the digraph changes. This is a time consuming (superlinearly
1623
  ///proportional (<em>O(m</em>log<em>m)</em>) to the number of arcs).
1624
  ///
1625
  ///\tparam G The type of the underlying digraph.
1626
  ///
1627
  ///\sa DynArcLookUp
1628
  ///\sa AllArcLookUp
1629
  template<class G>
1630
  class ArcLookUp
1631
  {
1632
  public:
1633
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
1634
    typedef G Digraph;
1635

	
1636
  protected:
1637
    const Digraph &_g;
1638
    typename Digraph::template NodeMap<Arc> _head;
1639
    typename Digraph::template ArcMap<Arc> _left;
1640
    typename Digraph::template ArcMap<Arc> _right;
1641

	
1642
    class ArcLess {
1643
      const Digraph &g;
1644
    public:
1645
      ArcLess(const Digraph &_g) : g(_g) {}
1646
      bool operator()(Arc a,Arc b) const
1647
      {
1648
        return g.target(a)<g.target(b);
1649
      }
1650
    };
1651

	
1652
  public:
1653

	
1654
    ///Constructor
1655

	
1656
    ///Constructor.
1657
    ///
1658
    ///It builds up the search database, which remains valid until the digraph
1659
    ///changes.
1660
    ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();}
1661

	
1662
  private:
1663
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1664
    {
1665
      int m=(a+b)/2;
1666
      Arc me=v[m];
1667
      _left[me] = a<m?refreshRec(v,a,m-1):INVALID;
1668
      _right[me] = m<b?refreshRec(v,m+1,b):INVALID;
1669
      return me;
1670
    }
1671
  public:
1672
    ///Refresh the data structure at a node.
1673

	
1674
    ///Build up the search database of node \c n.
1675
    ///
1676
    ///It runs in time <em>O(d</em>log<em>d)</em>, where <em>d</em> is
1677
    ///the number of the outgoing arcs of \c n.
1678
    void refresh(Node n)
1679
    {
1680
      std::vector<Arc> v;
1681
      for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
1682
      if(v.size()) {
1683
        std::sort(v.begin(),v.end(),ArcLess(_g));
1684
        _head[n]=refreshRec(v,0,v.size()-1);
1685
      }
1686
      else _head[n]=INVALID;
1687
    }
1688
    ///Refresh the full data structure.
1689

	
1690
    ///Build up the full search database. In fact, it simply calls
1691
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1692
    ///
1693
    ///It runs in time <em>O(m</em>log<em>D)</em>, where <em>m</em> is
1694
    ///the number of the arcs of \c n and <em>D</em> is the maximum
1695
    ///out-degree of the digraph.
1696

	
1697
    void refresh()
1698
    {
1699
      for(NodeIt n(_g);n!=INVALID;++n) refresh(n);
1700
    }
1701

	
1702
    ///Find an arc between two nodes.
1703

	
1704
    ///Find an arc between two nodes in time <em>O(</em>log<em>d)</em>, where
1705
    /// <em>d</em> is the number of outgoing arcs of \c s.
1706
    ///\param s The source node
1707
    ///\param t The target node
1708
    ///\return An arc from \c s to \c t if there exists,
1709
    ///\ref INVALID otherwise.
1710
    ///
1711
    ///\warning If you change the digraph, refresh() must be called before using
1712
    ///this operator. If you change the outgoing arcs of
1713
    ///a single node \c n, then
1714
    ///\ref refresh(Node) "refresh(n)" is enough.
1715
    ///
1716
    Arc operator()(Node s, Node t) const
1717
    {
1718
      Arc e;
1719
      for(e=_head[s];
1720
          e!=INVALID&&_g.target(e)!=t;
1721
          e = t < _g.target(e)?_left[e]:_right[e]) ;
1722
      return e;
1723
    }
1724

	
1725
  };
1726

	
1727
  ///Fast look up of all arcs between given endpoints.
1728

	
1729
  ///This class is the same as \ref ArcLookUp, with the addition
1730
  ///that it makes it possible to find all arcs between given endpoints.
1731
  ///
1732
  ///\warning This class is static, so you should refresh() (or at least
1733
  ///refresh(Node)) this data structure
1734
  ///whenever the digraph changes. This is a time consuming (superlinearly
1735
  ///proportional (<em>O(m</em>log<em>m)</em>) to the number of arcs).
1736
  ///
1737
  ///\tparam G The type of the underlying digraph.
1738
  ///
1739
  ///\sa DynArcLookUp
1740
  ///\sa ArcLookUp
1741
  template<class G>
1742
  class AllArcLookUp : public ArcLookUp<G>
1743
  {
1744
    using ArcLookUp<G>::_g;
1745
    using ArcLookUp<G>::_right;
1746
    using ArcLookUp<G>::_left;
1747
    using ArcLookUp<G>::_head;
1748

	
1749
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
1750
    typedef G Digraph;
1751

	
1752
    typename Digraph::template ArcMap<Arc> _next;
1753

	
1754
    Arc refreshNext(Arc head,Arc next=INVALID)
1755
    {
1756
      if(head==INVALID) return next;
1757
      else {
1758
        next=refreshNext(_right[head],next);
1759
//         _next[head]=next;
1760
        _next[head]=( next!=INVALID && _g.target(next)==_g.target(head))
1761
          ? next : INVALID;
1762
        return refreshNext(_left[head],head);
1763
      }
1764
    }
1765

	
1766
    void refreshNext()
1767
    {
1768
      for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]);
1769
    }
1770

	
1771
  public:
1772
    ///Constructor
1773

	
1774
    ///Constructor.
1775
    ///
1776
    ///It builds up the search database, which remains valid until the digraph
1777
    ///changes.
1778
    AllArcLookUp(const Digraph &g) : ArcLookUp<G>(g), _next(g) {refreshNext();}
1779

	
1780
    ///Refresh the data structure at a node.
1781

	
1782
    ///Build up the search database of node \c n.
1783
    ///
1784
    ///It runs in time <em>O(d</em>log<em>d)</em>, where <em>d</em> is
1785
    ///the number of the outgoing arcs of \c n.
1786

	
1787
    void refresh(Node n)
1788
    {
1789
      ArcLookUp<G>::refresh(n);
1790
      refreshNext(_head[n]);
1791
    }
1792

	
1793
    ///Refresh the full data structure.
1794

	
1795
    ///Build up the full search database. In fact, it simply calls
1796
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1797
    ///
1798
    ///It runs in time <em>O(m</em>log<em>D)</em>, where <em>m</em> is
1799
    ///the number of the arcs of \c n and <em>D</em> is the maximum
1800
    ///out-degree of the digraph.
1801

	
1802
    void refresh()
1803
    {
1804
      for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]);
1805
    }
1806

	
1807
    ///Find an arc between two nodes.
1808

	
1809
    ///Find an arc between two nodes.
1810
    ///\param s The source node
1811
    ///\param t The target node
1812
    ///\param prev The previous arc between \c s and \c t. It it is INVALID or
1813
    ///not given, the operator finds the first appropriate arc.
1814
    ///\return An arc from \c s to \c t after \c prev or
1815
    ///\ref INVALID if there is no more.
1816
    ///
1817
    ///For example, you can count the number of arcs from \c u to \c v in the
1818
    ///following way.
1819
    ///\code
1820
    ///AllArcLookUp<ListDigraph> ae(g);
1821
    ///...
1822
    ///int n=0;
1823
    ///for(Arc e=ae(u,v);e!=INVALID;e=ae(u,v,e)) n++;
1824
    ///\endcode
1825
    ///
1826
    ///Finding the first arc take <em>O(</em>log<em>d)</em> time, where
1827
    /// <em>d</em> is the number of outgoing arcs of \c s. Then, the
1828
    ///consecutive arcs are found in constant time.
1829
    ///
1830
    ///\warning If you change the digraph, refresh() must be called before using
1831
    ///this operator. If you change the outgoing arcs of
1832
    ///a single node \c n, then
1833
    ///\ref refresh(Node) "refresh(n)" is enough.
1834
    ///
1835
#ifdef DOXYGEN
1836
    Arc operator()(Node s, Node t, Arc prev=INVALID) const {}
1837
#else
1838
    using ArcLookUp<G>::operator() ;
1839
    Arc operator()(Node s, Node t, Arc prev) const
1840
    {
1841
      return prev==INVALID?(*this)(s,t):_next[prev];
1842
    }
1843
#endif
1844

	
1845
  };
1846

	
1847
  /// @}
1848

	
1849
} //namespace lemon
1850

	
1851
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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
/// \ingroup demos
20 20
/// \file
21 21
/// \brief Demo of the graph drawing function \ref graphToEps()
22 22
///
23 23
/// This demo program shows examples how to use the function \ref
24 24
/// graphToEps(). It takes no input but simply creates seven
25 25
/// <tt>.eps</tt> files demonstrating the capability of \ref
26 26
/// graphToEps(), and showing how to draw directed graphs,
27 27
/// how to handle parallel egdes, how to change the properties (like
28 28
/// color, shape, size, title etc.) of nodes and arcs individually
29 29
/// using appropriate \ref maps-page "graph maps".
30 30
///
31 31
/// \include graph_to_eps_demo.cc
32 32

	
33 33
#include<lemon/list_graph.h>
34
#include<lemon/graph_utils.h>
35 34
#include<lemon/graph_to_eps.h>
36 35
#include<lemon/math.h>
37 36

	
38 37
using namespace std;
39 38
using namespace lemon;
40 39

	
41 40
int main()
42 41
{
43 42
  Palette palette;
44 43
  Palette paletteW(true);
45 44

	
46 45
  // Create a small digraph
47 46
  ListDigraph g;
48 47
  typedef ListDigraph::Node Node;
49 48
  typedef ListDigraph::NodeIt NodeIt;
50 49
  typedef ListDigraph::Arc Arc;
51 50
  typedef dim2::Point<int> Point;
52 51

	
53 52
  Node n1=g.addNode();
54 53
  Node n2=g.addNode();
55 54
  Node n3=g.addNode();
56 55
  Node n4=g.addNode();
57 56
  Node n5=g.addNode();
58 57

	
59 58
  ListDigraph::NodeMap<Point> coords(g);
60 59
  ListDigraph::NodeMap<double> sizes(g);
61 60
  ListDigraph::NodeMap<int> colors(g);
62 61
  ListDigraph::NodeMap<int> shapes(g);
63 62
  ListDigraph::ArcMap<int> acolors(g);
64 63
  ListDigraph::ArcMap<int> widths(g);
65 64

	
66 65
  coords[n1]=Point(50,50);  sizes[n1]=1; colors[n1]=1; shapes[n1]=0;
67 66
  coords[n2]=Point(50,70);  sizes[n2]=2; colors[n2]=2; shapes[n2]=2;
68 67
  coords[n3]=Point(70,70);  sizes[n3]=1; colors[n3]=3; shapes[n3]=0;
69 68
  coords[n4]=Point(70,50);  sizes[n4]=2; colors[n4]=4; shapes[n4]=1;
70 69
  coords[n5]=Point(85,60);  sizes[n5]=3; colors[n5]=5; shapes[n5]=2;
71 70

	
72 71
  Arc a;
73 72

	
74 73
  a=g.addArc(n1,n2); acolors[a]=0; widths[a]=1;
75 74
  a=g.addArc(n2,n3); acolors[a]=0; widths[a]=1;
76 75
  a=g.addArc(n3,n5); acolors[a]=0; widths[a]=3;
77 76
  a=g.addArc(n5,n4); acolors[a]=0; widths[a]=1;
78 77
  a=g.addArc(n4,n1); acolors[a]=0; widths[a]=1;
79 78
  a=g.addArc(n2,n4); acolors[a]=1; widths[a]=2;
80 79
  a=g.addArc(n3,n4); acolors[a]=2; widths[a]=1;
81 80

	
82 81
  IdMap<ListDigraph,Node> id(g);
83 82

	
84 83
  // Create .eps files showing the digraph with different options
85 84
  cout << "Create 'graph_to_eps_demo_out_1_pure.eps'" << endl;
86 85
  graphToEps(g,"graph_to_eps_demo_out_1_pure.eps").
87 86
    coords(coords).
88 87
    title("Sample .eps figure").
89 88
    copyright("(C) 2003-2008 LEMON Project").
90 89
    run();
91 90

	
92 91
  cout << "Create 'graph_to_eps_demo_out_2.eps'" << endl;
93 92
  graphToEps(g,"graph_to_eps_demo_out_2.eps").
94 93
    coords(coords).
95 94
    title("Sample .eps figure").
96 95
    copyright("(C) 2003-2008 LEMON Project").
97 96
    absoluteNodeSizes().absoluteArcWidths().
98 97
    nodeScale(2).nodeSizes(sizes).
99 98
    nodeShapes(shapes).
100 99
    nodeColors(composeMap(palette,colors)).
101 100
    arcColors(composeMap(palette,acolors)).
102 101
    arcWidthScale(.4).arcWidths(widths).
103 102
    nodeTexts(id).nodeTextSize(3).
104 103
    run();
105 104

	
106 105
  cout << "Create 'graph_to_eps_demo_out_3_arr.eps'" << endl;
107 106
  graphToEps(g,"graph_to_eps_demo_out_3_arr.eps").
108 107
    title("Sample .eps figure (with arrowheads)").
109 108
    copyright("(C) 2003-2008 LEMON Project").
110 109
    absoluteNodeSizes().absoluteArcWidths().
111 110
    nodeColors(composeMap(palette,colors)).
112 111
    coords(coords).
113 112
    nodeScale(2).nodeSizes(sizes).
114 113
    nodeShapes(shapes).
115 114
    arcColors(composeMap(palette,acolors)).
116 115
    arcWidthScale(.4).arcWidths(widths).
117 116
    nodeTexts(id).nodeTextSize(3).
118 117
    drawArrows().arrowWidth(2).arrowLength(2).
119 118
    run();
120 119

	
121 120
  // Add more arcs to the digraph
122 121
  a=g.addArc(n1,n4); acolors[a]=2; widths[a]=1;
123 122
  a=g.addArc(n4,n1); acolors[a]=1; widths[a]=2;
124 123

	
125 124
  a=g.addArc(n1,n2); acolors[a]=1; widths[a]=1;
126 125
  a=g.addArc(n1,n2); acolors[a]=2; widths[a]=1;
127 126
  a=g.addArc(n1,n2); acolors[a]=3; widths[a]=1;
128 127
  a=g.addArc(n1,n2); acolors[a]=4; widths[a]=1;
129 128
  a=g.addArc(n1,n2); acolors[a]=5; widths[a]=1;
130 129
  a=g.addArc(n1,n2); acolors[a]=6; widths[a]=1;
131 130
  a=g.addArc(n1,n2); acolors[a]=7; widths[a]=1;
132 131

	
133 132
  cout << "Create 'graph_to_eps_demo_out_4_par.eps'" << endl;
134 133
  graphToEps(g,"graph_to_eps_demo_out_4_par.eps").
135 134
    title("Sample .eps figure (parallel arcs)").
136 135
    copyright("(C) 2003-2008 LEMON Project").
137 136
    absoluteNodeSizes().absoluteArcWidths().
138 137
    nodeShapes(shapes).
139 138
    coords(coords).
140 139
    nodeScale(2).nodeSizes(sizes).
141 140
    nodeColors(composeMap(palette,colors)).
142 141
    arcColors(composeMap(palette,acolors)).
143 142
    arcWidthScale(.4).arcWidths(widths).
144 143
    nodeTexts(id).nodeTextSize(3).
145 144
    enableParallel().parArcDist(1.5).
146 145
    run();
147 146

	
148 147
  cout << "Create 'graph_to_eps_demo_out_5_par_arr.eps'" << endl;
149 148
  graphToEps(g,"graph_to_eps_demo_out_5_par_arr.eps").
150 149
    title("Sample .eps figure (parallel arcs and arrowheads)").
151 150
    copyright("(C) 2003-2008 LEMON Project").
152 151
    absoluteNodeSizes().absoluteArcWidths().
153 152
    nodeScale(2).nodeSizes(sizes).
154 153
    coords(coords).
155 154
    nodeShapes(shapes).
156 155
    nodeColors(composeMap(palette,colors)).
157 156
    arcColors(composeMap(palette,acolors)).
158 157
    arcWidthScale(.3).arcWidths(widths).
159 158
    nodeTexts(id).nodeTextSize(3).
160 159
    enableParallel().parArcDist(1).
161 160
    drawArrows().arrowWidth(1).arrowLength(1).
162 161
    run();
163 162

	
164 163
  cout << "Create 'graph_to_eps_demo_out_6_par_arr_a4.eps'" << endl;
165 164
  graphToEps(g,"graph_to_eps_demo_out_6_par_arr_a4.eps").
166 165
    title("Sample .eps figure (fits to A4)").
167 166
    copyright("(C) 2003-2008 LEMON Project").
168 167
    scaleToA4().
169 168
    absoluteNodeSizes().absoluteArcWidths().
170 169
    nodeScale(2).nodeSizes(sizes).
171 170
    coords(coords).
172 171
    nodeShapes(shapes).
173 172
    nodeColors(composeMap(palette,colors)).
174 173
    arcColors(composeMap(palette,acolors)).
175 174
    arcWidthScale(.3).arcWidths(widths).
176 175
    nodeTexts(id).nodeTextSize(3).
177 176
    enableParallel().parArcDist(1).
178 177
    drawArrows().arrowWidth(1).arrowLength(1).
179 178
    run();
180 179

	
181 180
  // Create an .eps file showing the colors of a default Palette
182 181
  ListDigraph h;
183 182
  ListDigraph::NodeMap<int> hcolors(h);
184 183
  ListDigraph::NodeMap<Point> hcoords(h);
185 184

	
186 185
  int cols=int(sqrt(double(palette.size())));
187 186
  for(int i=0;i<int(paletteW.size());i++) {
188 187
    Node n=h.addNode();
189 188
    hcoords[n]=Point(1+i%cols,1+i/cols);
190 189
    hcolors[n]=i;
191 190
  }
192 191

	
193 192
  cout << "Create 'graph_to_eps_demo_out_7_colors.eps'" << endl;
194 193
  graphToEps(h,"graph_to_eps_demo_out_7_colors.eps").
195 194
    scale(60).
196 195
    title("Sample .eps figure (Palette demo)").
197 196
    copyright("(C) 2003-2008 LEMON Project").
198 197
    coords(hcoords).
199 198
    absoluteNodeSizes().absoluteArcWidths().
200 199
    nodeScale(.45).
201 200
    distantColorNodeTexts().
202 201
    nodeTexts(hcolors).nodeTextSize(.6).
203 202
    nodeColors(composeMap(paletteW,hcolors)).
204 203
    run();
205 204

	
206 205
  return 0;
207 206
}
Ignore white space 6 line context
1 1
EXTRA_DIST += \
2 2
	lemon/lemon.pc.in \
3 3
	lemon/CMakeLists.txt
4 4

	
5 5
pkgconfig_DATA += lemon/lemon.pc
6 6

	
7 7
lib_LTLIBRARIES += lemon/libemon.la
8 8

	
9 9
lemon_libemon_la_SOURCES = \
10 10
        lemon/arg_parser.cc \
11 11
        lemon/base.cc \
12 12
        lemon/color.cc \
13 13
        lemon/random.cc
14 14

	
15 15

	
16 16
lemon_libemon_la_CXXFLAGS = $(GLPK_CFLAGS) $(CPLEX_CFLAGS) $(SOPLEX_CXXFLAGS)
17 17
lemon_libemon_la_LDFLAGS = $(GLPK_LIBS) $(CPLEX_LIBS) $(SOPLEX_LIBS)
18 18

	
19 19
lemon_HEADERS += \
20 20
        lemon/arg_parser.h \
21 21
	lemon/assert.h \
22 22
        lemon/bfs.h \
23 23
        lemon/bin_heap.h \
24 24
        lemon/color.h \
25 25
	lemon/concept_check.h \
26 26
        lemon/counter.h \
27
	lemon/core.h \
27 28
        lemon/dfs.h \
28 29
        lemon/dijkstra.h \
29 30
        lemon/dim2.h \
30 31
	lemon/error.h \
31 32
        lemon/graph_to_eps.h \
32
	lemon/graph_utils.h \
33 33
	lemon/kruskal.h \
34 34
	lemon/lgf_reader.h \
35 35
	lemon/lgf_writer.h \
36 36
	lemon/list_graph.h \
37 37
	lemon/maps.h \
38 38
	lemon/math.h \
39 39
	lemon/path.h \
40 40
        lemon/random.h \
41 41
	lemon/smart_graph.h \
42 42
        lemon/time_measure.h \
43 43
        lemon/tolerance.h \
44 44
	lemon/unionfind.h
45 45

	
46 46
bits_HEADERS += \
47 47
	lemon/bits/alteration_notifier.h \
48 48
	lemon/bits/array_map.h \
49 49
	lemon/bits/base_extender.h \
50 50
        lemon/bits/bezier.h \
51 51
	lemon/bits/default_map.h \
52
        lemon/bits/enable_if.h \
52 53
	lemon/bits/graph_extender.h \
53
        lemon/bits/invalid.h \
54 54
	lemon/bits/map_extender.h \
55 55
	lemon/bits/path_dump.h \
56 56
	lemon/bits/traits.h \
57
        lemon/bits/utility.h \
58 57
	lemon/bits/vector_map.h
59 58

	
60 59
concept_HEADERS += \
61 60
	lemon/concepts/digraph.h \
62 61
	lemon/concepts/graph.h \
63 62
	lemon/concepts/graph_components.h \
64 63
	lemon/concepts/heap.h \
65 64
	lemon/concepts/maps.h \
66 65
	lemon/concepts/path.h
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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
///\file
20 20
///\brief Some basic non-inline functions and static global data.
21 21

	
22 22
#include<lemon/tolerance.h>
23
#include<lemon/bits/invalid.h>
23
#include<lemon/core.h>
24 24
namespace lemon {
25 25

	
26 26
  float Tolerance<float>::def_epsilon = 1e-4;
27 27
  double Tolerance<double>::def_epsilon = 1e-10;
28 28
  long double Tolerance<long double>::def_epsilon = 1e-14;
29 29

	
30 30
#ifndef LEMON_ONLY_TEMPLATES
31 31
  const Invalid INVALID = Invalid();
32 32
#endif
33 33

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

	
19 19
#ifndef LEMON_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
#include <lemon/graph_utils.h>
28 27
#include <lemon/bits/path_dump.h>
29
#include <lemon/bits/invalid.h>
28
#include <lemon/core.h>
30 29
#include <lemon/error.h>
31 30
#include <lemon/maps.h>
32 31

	
33 32
namespace lemon {
34 33

	
35 34

	
36 35

	
37 36
  ///Default traits class of Bfs class.
38 37

	
39 38
  ///Default traits class of Bfs class.
40 39
  ///\tparam GR Digraph type.
41 40
  template<class GR>
42 41
  struct BfsDefaultTraits
43 42
  {
44 43
    ///The digraph type the algorithm runs on.
45 44
    typedef GR Digraph;
46 45
    ///\brief The type of the map that stores the last
47 46
    ///arcs of the shortest paths.
48 47
    ///
49 48
    ///The type of the map that stores the last
50 49
    ///arcs of the shortest paths.
51 50
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
52 51
    ///
53 52
    typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
54 53
    ///Instantiates a PredMap.
55 54

	
56 55
    ///This function instantiates a \ref PredMap.
57 56
    ///\param G is the digraph, to which we would like to define the PredMap.
58 57
    ///\todo The digraph alone may be insufficient to initialize
59 58
    static PredMap *createPredMap(const GR &G)
60 59
    {
61 60
      return new PredMap(G);
62 61
    }
63 62
    ///The type of the map that indicates which nodes are processed.
64 63

	
65 64
    ///The type of the map that indicates which nodes are processed.
66 65
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
67 66
    ///\todo named parameter to set this type, function to read and write.
68 67
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
69 68
    ///Instantiates a ProcessedMap.
70 69

	
71 70
    ///This function instantiates a \ref ProcessedMap.
72 71
    ///\param g is the digraph, to which
73 72
    ///we would like to define the \ref ProcessedMap
74 73
#ifdef DOXYGEN
75 74
    static ProcessedMap *createProcessedMap(const GR &g)
76 75
#else
77 76
    static ProcessedMap *createProcessedMap(const GR &)
78 77
#endif
79 78
    {
80 79
      return new ProcessedMap();
81 80
    }
82 81
    ///The type of the map that indicates which nodes are reached.
83 82

	
84 83
    ///The type of the map that indicates which nodes are reached.
85 84
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
86 85
    ///\todo named parameter to set this type, function to read and write.
87 86
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
88 87
    ///Instantiates a ReachedMap.
89 88

	
90 89
    ///This function instantiates a \ref ReachedMap.
91 90
    ///\param G is the digraph, to which
92 91
    ///we would like to define the \ref ReachedMap.
93 92
    static ReachedMap *createReachedMap(const GR &G)
94 93
    {
95 94
      return new ReachedMap(G);
96 95
    }
97 96
    ///The type of the map that stores the dists of the nodes.
98 97

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

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

	
114 113
  ///%BFS algorithm class.
115 114

	
116 115
  ///\ingroup search
117 116
  ///This class provides an efficient implementation of the %BFS algorithm.
118 117
  ///
119 118
  ///\tparam GR The digraph type the algorithm runs on. The default value is
120 119
  ///\ref ListDigraph. The value of GR is not used directly by Bfs, it
121 120
  ///is only passed to \ref BfsDefaultTraits.
122 121
  ///\tparam TR Traits class to set various data types used by the algorithm.
123 122
  ///The default traits class is
124 123
  ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
125 124
  ///See \ref BfsDefaultTraits for the documentation of
126 125
  ///a Bfs traits class.
127 126

	
128 127
#ifdef DOXYGEN
129 128
  template <typename GR,
130 129
            typename TR>
131 130
#else
132 131
  template <typename GR=ListDigraph,
133 132
            typename TR=BfsDefaultTraits<GR> >
134 133
#endif
135 134
  class Bfs {
136 135
  public:
137 136
    /**
138 137
     * \brief \ref Exception for uninitialized parameters.
139 138
     *
140 139
     * This error represents problems in the initialization
141 140
     * of the parameters of the algorithms.
142 141
     */
143 142
    class UninitializedParameter : public lemon::UninitializedParameter {
144 143
    public:
145 144
      virtual const char* what() const throw() {
146 145
        return "lemon::Bfs::UninitializedParameter";
147 146
      }
148 147
    };
149 148

	
150 149
    typedef TR Traits;
151 150
    ///The type of the underlying digraph.
152 151
    typedef typename TR::Digraph Digraph;
153 152

	
154 153
    ///\brief The type of the map that stores the last
155 154
    ///arcs of the shortest paths.
156 155
    typedef typename TR::PredMap PredMap;
157 156
    ///The type of the map indicating which nodes are reached.
158 157
    typedef typename TR::ReachedMap ReachedMap;
159 158
    ///The type of the map indicating which nodes are processed.
160 159
    typedef typename TR::ProcessedMap ProcessedMap;
161 160
    ///The type of the map that stores the dists of the nodes.
162 161
    typedef typename TR::DistMap DistMap;
163 162
  private:
164 163

	
165 164
    typedef typename Digraph::Node Node;
166 165
    typedef typename Digraph::NodeIt NodeIt;
167 166
    typedef typename Digraph::Arc Arc;
168 167
    typedef typename Digraph::OutArcIt OutArcIt;
169 168

	
170 169
    /// Pointer to the underlying digraph.
171 170
    const Digraph *G;
172 171
    ///Pointer to the map of predecessors arcs.
173 172
    PredMap *_pred;
174 173
    ///Indicates if \ref _pred is locally allocated (\c true) or not.
175 174
    bool local_pred;
176 175
    ///Pointer to the map of distances.
177 176
    DistMap *_dist;
178 177
    ///Indicates if \ref _dist is locally allocated (\c true) or not.
179 178
    bool local_dist;
180 179
    ///Pointer to the map of reached status of the nodes.
181 180
    ReachedMap *_reached;
182 181
    ///Indicates if \ref _reached is locally allocated (\c true) or not.
183 182
    bool local_reached;
184 183
    ///Pointer to the map of processed status of the nodes.
185 184
    ProcessedMap *_processed;
186 185
    ///Indicates if \ref _processed is locally allocated (\c true) or not.
187 186
    bool local_processed;
188 187

	
189 188
    std::vector<typename Digraph::Node> _queue;
190 189
    int _queue_head,_queue_tail,_queue_next_dist;
191 190
    int _curr_dist;
192 191

	
193 192
    ///Creates the maps if necessary.
194 193

	
195 194
    ///\todo Better memory allocation (instead of new).
196 195
    void create_maps()
197 196
    {
198 197
      if(!_pred) {
199 198
        local_pred = true;
200 199
        _pred = Traits::createPredMap(*G);
201 200
      }
202 201
      if(!_dist) {
203 202
        local_dist = true;
204 203
        _dist = Traits::createDistMap(*G);
205 204
      }
206 205
      if(!_reached) {
207 206
        local_reached = true;
208 207
        _reached = Traits::createReachedMap(*G);
209 208
      }
210 209
      if(!_processed) {
211 210
        local_processed = true;
212 211
        _processed = Traits::createProcessedMap(*G);
213 212
      }
214 213
    }
215 214

	
216 215
  protected:
217 216

	
218 217
    Bfs() {}
219 218

	
220 219
  public:
221 220

	
222 221
    typedef Bfs Create;
223 222

	
224 223
    ///\name Named template parameters
225 224

	
226 225
    ///@{
227 226

	
228 227
    template <class T>
229 228
    struct DefPredMapTraits : public Traits {
230 229
      typedef T PredMap;
231 230
      static PredMap *createPredMap(const Digraph &)
232 231
      {
233 232
        throw UninitializedParameter();
234 233
      }
235 234
    };
236 235
    ///\brief \ref named-templ-param "Named parameter" for setting
237 236
    ///PredMap type
238 237
    ///
239 238
    ///\ref named-templ-param "Named parameter" for setting PredMap type
240 239
    ///
241 240
    template <class T>
242 241
    struct DefPredMap : public Bfs< Digraph, DefPredMapTraits<T> > {
243 242
      typedef Bfs< Digraph, DefPredMapTraits<T> > Create;
244 243
    };
245 244

	
246 245
    template <class T>
247 246
    struct DefDistMapTraits : public Traits {
248 247
      typedef T DistMap;
249 248
      static DistMap *createDistMap(const Digraph &)
250 249
      {
251 250
        throw UninitializedParameter();
252 251
      }
253 252
    };
254 253
    ///\brief \ref named-templ-param "Named parameter" for setting
255 254
    ///DistMap type
256 255
    ///
257 256
    ///\ref named-templ-param "Named parameter" for setting DistMap type
258 257
    ///
259 258
    template <class T>
260 259
    struct DefDistMap : public Bfs< Digraph, DefDistMapTraits<T> > {
261 260
      typedef Bfs< Digraph, DefDistMapTraits<T> > Create;
262 261
    };
263 262

	
264 263
    template <class T>
265 264
    struct DefReachedMapTraits : public Traits {
266 265
      typedef T ReachedMap;
267 266
      static ReachedMap *createReachedMap(const Digraph &)
268 267
      {
269 268
        throw UninitializedParameter();
270 269
      }
271 270
    };
272 271
    ///\brief \ref named-templ-param "Named parameter" for setting
273 272
    ///ReachedMap type
274 273
    ///
275 274
    ///\ref named-templ-param "Named parameter" for setting ReachedMap type
276 275
    ///
277 276
    template <class T>
278 277
    struct DefReachedMap : public Bfs< Digraph, DefReachedMapTraits<T> > {
279 278
      typedef Bfs< Digraph, DefReachedMapTraits<T> > Create;
280 279
    };
281 280

	
282 281
    template <class T>
283 282
    struct DefProcessedMapTraits : public Traits {
284 283
      typedef T ProcessedMap;
285 284
      static ProcessedMap *createProcessedMap(const Digraph &)
286 285
      {
287 286
        throw UninitializedParameter();
288 287
      }
289 288
    };
290 289
    ///\brief \ref named-templ-param "Named parameter" for setting
291 290
    ///ProcessedMap type
292 291
    ///
293 292
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
294 293
    ///
295 294
    template <class T>
296 295
    struct DefProcessedMap : public Bfs< Digraph, DefProcessedMapTraits<T> > {
297 296
      typedef Bfs< Digraph, DefProcessedMapTraits<T> > Create;
298 297
    };
299 298

	
300 299
    struct DefDigraphProcessedMapTraits : public Traits {
301 300
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
302 301
      static ProcessedMap *createProcessedMap(const Digraph &G)
303 302
      {
304 303
        return new ProcessedMap(G);
305 304
      }
306 305
    };
307 306
    ///\brief \ref named-templ-param "Named parameter"
308 307
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
309 308
    ///
310 309
    ///\ref named-templ-param "Named parameter"
311 310
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
312 311
    ///If you don't set it explicitly, it will be automatically allocated.
313 312
    template <class T>
314 313
    struct DefProcessedMapToBeDefaultMap :
315 314
      public Bfs< Digraph, DefDigraphProcessedMapTraits> {
316 315
      typedef Bfs< Digraph, DefDigraphProcessedMapTraits> Create;
317 316
    };
318 317

	
319 318
    ///@}
320 319

	
321 320
  public:
322 321

	
323 322
    ///Constructor.
324 323

	
325 324
    ///\param _G the digraph the algorithm will run on.
326 325
    ///
327 326
    Bfs(const Digraph& _G) :
328 327
      G(&_G),
329 328
      _pred(NULL), local_pred(false),
330 329
      _dist(NULL), local_dist(false),
331 330
      _reached(NULL), local_reached(false),
332 331
      _processed(NULL), local_processed(false)
333 332
    { }
334 333

	
335 334
    ///Destructor.
336 335
    ~Bfs()
337 336
    {
338 337
      if(local_pred) delete _pred;
339 338
      if(local_dist) delete _dist;
340 339
      if(local_reached) delete _reached;
341 340
      if(local_processed) delete _processed;
342 341
    }
343 342

	
344 343
    ///Sets the map storing the predecessor arcs.
345 344

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

	
361 360
    ///Sets the map indicating the reached nodes.
362 361

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

	
378 377
    ///Sets the map indicating the processed nodes.
379 378

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

	
395 394
    ///Sets the map storing the distances calculated by the algorithm.
396 395

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

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

	
19 19
#ifndef LEMON_BITS_ALTERATION_NOTIFIER_H
20 20
#define LEMON_BITS_ALTERATION_NOTIFIER_H
21 21

	
22 22
#include <vector>
23 23
#include <list>
24 24

	
25
#include <lemon/bits/utility.h>
25
#include <lemon/core.h>
26 26

	
27 27
///\ingroup graphbits
28 28
///\file
29 29
///\brief Observer notifier for graph alteration observers.
30 30

	
31 31
namespace lemon {
32 32

	
33 33
  /// \ingroup graphbits
34 34
  ///
35 35
  /// \brief Notifier class to notify observes about alterations in
36 36
  /// a container.
37 37
  ///
38 38
  /// The simple graph's can be refered as two containers, one node container
39 39
  /// and one edge container. But they are not standard containers they
40 40
  /// does not store values directly they are just key continars for more
41 41
  /// value containers which are the node and edge maps.
42 42
  ///
43 43
  /// The graph's node and edge sets can be changed as we add or erase
44 44
  /// nodes and edges in the graph. Lemon would like to handle easily
45 45
  /// that the node and edge maps should contain values for all nodes or
46 46
  /// edges. If we want to check on every indicing if the map contains
47 47
  /// the current indicing key that cause a drawback in the performance
48 48
  /// in the library. We use another solution we notify all maps about
49 49
  /// an alteration in the graph, which cause only drawback on the
50 50
  /// alteration of the graph.
51 51
  ///
52 52
  /// This class provides an interface to the container. The \e first() and \e
53 53
  /// next() member functions make possible to iterate on the keys of the
54 54
  /// container. The \e id() function returns an integer id for each key.
55 55
  /// The \e maxId() function gives back an upper bound of the ids.
56 56
  ///
57 57
  /// For the proper functonality of this class, we should notify it
58 58
  /// about each alteration in the container. The alterations have four type
59 59
  /// as \e add(), \e erase(), \e build() and \e clear(). The \e add() and
60 60
  /// \e erase() signals that only one or few items added or erased to or
61 61
  /// from the graph. If all items are erased from the graph or from an empty
62 62
  /// graph a new graph is builded then it can be signaled with the
63 63
  /// clear() and build() members. Important rule that if we erase items
64 64
  /// from graph we should first signal the alteration and after that erase
65 65
  /// them from the container, on the other way on item addition we should
66 66
  /// first extend the container and just after that signal the alteration.
67 67
  ///
68 68
  /// The alteration can be observed with a class inherited from the
69 69
  /// \e ObserverBase nested class. The signals can be handled with
70 70
  /// overriding the virtual functions defined in the base class.  The
71 71
  /// observer base can be attached to the notifier with the
72 72
  /// \e attach() member and can be detached with detach() function. The
73 73
  /// alteration handlers should not call any function which signals
74 74
  /// an other alteration in the same notifier and should not
75 75
  /// detach any observer from the notifier.
76 76
  ///
77 77
  /// Alteration observers try to be exception safe. If an \e add() or
78 78
  /// a \e clear() function throws an exception then the remaining
79 79
  /// observeres will not be notified and the fulfilled additions will
80 80
  /// be rolled back by calling the \e erase() or \e clear()
81 81
  /// functions. Thence the \e erase() and \e clear() should not throw
82 82
  /// exception. Actullay, it can be throw only
83 83
  /// \ref AlterationObserver::ImmediateDetach ImmediateDetach
84 84
  /// exception which detach the observer from the notifier.
85 85
  ///
86 86
  /// There are some place when the alteration observing is not completly
87 87
  /// reliable. If we want to carry out the node degree in the graph
88 88
  /// as in the \ref InDegMap and we use the reverseEdge that cause
89 89
  /// unreliable functionality. Because the alteration observing signals
90 90
  /// only erasing and adding but not the reversing it will stores bad
91 91
  /// degrees. The sub graph adaptors cannot signal the alterations because
92 92
  /// just a setting in the filter map can modify the graph and this cannot
93 93
  /// be watched in any way.
94 94
  ///
95 95
  /// \param _Container The container which is observed.
96 96
  /// \param _Item The item type which is obserbved.
97 97

	
98 98
  template <typename _Container, typename _Item>
99 99
  class AlterationNotifier {
100 100
  public:
101 101

	
102 102
    typedef True Notifier;
103 103

	
104 104
    typedef _Container Container;
105 105
    typedef _Item Item;
106 106

	
107 107
    /// \brief Exception which can be called from \e clear() and
108 108
    /// \e erase().
109 109
    ///
110 110
    /// From the \e clear() and \e erase() function only this
111 111
    /// exception is allowed to throw. The exception immediatly
112 112
    /// detaches the current observer from the notifier. Because the
113 113
    /// \e clear() and \e erase() should not throw other exceptions
114 114
    /// it can be used to invalidate the observer.
115 115
    struct ImmediateDetach {};
116 116

	
117 117
    /// \brief ObserverBase is the base class for the observers.
118 118
    ///
119 119
    /// ObserverBase is the abstract base class for the observers.
120 120
    /// It will be notified about an item was inserted into or
121 121
    /// erased from the graph.
122 122
    ///
123 123
    /// The observer interface contains some pure virtual functions
124 124
    /// to override. The add() and erase() functions are
125 125
    /// to notify the oberver when one item is added or
126 126
    /// erased.
127 127
    ///
128 128
    /// The build() and clear() members are to notify the observer
129 129
    /// about the container is built from an empty container or
130 130
    /// is cleared to an empty container.
131 131

	
132 132
    class ObserverBase {
133 133
    protected:
134 134
      typedef AlterationNotifier Notifier;
135 135

	
136 136
      friend class AlterationNotifier;
137 137

	
138 138
      /// \brief Default constructor.
139 139
      ///
140 140
      /// Default constructor for ObserverBase.
141 141
      ///
142 142
      ObserverBase() : _notifier(0) {}
143 143

	
144 144
      /// \brief Constructor which attach the observer into notifier.
145 145
      ///
146 146
      /// Constructor which attach the observer into notifier.
147 147
      ObserverBase(AlterationNotifier& nf) {
148 148
        attach(nf);
149 149
      }
150 150

	
151 151
      /// \brief Constructor which attach the obserever to the same notifier.
152 152
      ///
153 153
      /// Constructor which attach the obserever to the same notifier as
154 154
      /// the other observer is attached to.
155 155
      ObserverBase(const ObserverBase& copy) {
156 156
        if (copy.attached()) {
157 157
          attach(*copy.notifier());
158 158
        }
159 159
      }
160 160

	
161 161
      /// \brief Destructor
162 162
      virtual ~ObserverBase() {
163 163
        if (attached()) {
164 164
          detach();
165 165
        }
166 166
      }
167 167

	
168 168
      /// \brief Attaches the observer into an AlterationNotifier.
169 169
      ///
170 170
      /// This member attaches the observer into an AlterationNotifier.
171 171
      ///
172 172
      void attach(AlterationNotifier& nf) {
173 173
        nf.attach(*this);
174 174
      }
175 175

	
176 176
      /// \brief Detaches the observer into an AlterationNotifier.
177 177
      ///
178 178
      /// This member detaches the observer from an AlterationNotifier.
179 179
      ///
180 180
      void detach() {
181 181
        _notifier->detach(*this);
182 182
      }
183 183

	
184 184
      /// \brief Gives back a pointer to the notifier which the map
185 185
      /// attached into.
186 186
      ///
187 187
      /// This function gives back a pointer to the notifier which the map
188 188
      /// attached into.
189 189
      ///
190 190
      Notifier* notifier() const { return const_cast<Notifier*>(_notifier); }
191 191

	
192 192
      /// Gives back true when the observer is attached into a notifier.
193 193
      bool attached() const { return _notifier != 0; }
194 194

	
195 195
    private:
196 196

	
197 197
      ObserverBase& operator=(const ObserverBase& copy);
198 198

	
199 199
    protected:
200 200

	
201 201
      Notifier* _notifier;
202 202
      typename std::list<ObserverBase*>::iterator _index;
203 203

	
204 204
      /// \brief The member function to notificate the observer about an
205 205
      /// item is added to the container.
206 206
      ///
207 207
      /// The add() member function notificates the observer about an item
208 208
      /// is added to the container. It have to be overrided in the
209 209
      /// subclasses.
210 210
      virtual void add(const Item&) = 0;
211 211

	
212 212
      /// \brief The member function to notificate the observer about
213 213
      /// more item is added to the container.
214 214
      ///
215 215
      /// The add() member function notificates the observer about more item
216 216
      /// is added to the container. It have to be overrided in the
217 217
      /// subclasses.
218 218
      virtual void add(const std::vector<Item>& items) = 0;
219 219

	
220 220
      /// \brief The member function to notificate the observer about an
221 221
      /// item is erased from the container.
222 222
      ///
223 223
      /// The erase() member function notificates the observer about an
224 224
      /// item is erased from the container. It have to be overrided in
225 225
      /// the subclasses.
226 226
      virtual void erase(const Item&) = 0;
227 227

	
228 228
      /// \brief The member function to notificate the observer about
229 229
      /// more item is erased from the container.
230 230
      ///
231 231
      /// The erase() member function notificates the observer about more item
232 232
      /// is erased from the container. It have to be overrided in the
233 233
      /// subclasses.
234 234
      virtual void erase(const std::vector<Item>& items) = 0;
235 235

	
236 236
      /// \brief The member function to notificate the observer about the
237 237
      /// container is built.
238 238
      ///
239 239
      /// The build() member function notificates the observer about the
240 240
      /// container is built from an empty container. It have to be
241 241
      /// overrided in the subclasses.
242 242

	
243 243
      virtual void build() = 0;
244 244

	
245 245
      /// \brief The member function to notificate the observer about all
246 246
      /// items are erased from the container.
247 247
      ///
248 248
      /// The clear() member function notificates the observer about all
249 249
      /// items are erased from the container. It have to be overrided in
250 250
      /// the subclasses.
251 251
      virtual void clear() = 0;
252 252

	
253 253
    };
254 254

	
255 255
  protected:
256 256

	
257 257
    const Container* container;
258 258

	
259 259
    typedef std::list<ObserverBase*> Observers;
260 260
    Observers _observers;
261 261

	
262 262

	
263 263
  public:
264 264

	
265 265
    /// \brief Default constructor.
266 266
    ///
267 267
    /// The default constructor of the AlterationNotifier.
268 268
    /// It creates an empty notifier.
269 269
    AlterationNotifier()
270 270
      : container(0) {}
271 271

	
272 272
    /// \brief Constructor.
273 273
    ///
274 274
    /// Constructor with the observed container parameter.
275 275
    AlterationNotifier(const Container& _container)
276 276
      : container(&_container) {}
277 277

	
278 278
    /// \brief Copy Constructor of the AlterationNotifier.
279 279
    ///
280 280
    /// Copy constructor of the AlterationNotifier.
281 281
    /// It creates only an empty notifier because the copiable
282 282
    /// notifier's observers have to be registered still into that notifier.
283 283
    AlterationNotifier(const AlterationNotifier& _notifier)
284 284
      : container(_notifier.container) {}
285 285

	
286 286
    /// \brief Destructor.
287 287
    ///
288 288
    /// Destructor of the AlterationNotifier.
289 289
    ///
290 290
    ~AlterationNotifier() {
291 291
      typename Observers::iterator it;
292 292
      for (it = _observers.begin(); it != _observers.end(); ++it) {
293 293
        (*it)->_notifier = 0;
294 294
      }
295 295
    }
296 296

	
297 297
    /// \brief Sets the container.
298 298
    ///
299 299
    /// Sets the container.
300 300
    void setContainer(const Container& _container) {
301 301
      container = &_container;
302 302
    }
303 303

	
304 304
  protected:
305 305

	
306 306
    AlterationNotifier& operator=(const AlterationNotifier&);
307 307

	
308 308
  public:
309 309

	
310 310

	
311 311

	
312 312
    /// \brief First item in the container.
313 313
    ///
314 314
    /// Returns the first item in the container. It is
315 315
    /// for start the iteration on the container.
316 316
    void first(Item& item) const {
317 317
      container->first(item);
318 318
    }
319 319

	
320 320
    /// \brief Next item in the container.
321 321
    ///
322 322
    /// Returns the next item in the container. It is
323 323
    /// for iterate on the container.
324 324
    void next(Item& item) const {
325 325
      container->next(item);
326 326
    }
327 327

	
328 328
    /// \brief Returns the id of the item.
329 329
    ///
330 330
    /// Returns the id of the item provided by the container.
331 331
    int id(const Item& item) const {
332 332
      return container->id(item);
333 333
    }
334 334

	
335 335
    /// \brief Returns the maximum id of the container.
336 336
    ///
337 337
    /// Returns the maximum id of the container.
338 338
    int maxId() const {
339 339
      return container->maxId(Item());
340 340
    }
341 341

	
342 342
  protected:
343 343

	
344 344
    void attach(ObserverBase& observer) {
345 345
      observer._index = _observers.insert(_observers.begin(), &observer);
346 346
      observer._notifier = this;
347 347
    }
348 348

	
349 349
    void detach(ObserverBase& observer) {
350 350
      _observers.erase(observer._index);
351 351
      observer._index = _observers.end();
352 352
      observer._notifier = 0;
353 353
    }
354 354

	
355 355
  public:
356 356

	
357 357
    /// \brief Notifies all the registed observers about an item added to
358 358
    /// the container.
359 359
    ///
360 360
    /// It notifies all the registed observers about an item added to
361 361
    /// the container.
362 362
    ///
363 363
    void add(const Item& item) {
364 364
      typename Observers::reverse_iterator it;
365 365
      try {
366 366
        for (it = _observers.rbegin(); it != _observers.rend(); ++it) {
367 367
          (*it)->add(item);
368 368
        }
369 369
      } catch (...) {
370 370
        typename Observers::iterator jt;
371 371
        for (jt = it.base(); jt != _observers.end(); ++jt) {
372 372
          (*jt)->erase(item);
373 373
        }
374 374
        throw;
375 375
      }
376 376
    }
377 377

	
378 378
    /// \brief Notifies all the registed observers about more item added to
379 379
    /// the container.
380 380
    ///
381 381
    /// It notifies all the registed observers about more item added to
382 382
    /// the container.
383 383
    ///
384 384
    void add(const std::vector<Item>& items) {
385 385
      typename Observers::reverse_iterator it;
386 386
      try {
387 387
        for (it = _observers.rbegin(); it != _observers.rend(); ++it) {
388 388
          (*it)->add(items);
389 389
        }
390 390
      } catch (...) {
391 391
        typename Observers::iterator jt;
392 392
        for (jt = it.base(); jt != _observers.end(); ++jt) {
393 393
          (*jt)->erase(items);
394 394
        }
395 395
        throw;
396 396
      }
397 397
    }
398 398

	
399 399
    /// \brief Notifies all the registed observers about an item erased from
400 400
    /// the container.
401 401
    ///
402 402
    /// It notifies all the registed observers about an item erased from
403 403
    /// the container.
404 404
    ///
405 405
    void erase(const Item& item) throw() {
406 406
      typename Observers::iterator it = _observers.begin();
407 407
      while (it != _observers.end()) {
408 408
        try {
409 409
          (*it)->erase(item);
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_BASE_EXTENDER_H
20 20
#define LEMON_BITS_BASE_EXTENDER_H
21 21

	
22
#include <lemon/bits/invalid.h>
22
#include <lemon/core.h>
23 23
#include <lemon/error.h>
24 24

	
25 25
#include <lemon/bits/map_extender.h>
26 26
#include <lemon/bits/default_map.h>
27 27

	
28 28
#include <lemon/concept_check.h>
29 29
#include <lemon/concepts/maps.h>
30 30

	
31 31
///\ingroup digraphbits
32 32
///\file
33 33
///\brief Extenders for the digraph types
34 34
namespace lemon {
35 35

	
36 36
  /// \ingroup digraphbits
37 37
  ///
38 38
  /// \brief BaseDigraph to BaseGraph extender
39 39
  template <typename Base>
40 40
  class UndirDigraphExtender : public Base {
41 41

	
42 42
  public:
43 43

	
44 44
    typedef Base Parent;
45 45
    typedef typename Parent::Arc Edge;
46 46
    typedef typename Parent::Node Node;
47 47

	
48 48
    typedef True UndirectedTag;
49 49

	
50 50
    class Arc : public Edge {
51 51
      friend class UndirDigraphExtender;
52 52

	
53 53
    protected:
54 54
      bool forward;
55 55

	
56 56
      Arc(const Edge &ue, bool _forward) :
57 57
        Edge(ue), forward(_forward) {}
58 58

	
59 59
    public:
60 60
      Arc() {}
61 61

	
62 62
      /// Invalid arc constructor
63 63
      Arc(Invalid i) : Edge(i), forward(true) {}
64 64

	
65 65
      bool operator==(const Arc &that) const {
66 66
        return forward==that.forward && Edge(*this)==Edge(that);
67 67
      }
68 68
      bool operator!=(const Arc &that) const {
69 69
        return forward!=that.forward || Edge(*this)!=Edge(that);
70 70
      }
71 71
      bool operator<(const Arc &that) const {
72 72
        return forward<that.forward ||
73 73
          (!(that.forward<forward) && Edge(*this)<Edge(that));
74 74
      }
75 75
    };
76 76

	
77 77

	
78 78

	
79 79
    using Parent::source;
80 80

	
81 81
    /// Source of the given Arc.
82 82
    Node source(const Arc &e) const {
83 83
      return e.forward ? Parent::source(e) : Parent::target(e);
84 84
    }
85 85

	
86 86
    using Parent::target;
87 87

	
88 88
    /// Target of the given Arc.
89 89
    Node target(const Arc &e) const {
90 90
      return e.forward ? Parent::target(e) : Parent::source(e);
91 91
    }
92 92

	
93 93
    /// \brief Directed arc from an edge.
94 94
    ///
95 95
    /// Returns a directed arc corresponding to the specified Edge.
96 96
    /// If the given bool is true the given edge and the
97 97
    /// returned arc have the same source node.
98 98
    static Arc direct(const Edge &ue, bool d) {
99 99
      return Arc(ue, d);
100 100
    }
101 101

	
102 102
    /// Returns whether the given directed arc is same orientation as the
103 103
    /// corresponding edge.
104 104
    ///
105 105
    /// \todo reference to the corresponding point of the undirected digraph
106 106
    /// concept. "What does the direction of an edge mean?"
107 107
    static bool direction(const Arc &e) { return e.forward; }
108 108

	
109 109

	
110 110
    using Parent::first;
111 111
    using Parent::next;
112 112

	
113 113
    void first(Arc &e) const {
114 114
      Parent::first(e);
115 115
      e.forward=true;
116 116
    }
117 117

	
118 118
    void next(Arc &e) const {
119 119
      if( e.forward ) {
120 120
        e.forward = false;
121 121
      }
122 122
      else {
123 123
        Parent::next(e);
124 124
        e.forward = true;
125 125
      }
126 126
    }
127 127

	
128 128
    void firstOut(Arc &e, const Node &n) const {
129 129
      Parent::firstIn(e,n);
130 130
      if( Edge(e) != INVALID ) {
131 131
        e.forward = false;
132 132
      }
133 133
      else {
134 134
        Parent::firstOut(e,n);
135 135
        e.forward = true;
136 136
      }
137 137
    }
138 138
    void nextOut(Arc &e) const {
139 139
      if( ! e.forward ) {
140 140
        Node n = Parent::target(e);
141 141
        Parent::nextIn(e);
142 142
        if( Edge(e) == INVALID ) {
143 143
          Parent::firstOut(e, n);
144 144
          e.forward = true;
145 145
        }
146 146
      }
147 147
      else {
148 148
        Parent::nextOut(e);
149 149
      }
150 150
    }
151 151

	
152 152
    void firstIn(Arc &e, const Node &n) const {
153 153
      Parent::firstOut(e,n);
154 154
      if( Edge(e) != INVALID ) {
155 155
        e.forward = false;
156 156
      }
157 157
      else {
158 158
        Parent::firstIn(e,n);
159 159
        e.forward = true;
160 160
      }
161 161
    }
162 162
    void nextIn(Arc &e) const {
163 163
      if( ! e.forward ) {
164 164
        Node n = Parent::source(e);
165 165
        Parent::nextOut(e);
166 166
        if( Edge(e) == INVALID ) {
167 167
          Parent::firstIn(e, n);
168 168
          e.forward = true;
169 169
        }
170 170
      }
171 171
      else {
172 172
        Parent::nextIn(e);
173 173
      }
174 174
    }
175 175

	
176 176
    void firstInc(Edge &e, bool &d, const Node &n) const {
177 177
      d = true;
178 178
      Parent::firstOut(e, n);
179 179
      if (e != INVALID) return;
180 180
      d = false;
181 181
      Parent::firstIn(e, n);
182 182
    }
183 183

	
184 184
    void nextInc(Edge &e, bool &d) const {
185 185
      if (d) {
186 186
        Node s = Parent::source(e);
187 187
        Parent::nextOut(e);
188 188
        if (e != INVALID) return;
189 189
        d = false;
190 190
        Parent::firstIn(e, s);
191 191
      } else {
192 192
        Parent::nextIn(e);
193 193
      }
194 194
    }
195 195

	
196 196
    Node nodeFromId(int ix) const {
197 197
      return Parent::nodeFromId(ix);
198 198
    }
199 199

	
200 200
    Arc arcFromId(int ix) const {
201 201
      return direct(Parent::arcFromId(ix >> 1), bool(ix & 1));
202 202
    }
203 203

	
204 204
    Edge edgeFromId(int ix) const {
205 205
      return Parent::arcFromId(ix);
206 206
    }
207 207

	
208 208
    int id(const Node &n) const {
209 209
      return Parent::id(n);
210 210
    }
211 211

	
212 212
    int id(const Edge &e) const {
213 213
      return Parent::id(e);
214 214
    }
215 215

	
216 216
    int id(const Arc &e) const {
217 217
      return 2 * Parent::id(e) + int(e.forward);
218 218
    }
219 219

	
220 220
    int maxNodeId() const {
221 221
      return Parent::maxNodeId();
222 222
    }
223 223

	
224 224
    int maxArcId() const {
225 225
      return 2 * Parent::maxArcId() + 1;
226 226
    }
227 227

	
228 228
    int maxEdgeId() const {
229 229
      return Parent::maxArcId();
230 230
    }
231 231

	
232 232

	
233 233
    int arcNum() const {
234 234
      return 2 * Parent::arcNum();
235 235
    }
236 236

	
237 237
    int edgeNum() const {
238 238
      return Parent::arcNum();
239 239
    }
240 240

	
241 241
    Arc findArc(Node s, Node t, Arc p = INVALID) const {
242 242
      if (p == INVALID) {
243 243
        Edge arc = Parent::findArc(s, t);
244 244
        if (arc != INVALID) return direct(arc, true);
245 245
        arc = Parent::findArc(t, s);
246 246
        if (arc != INVALID) return direct(arc, false);
247 247
      } else if (direction(p)) {
248 248
        Edge arc = Parent::findArc(s, t, p);
249 249
        if (arc != INVALID) return direct(arc, true);
250 250
        arc = Parent::findArc(t, s);
251 251
        if (arc != INVALID) return direct(arc, false);
252 252
      } else {
253 253
        Edge arc = Parent::findArc(t, s, p);
254 254
        if (arc != INVALID) return direct(arc, false);
255 255
      }
256 256
      return INVALID;
257 257
    }
258 258

	
259 259
    Edge findEdge(Node s, Node t, Edge p = INVALID) const {
260 260
      if (s != t) {
261 261
        if (p == INVALID) {
262 262
          Edge arc = Parent::findArc(s, t);
263 263
          if (arc != INVALID) return arc;
264 264
          arc = Parent::findArc(t, s);
265 265
          if (arc != INVALID) return arc;
266 266
        } else if (Parent::s(p) == s) {
267 267
          Edge arc = Parent::findArc(s, t, p);
268 268
          if (arc != INVALID) return arc;
269 269
          arc = Parent::findArc(t, s);
270 270
          if (arc != INVALID) return arc;
271 271
        } else {
272 272
          Edge arc = Parent::findArc(t, s, p);
273 273
          if (arc != INVALID) return arc;
274 274
        }
275 275
      } else {
276 276
        return Parent::findArc(s, t, p);
277 277
      }
278 278
      return INVALID;
279 279
    }
280 280
  };
281 281

	
282 282
  template <typename Base>
283 283
  class BidirBpGraphExtender : public Base {
284 284
  public:
285 285
    typedef Base Parent;
286 286
    typedef BidirBpGraphExtender Digraph;
287 287

	
288 288
    typedef typename Parent::Node Node;
289 289
    typedef typename Parent::Edge Edge;
290 290

	
291 291

	
292 292
    using Parent::first;
293 293
    using Parent::next;
294 294

	
295 295
    using Parent::id;
296 296

	
297 297
    class Red : public Node {
298 298
      friend class BidirBpGraphExtender;
299 299
    public:
300 300
      Red() {}
301 301
      Red(const Node& node) : Node(node) {
302 302
        LEMON_ASSERT(Parent::red(node) || node == INVALID,
303 303
                     typename Parent::NodeSetError());
304 304
      }
305 305
      Red& operator=(const Node& node) {
306 306
        LEMON_ASSERT(Parent::red(node) || node == INVALID,
307 307
                     typename Parent::NodeSetError());
308 308
        Node::operator=(node);
309 309
        return *this;
310 310
      }
311 311
      Red(Invalid) : Node(INVALID) {}
312 312
      Red& operator=(Invalid) {
313 313
        Node::operator=(INVALID);
314 314
        return *this;
315 315
      }
316 316
    };
317 317

	
318 318
    void first(Red& node) const {
319 319
      Parent::firstRed(static_cast<Node&>(node));
320 320
    }
321 321
    void next(Red& node) const {
322 322
      Parent::nextRed(static_cast<Node&>(node));
323 323
    }
324 324

	
325 325
    int id(const Red& node) const {
326 326
      return Parent::redId(node);
327 327
    }
328 328

	
329 329
    class Blue : public Node {
330 330
      friend class BidirBpGraphExtender;
331 331
    public:
332 332
      Blue() {}
333 333
      Blue(const Node& node) : Node(node) {
334 334
        LEMON_ASSERT(Parent::blue(node) || node == INVALID,
335 335
                     typename Parent::NodeSetError());
336 336
      }
337 337
      Blue& operator=(const Node& node) {
338 338
        LEMON_ASSERT(Parent::blue(node) || node == INVALID,
339 339
                     typename Parent::NodeSetError());
340 340
        Node::operator=(node);
341 341
        return *this;
342 342
      }
343 343
      Blue(Invalid) : Node(INVALID) {}
344 344
      Blue& operator=(Invalid) {
345 345
        Node::operator=(INVALID);
346 346
        return *this;
347 347
      }
348 348
    };
349 349

	
350 350
    void first(Blue& node) const {
351 351
      Parent::firstBlue(static_cast<Node&>(node));
352 352
    }
353 353
    void next(Blue& node) const {
354 354
      Parent::nextBlue(static_cast<Node&>(node));
355 355
    }
356 356

	
357 357
    int id(const Blue& node) const {
358 358
      return Parent::redId(node);
359 359
    }
360 360

	
361 361
    Node source(const Edge& arc) const {
362 362
      return red(arc);
363 363
    }
364 364
    Node target(const Edge& arc) const {
365 365
      return blue(arc);
366 366
    }
367 367

	
368 368
    void firstInc(Edge& arc, bool& dir, const Node& node) const {
369 369
      if (Parent::red(node)) {
370 370
        Parent::firstFromRed(arc, node);
371 371
        dir = true;
372 372
      } else {
373 373
        Parent::firstFromBlue(arc, node);
374 374
        dir = static_cast<Edge&>(arc) == INVALID;
375 375
      }
376 376
    }
377 377
    void nextInc(Edge& arc, bool& dir) const {
378 378
      if (dir) {
379 379
        Parent::nextFromRed(arc);
380 380
      } else {
381 381
        Parent::nextFromBlue(arc);
382 382
        if (arc == INVALID) dir = true;
383 383
      }
384 384
    }
385 385

	
386 386
    class Arc : public Edge {
387 387
      friend class BidirBpGraphExtender;
388 388
    protected:
389 389
      bool forward;
390 390

	
391 391
      Arc(const Edge& arc, bool _forward)
392 392
        : Edge(arc), forward(_forward) {}
393 393

	
394 394
    public:
395 395
      Arc() {}
396 396
      Arc (Invalid) : Edge(INVALID), forward(true) {}
397 397
      bool operator==(const Arc& i) const {
398 398
        return Edge::operator==(i) && forward == i.forward;
399 399
      }
400 400
      bool operator!=(const Arc& i) const {
401 401
        return Edge::operator!=(i) || forward != i.forward;
402 402
      }
403 403
      bool operator<(const Arc& i) const {
404 404
        return Edge::operator<(i) ||
405 405
          (!(i.forward<forward) && Edge(*this)<Edge(i));
406 406
      }
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_GRAPH_EXTENDER_H
20 20
#define LEMON_BITS_GRAPH_EXTENDER_H
21 21

	
22
#include <lemon/bits/invalid.h>
23
#include <lemon/bits/utility.h>
22
#include <lemon/core.h>
24 23

	
25 24
#include <lemon/bits/map_extender.h>
26 25
#include <lemon/bits/default_map.h>
27 26

	
28 27
#include <lemon/concept_check.h>
29 28
#include <lemon/concepts/maps.h>
30 29

	
31 30
///\ingroup graphbits
32 31
///\file
33 32
///\brief Extenders for the digraph types
34 33
namespace lemon {
35 34

	
36 35
  /// \ingroup graphbits
37 36
  ///
38 37
  /// \brief Extender for the Digraphs
39 38
  template <typename Base>
40 39
  class DigraphExtender : public Base {
41 40
  public:
42 41

	
43 42
    typedef Base Parent;
44 43
    typedef DigraphExtender Digraph;
45 44

	
46 45
    // Base extensions
47 46

	
48 47
    typedef typename Parent::Node Node;
49 48
    typedef typename Parent::Arc Arc;
50 49

	
51 50
    int maxId(Node) const {
52 51
      return Parent::maxNodeId();
53 52
    }
54 53

	
55 54
    int maxId(Arc) const {
56 55
      return Parent::maxArcId();
57 56
    }
58 57

	
59 58
    Node fromId(int id, Node) const {
60 59
      return Parent::nodeFromId(id);
61 60
    }
62 61

	
63 62
    Arc fromId(int id, Arc) const {
64 63
      return Parent::arcFromId(id);
65 64
    }
66 65

	
67 66
    Node oppositeNode(const Node &node, const Arc &arc) const {
68 67
      if (node == Parent::source(arc))
69 68
        return Parent::target(arc);
70 69
      else if(node == Parent::target(arc))
71 70
        return Parent::source(arc);
72 71
      else
73 72
        return INVALID;
74 73
    }
75 74

	
76 75
    // Alterable extension
77 76

	
78 77
    typedef AlterationNotifier<DigraphExtender, Node> NodeNotifier;
79 78
    typedef AlterationNotifier<DigraphExtender, Arc> ArcNotifier;
80 79

	
81 80

	
82 81
  protected:
83 82

	
84 83
    mutable NodeNotifier node_notifier;
85 84
    mutable ArcNotifier arc_notifier;
86 85

	
87 86
  public:
88 87

	
89 88
    NodeNotifier& notifier(Node) const {
90 89
      return node_notifier;
91 90
    }
92 91

	
93 92
    ArcNotifier& notifier(Arc) const {
94 93
      return arc_notifier;
95 94
    }
96 95

	
97 96
    class NodeIt : public Node {
98 97
      const Digraph* _digraph;
99 98
    public:
100 99

	
101 100
      NodeIt() {}
102 101

	
103 102
      NodeIt(Invalid i) : Node(i) { }
104 103

	
105 104
      explicit NodeIt(const Digraph& digraph) : _digraph(&digraph) {
106 105
        _digraph->first(static_cast<Node&>(*this));
107 106
      }
108 107

	
109 108
      NodeIt(const Digraph& digraph, const Node& node)
110 109
        : Node(node), _digraph(&digraph) {}
111 110

	
112 111
      NodeIt& operator++() {
113 112
        _digraph->next(*this);
114 113
        return *this;
115 114
      }
116 115

	
117 116
    };
118 117

	
119 118

	
120 119
    class ArcIt : public Arc {
121 120
      const Digraph* _digraph;
122 121
    public:
123 122

	
124 123
      ArcIt() { }
125 124

	
126 125
      ArcIt(Invalid i) : Arc(i) { }
127 126

	
128 127
      explicit ArcIt(const Digraph& digraph) : _digraph(&digraph) {
129 128
        _digraph->first(static_cast<Arc&>(*this));
130 129
      }
131 130

	
132 131
      ArcIt(const Digraph& digraph, const Arc& arc) :
133 132
        Arc(arc), _digraph(&digraph) { }
134 133

	
135 134
      ArcIt& operator++() {
136 135
        _digraph->next(*this);
137 136
        return *this;
138 137
      }
139 138

	
140 139
    };
141 140

	
142 141

	
143 142
    class OutArcIt : public Arc {
144 143
      const Digraph* _digraph;
145 144
    public:
146 145

	
147 146
      OutArcIt() { }
148 147

	
149 148
      OutArcIt(Invalid i) : Arc(i) { }
150 149

	
151 150
      OutArcIt(const Digraph& digraph, const Node& node)
152 151
        : _digraph(&digraph) {
153 152
        _digraph->firstOut(*this, node);
154 153
      }
155 154

	
156 155
      OutArcIt(const Digraph& digraph, const Arc& arc)
157 156
        : Arc(arc), _digraph(&digraph) {}
158 157

	
159 158
      OutArcIt& operator++() {
160 159
        _digraph->nextOut(*this);
161 160
        return *this;
162 161
      }
163 162

	
164 163
    };
165 164

	
166 165

	
167 166
    class InArcIt : public Arc {
168 167
      const Digraph* _digraph;
169 168
    public:
170 169

	
171 170
      InArcIt() { }
172 171

	
173 172
      InArcIt(Invalid i) : Arc(i) { }
174 173

	
175 174
      InArcIt(const Digraph& digraph, const Node& node)
176 175
        : _digraph(&digraph) {
177 176
        _digraph->firstIn(*this, node);
178 177
      }
179 178

	
180 179
      InArcIt(const Digraph& digraph, const Arc& arc) :
181 180
        Arc(arc), _digraph(&digraph) {}
182 181

	
183 182
      InArcIt& operator++() {
184 183
        _digraph->nextIn(*this);
185 184
        return *this;
186 185
      }
187 186

	
188 187
    };
189 188

	
190 189
    /// \brief Base node of the iterator
191 190
    ///
192 191
    /// Returns the base node (i.e. the source in this case) of the iterator
193 192
    Node baseNode(const OutArcIt &arc) const {
194 193
      return Parent::source(arc);
195 194
    }
196 195
    /// \brief Running node of the iterator
197 196
    ///
198 197
    /// Returns the running node (i.e. the target in this case) of the
199 198
    /// iterator
200 199
    Node runningNode(const OutArcIt &arc) const {
201 200
      return Parent::target(arc);
202 201
    }
203 202

	
204 203
    /// \brief Base node of the iterator
205 204
    ///
206 205
    /// Returns the base node (i.e. the target in this case) of the iterator
207 206
    Node baseNode(const InArcIt &arc) const {
208 207
      return Parent::target(arc);
209 208
    }
210 209
    /// \brief Running node of the iterator
211 210
    ///
212 211
    /// Returns the running node (i.e. the source in this case) of the
213 212
    /// iterator
214 213
    Node runningNode(const InArcIt &arc) const {
215 214
      return Parent::source(arc);
216 215
    }
217 216

	
218 217

	
219 218
    template <typename _Value>
220 219
    class NodeMap
221 220
      : public MapExtender<DefaultMap<Digraph, Node, _Value> > {
222 221
    public:
223 222
      typedef DigraphExtender Digraph;
224 223
      typedef MapExtender<DefaultMap<Digraph, Node, _Value> > Parent;
225 224

	
226 225
      explicit NodeMap(const Digraph& digraph)
227 226
        : Parent(digraph) {}
228 227
      NodeMap(const Digraph& digraph, const _Value& value)
229 228
        : Parent(digraph, value) {}
230 229

	
231 230
      NodeMap& operator=(const NodeMap& cmap) {
232 231
        return operator=<NodeMap>(cmap);
233 232
      }
234 233

	
235 234
      template <typename CMap>
236 235
      NodeMap& operator=(const CMap& cmap) {
237 236
        Parent::operator=(cmap);
238 237
        return *this;
239 238
      }
240 239

	
241 240
    };
242 241

	
243 242
    template <typename _Value>
244 243
    class ArcMap
245 244
      : public MapExtender<DefaultMap<Digraph, Arc, _Value> > {
246 245
    public:
247 246
      typedef DigraphExtender Digraph;
248 247
      typedef MapExtender<DefaultMap<Digraph, Arc, _Value> > Parent;
249 248

	
250 249
      explicit ArcMap(const Digraph& digraph)
251 250
        : Parent(digraph) {}
252 251
      ArcMap(const Digraph& digraph, const _Value& value)
253 252
        : Parent(digraph, value) {}
254 253

	
255 254
      ArcMap& operator=(const ArcMap& cmap) {
256 255
        return operator=<ArcMap>(cmap);
257 256
      }
258 257

	
259 258
      template <typename CMap>
260 259
      ArcMap& operator=(const CMap& cmap) {
261 260
        Parent::operator=(cmap);
262 261
        return *this;
263 262
      }
264 263
    };
265 264

	
266 265

	
267 266
    Node addNode() {
268 267
      Node node = Parent::addNode();
269 268
      notifier(Node()).add(node);
270 269
      return node;
271 270
    }
272 271

	
273 272
    Arc addArc(const Node& from, const Node& to) {
274 273
      Arc arc = Parent::addArc(from, to);
275 274
      notifier(Arc()).add(arc);
276 275
      return arc;
277 276
    }
278 277

	
279 278
    void clear() {
280 279
      notifier(Arc()).clear();
281 280
      notifier(Node()).clear();
282 281
      Parent::clear();
283 282
    }
284 283

	
285 284
    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
286 285
    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
287 286
      Parent::build(digraph, nodeRef, arcRef);
288 287
      notifier(Node()).build();
289 288
      notifier(Arc()).build();
290 289
    }
291 290

	
292 291
    void erase(const Node& node) {
293 292
      Arc arc;
294 293
      Parent::firstOut(arc, node);
295 294
      while (arc != INVALID ) {
296 295
        erase(arc);
297 296
        Parent::firstOut(arc, node);
298 297
      }
299 298

	
300 299
      Parent::firstIn(arc, node);
301 300
      while (arc != INVALID ) {
302 301
        erase(arc);
303 302
        Parent::firstIn(arc, node);
304 303
      }
305 304

	
306 305
      notifier(Node()).erase(node);
307 306
      Parent::erase(node);
308 307
    }
309 308

	
310 309
    void erase(const Arc& arc) {
311 310
      notifier(Arc()).erase(arc);
312 311
      Parent::erase(arc);
313 312
    }
314 313

	
315 314
    DigraphExtender() {
316 315
      node_notifier.setContainer(*this);
317 316
      arc_notifier.setContainer(*this);
318 317
    }
319 318

	
320 319

	
321 320
    ~DigraphExtender() {
322 321
      arc_notifier.clear();
323 322
      node_notifier.clear();
324 323
    }
325 324
  };
326 325

	
327 326
  /// \ingroup _graphbits
328 327
  ///
329 328
  /// \brief Extender for the Graphs
330 329
  template <typename Base>
331 330
  class GraphExtender : public Base {
332 331
  public:
333 332

	
334 333
    typedef Base Parent;
335 334
    typedef GraphExtender Graph;
336 335

	
337 336
    typedef True UndirectedTag;
338 337

	
339 338
    typedef typename Parent::Node Node;
340 339
    typedef typename Parent::Arc Arc;
341 340
    typedef typename Parent::Edge Edge;
342 341

	
343 342
    // Graph extension
344 343

	
345 344
    int maxId(Node) const {
346 345
      return Parent::maxNodeId();
347 346
    }
348 347

	
349 348
    int maxId(Arc) const {
350 349
      return Parent::maxArcId();
351 350
    }
352 351

	
353 352
    int maxId(Edge) const {
354 353
      return Parent::maxEdgeId();
355 354
    }
356 355

	
357 356
    Node fromId(int id, Node) const {
358 357
      return Parent::nodeFromId(id);
359 358
    }
360 359

	
361 360
    Arc fromId(int id, Arc) const {
362 361
      return Parent::arcFromId(id);
363 362
    }
364 363

	
365 364
    Edge fromId(int id, Edge) const {
366 365
      return Parent::edgeFromId(id);
367 366
    }
368 367

	
369 368
    Node oppositeNode(const Node &n, const Edge &e) const {
370 369
      if( n == Parent::u(e))
371 370
        return Parent::v(e);
372 371
      else if( n == Parent::v(e))
373 372
        return Parent::u(e);
374 373
      else
375 374
        return INVALID;
376 375
    }
377 376

	
378 377
    Arc oppositeArc(const Arc &arc) const {
379 378
      return Parent::direct(arc, !Parent::direction(arc));
380 379
    }
381 380

	
382 381
    using Parent::direct;
383 382
    Arc direct(const Edge &edge, const Node &node) const {
384 383
      return Parent::direct(edge, Parent::u(edge) == node);
385 384
    }
386 385

	
387 386
    // Alterable extension
388 387

	
389 388
    typedef AlterationNotifier<GraphExtender, Node> NodeNotifier;
390 389
    typedef AlterationNotifier<GraphExtender, Arc> ArcNotifier;
391 390
    typedef AlterationNotifier<GraphExtender, Edge> EdgeNotifier;
392 391

	
393 392

	
394 393
  protected:
395 394

	
396 395
    mutable NodeNotifier node_notifier;
397 396
    mutable ArcNotifier arc_notifier;
398 397
    mutable EdgeNotifier edge_notifier;
399 398

	
400 399
  public:
401 400

	
402 401
    NodeNotifier& notifier(Node) const {
403 402
      return node_notifier;
404 403
    }
405 404

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

	
19 19
#ifndef LEMON_BITS_TRAITS_H
20 20
#define LEMON_BITS_TRAITS_H
21 21

	
22
#include <lemon/bits/utility.h>
23

	
24 22
///\file
25 23
///\brief Traits for graphs and maps
26 24
///
27 25

	
26
#include <lemon/bits/enable_if.h>
27

	
28 28
namespace lemon {
29

	
30
  struct InvalidType {};
31

	
29 32
  template <typename _Graph, typename _Item>
30 33
  class ItemSetTraits {};
31 34

	
32 35

	
33 36
  template <typename Graph, typename Enable = void>
34 37
  struct NodeNotifierIndicator {
35 38
    typedef InvalidType Type;
36 39
  };
37 40
  template <typename Graph>
38 41
  struct NodeNotifierIndicator<
39 42
    Graph,
40 43
    typename enable_if<typename Graph::NodeNotifier::Notifier, void>::type
41 44
  > {
42 45
    typedef typename Graph::NodeNotifier Type;
43 46
  };
44 47

	
45 48
  template <typename _Graph>
46 49
  class ItemSetTraits<_Graph, typename _Graph::Node> {
47 50
  public:
48 51

	
49 52
    typedef _Graph Graph;
50 53

	
51 54
    typedef typename Graph::Node Item;
52 55
    typedef typename Graph::NodeIt ItemIt;
53 56

	
54 57
    typedef typename NodeNotifierIndicator<Graph>::Type ItemNotifier;
55 58

	
56 59
    template <typename _Value>
57 60
    class Map : public Graph::template NodeMap<_Value> {
58 61
    public:
59 62
      typedef typename Graph::template NodeMap<_Value> Parent;
60 63
      typedef typename Graph::template NodeMap<_Value> Type;
61 64
      typedef typename Parent::Value Value;
62 65

	
63 66
      Map(const Graph& _digraph) : Parent(_digraph) {}
64 67
      Map(const Graph& _digraph, const Value& _value)
65 68
        : Parent(_digraph, _value) {}
66 69

	
67 70
     };
68 71

	
69 72
  };
70 73

	
71 74
  template <typename Graph, typename Enable = void>
72 75
  struct ArcNotifierIndicator {
73 76
    typedef InvalidType Type;
74 77
  };
75 78
  template <typename Graph>
76 79
  struct ArcNotifierIndicator<
77 80
    Graph,
78 81
    typename enable_if<typename Graph::ArcNotifier::Notifier, void>::type
79 82
  > {
80 83
    typedef typename Graph::ArcNotifier Type;
81 84
  };
82 85

	
83 86
  template <typename _Graph>
84 87
  class ItemSetTraits<_Graph, typename _Graph::Arc> {
85 88
  public:
86 89

	
87 90
    typedef _Graph Graph;
88 91

	
89 92
    typedef typename Graph::Arc Item;
90 93
    typedef typename Graph::ArcIt ItemIt;
91 94

	
92 95
    typedef typename ArcNotifierIndicator<Graph>::Type ItemNotifier;
93 96

	
94 97
    template <typename _Value>
95 98
    class Map : public Graph::template ArcMap<_Value> {
96 99
    public:
97 100
      typedef typename Graph::template ArcMap<_Value> Parent;
98 101
      typedef typename Graph::template ArcMap<_Value> Type;
99 102
      typedef typename Parent::Value Value;
100 103

	
101 104
      Map(const Graph& _digraph) : Parent(_digraph) {}
102 105
      Map(const Graph& _digraph, const Value& _value)
103 106
        : Parent(_digraph, _value) {}
104 107
    };
105 108

	
106 109
  };
107 110

	
108 111
  template <typename Graph, typename Enable = void>
109 112
  struct EdgeNotifierIndicator {
110 113
    typedef InvalidType Type;
111 114
  };
112 115
  template <typename Graph>
113 116
  struct EdgeNotifierIndicator<
114 117
    Graph,
115 118
    typename enable_if<typename Graph::EdgeNotifier::Notifier, void>::type
116 119
  > {
117 120
    typedef typename Graph::EdgeNotifier Type;
118 121
  };
119 122

	
120 123
  template <typename _Graph>
121 124
  class ItemSetTraits<_Graph, typename _Graph::Edge> {
122 125
  public:
123 126

	
124 127
    typedef _Graph Graph;
125 128

	
126 129
    typedef typename Graph::Edge Item;
127 130
    typedef typename Graph::EdgeIt ItemIt;
128 131

	
129 132
    typedef typename EdgeNotifierIndicator<Graph>::Type ItemNotifier;
130 133

	
131 134
    template <typename _Value>
132 135
    class Map : public Graph::template EdgeMap<_Value> {
133 136
    public:
134 137
      typedef typename Graph::template EdgeMap<_Value> Parent;
135 138
      typedef typename Graph::template EdgeMap<_Value> Type;
136 139
      typedef typename Parent::Value Value;
137 140

	
138 141
      Map(const Graph& _digraph) : Parent(_digraph) {}
139 142
      Map(const Graph& _digraph, const Value& _value)
140 143
        : Parent(_digraph, _value) {}
141 144
    };
142 145

	
143 146
  };
144 147

	
145 148
  template <typename Map, typename Enable = void>
146 149
  struct MapTraits {
147 150
    typedef False ReferenceMapTag;
148 151

	
149 152
    typedef typename Map::Key Key;
150 153
    typedef typename Map::Value Value;
151 154

	
152 155
    typedef Value ConstReturnValue;
153 156
    typedef Value ReturnValue;
154 157
  };
155 158

	
156 159
  template <typename Map>
157 160
  struct MapTraits<
158 161
    Map, typename enable_if<typename Map::ReferenceMapTag, void>::type >
159 162
  {
160 163
    typedef True ReferenceMapTag;
161 164

	
162 165
    typedef typename Map::Key Key;
163 166
    typedef typename Map::Value Value;
164 167

	
165 168
    typedef typename Map::ConstReference ConstReturnValue;
166 169
    typedef typename Map::Reference ReturnValue;
167 170

	
168 171
    typedef typename Map::ConstReference ConstReference;
169 172
    typedef typename Map::Reference Reference;
170 173
 };
171 174

	
172 175
  template <typename MatrixMap, typename Enable = void>
173 176
  struct MatrixMapTraits {
174 177
    typedef False ReferenceMapTag;
175 178

	
176 179
    typedef typename MatrixMap::FirstKey FirstKey;
177 180
    typedef typename MatrixMap::SecondKey SecondKey;
178 181
    typedef typename MatrixMap::Value Value;
179 182

	
180 183
    typedef Value ConstReturnValue;
181 184
    typedef Value ReturnValue;
182 185
  };
183 186

	
184 187
  template <typename MatrixMap>
185 188
  struct MatrixMapTraits<
186 189
    MatrixMap, typename enable_if<typename MatrixMap::ReferenceMapTag,
187 190
                                  void>::type >
188 191
  {
189 192
    typedef True ReferenceMapTag;
190 193

	
191 194
    typedef typename MatrixMap::FirstKey FirstKey;
192 195
    typedef typename MatrixMap::SecondKey SecondKey;
193 196
    typedef typename MatrixMap::Value Value;
194 197

	
195 198
    typedef typename MatrixMap::ConstReference ConstReturnValue;
196 199
    typedef typename MatrixMap::Reference ReturnValue;
197 200

	
198 201
    typedef typename MatrixMap::ConstReference ConstReference;
199 202
    typedef typename MatrixMap::Reference Reference;
200 203
 };
201 204

	
202 205
  // Indicators for the tags
203 206

	
204 207
  template <typename Graph, typename Enable = void>
205 208
  struct NodeNumTagIndicator {
206 209
    static const bool value = false;
207 210
  };
208 211

	
209 212
  template <typename Graph>
210 213
  struct NodeNumTagIndicator<
211 214
    Graph,
212 215
    typename enable_if<typename Graph::NodeNumTag, void>::type
213 216
  > {
214 217
    static const bool value = true;
215 218
  };
216 219

	
217 220
  template <typename Graph, typename Enable = void>
218 221
  struct EdgeNumTagIndicator {
219 222
    static const bool value = false;
220 223
  };
221 224

	
222 225
  template <typename Graph>
223 226
  struct EdgeNumTagIndicator<
224 227
    Graph,
225 228
    typename enable_if<typename Graph::EdgeNumTag, void>::type
226 229
  > {
227 230
    static const bool value = true;
228 231
  };
229 232

	
230 233
  template <typename Graph, typename Enable = void>
231 234
  struct FindEdgeTagIndicator {
232 235
    static const bool value = false;
233 236
  };
234 237

	
235 238
  template <typename Graph>
236 239
  struct FindEdgeTagIndicator<
237 240
    Graph,
238 241
    typename enable_if<typename Graph::FindEdgeTag, void>::type
239 242
  > {
240 243
    static const bool value = true;
241 244
  };
242 245

	
243 246
  template <typename Graph, typename Enable = void>
244 247
  struct UndirectedTagIndicator {
245 248
    static const bool value = false;
246 249
  };
247 250

	
248 251
  template <typename Graph>
249 252
  struct UndirectedTagIndicator<
250 253
    Graph,
251 254
    typename enable_if<typename Graph::UndirectedTag, void>::type
252 255
  > {
253 256
    static const bool value = true;
254 257
  };
255 258

	
256 259
  template <typename Graph, typename Enable = void>
257 260
  struct BuildTagIndicator {
258 261
    static const bool value = false;
259 262
  };
260 263

	
261 264
  template <typename Graph>
262 265
  struct BuildTagIndicator<
263 266
    Graph,
264 267
    typename enable_if<typename Graph::BuildTag, void>::type
265 268
  > {
266 269
    static const bool value = true;
267 270
  };
268 271

	
269 272
}
270 273

	
271 274
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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_BITS_VECTOR_MAP_H
20 20
#define LEMON_BITS_VECTOR_MAP_H
21 21

	
22 22
#include <vector>
23 23
#include <algorithm>
24 24

	
25
#include <lemon/bits/traits.h>
26
#include <lemon/bits/utility.h>
27

	
25
#include <lemon/core.h>
28 26
#include <lemon/bits/alteration_notifier.h>
29 27

	
30 28
#include <lemon/concept_check.h>
31 29
#include <lemon/concepts/maps.h>
32 30

	
33 31
///\ingroup graphbits
34 32
///
35 33
///\file
36 34
///\brief Vector based graph maps.
37 35
namespace lemon {
38 36

	
39 37
  /// \ingroup graphbits
40 38
  ///
41 39
  /// \brief Graph map based on the std::vector storage.
42 40
  ///
43 41
  /// The VectorMap template class is graph map structure what
44 42
  /// automatically updates the map when a key is added to or erased from
45 43
  /// the map. This map type uses the std::vector to store the values.
46 44
  ///
47 45
  /// \tparam _Notifier The AlterationNotifier that will notify this map.
48 46
  /// \tparam _Item The item type of the graph items.
49 47
  /// \tparam _Value The value type of the map.
50 48
  /// \todo Fix the doc: there is _Graph parameter instead of _Notifier.
51 49
  template <typename _Graph, typename _Item, typename _Value>
52 50
  class VectorMap
53 51
    : public ItemSetTraits<_Graph, _Item>::ItemNotifier::ObserverBase {
54 52
  private:
55 53

	
56 54
    /// The container type of the map.
57 55
    typedef std::vector<_Value> Container;
58 56

	
59 57
  public:
60 58

	
61 59
    /// The graph type of the map.
62 60
    typedef _Graph Graph;
63 61
    /// The item type of the map.
64 62
    typedef _Item Item;
65 63
    /// The reference map tag.
66 64
    typedef True ReferenceMapTag;
67 65

	
68 66
    /// The key type of the map.
69 67
    typedef _Item Key;
70 68
    /// The value type of the map.
71 69
    typedef _Value Value;
72 70

	
73 71
    /// The notifier type.
74 72
    typedef typename ItemSetTraits<_Graph, _Item>::ItemNotifier Notifier;
75 73

	
76 74
    /// The map type.
77 75
    typedef VectorMap Map;
78 76
    /// The base class of the map.
79 77
    typedef typename Notifier::ObserverBase Parent;
80 78

	
81 79
    /// The reference type of the map;
82 80
    typedef typename Container::reference Reference;
83 81
    /// The const reference type of the map;
84 82
    typedef typename Container::const_reference ConstReference;
85 83

	
86 84

	
87 85
    /// \brief Constructor to attach the new map into the notifier.
88 86
    ///
89 87
    /// It constructs a map and attachs it into the notifier.
90 88
    /// It adds all the items of the graph to the map.
91 89
    VectorMap(const Graph& graph) {
92 90
      Parent::attach(graph.notifier(Item()));
93 91
      container.resize(Parent::notifier()->maxId() + 1);
94 92
    }
95 93

	
96 94
    /// \brief Constructor uses given value to initialize the map.
97 95
    ///
98 96
    /// It constructs a map uses a given value to initialize the map.
99 97
    /// It adds all the items of the graph to the map.
100 98
    VectorMap(const Graph& graph, const Value& value) {
101 99
      Parent::attach(graph.notifier(Item()));
102 100
      container.resize(Parent::notifier()->maxId() + 1, value);
103 101
    }
104 102

	
105 103
    /// \brief Copy constructor
106 104
    ///
107 105
    /// Copy constructor.
108 106
    VectorMap(const VectorMap& _copy) : Parent() {
109 107
      if (_copy.attached()) {
110 108
        Parent::attach(*_copy.notifier());
111 109
        container = _copy.container;
112 110
      }
113 111
    }
114 112

	
115 113
    /// \brief Assign operator.
116 114
    ///
117 115
    /// This operator assigns for each item in the map the
118 116
    /// value mapped to the same item in the copied map.
119 117
    /// The parameter map should be indiced with the same
120 118
    /// itemset because this assign operator does not change
121 119
    /// the container of the map.
122 120
    VectorMap& operator=(const VectorMap& cmap) {
123 121
      return operator=<VectorMap>(cmap);
124 122
    }
125 123

	
126 124

	
127 125
    /// \brief Template assign operator.
128 126
    ///
129 127
    /// The given parameter should be conform to the ReadMap
130 128
    /// concecpt and could be indiced by the current item set of
131 129
    /// the NodeMap. In this case the value for each item
132 130
    /// is assigned by the value of the given ReadMap.
133 131
    template <typename CMap>
134 132
    VectorMap& operator=(const CMap& cmap) {
135 133
      checkConcept<concepts::ReadMap<Key, _Value>, CMap>();
136 134
      const typename Parent::Notifier* nf = Parent::notifier();
137 135
      Item it;
138 136
      for (nf->first(it); it != INVALID; nf->next(it)) {
139 137
        set(it, cmap[it]);
140 138
      }
141 139
      return *this;
142 140
    }
143 141

	
144 142
  public:
145 143

	
146 144
    /// \brief The subcript operator.
147 145
    ///
148 146
    /// The subscript operator. The map can be subscripted by the
149 147
    /// actual items of the graph.
150 148
    Reference operator[](const Key& key) {
151 149
      return container[Parent::notifier()->id(key)];
152 150
    }
153 151

	
154 152
    /// \brief The const subcript operator.
155 153
    ///
156 154
    /// The const subscript operator. The map can be subscripted by the
157 155
    /// actual items of the graph.
158 156
    ConstReference operator[](const Key& key) const {
159 157
      return container[Parent::notifier()->id(key)];
160 158
    }
161 159

	
162 160

	
163 161
    /// \brief The setter function of the map.
164 162
    ///
165 163
    /// It the same as operator[](key) = value expression.
166 164
    void set(const Key& key, const Value& value) {
167 165
      (*this)[key] = value;
168 166
    }
169 167

	
170 168
  protected:
171 169

	
172 170
    /// \brief Adds a new key to the map.
173 171
    ///
174 172
    /// It adds a new key to the map. It called by the observer notifier
175 173
    /// and it overrides the add() member function of the observer base.
176 174
    virtual void add(const Key& key) {
177 175
      int id = Parent::notifier()->id(key);
178 176
      if (id >= int(container.size())) {
179 177
        container.resize(id + 1);
180 178
      }
181 179
    }
182 180

	
183 181
    /// \brief Adds more new keys to the map.
184 182
    ///
185 183
    /// It adds more new keys to the map. It called by the observer notifier
186 184
    /// and it overrides the add() member function of the observer base.
187 185
    virtual void add(const std::vector<Key>& keys) {
188 186
      int max = container.size() - 1;
189 187
      for (int i = 0; i < int(keys.size()); ++i) {
190 188
        int id = Parent::notifier()->id(keys[i]);
191 189
        if (id >= max) {
192 190
          max = id;
193 191
        }
194 192
      }
195 193
      container.resize(max + 1);
196 194
    }
197 195

	
198 196
    /// \brief Erase a key from the map.
199 197
    ///
200 198
    /// Erase a key from the map. It called by the observer notifier
201 199
    /// and it overrides the erase() member function of the observer base.
202 200
    virtual void erase(const Key& key) {
203 201
      container[Parent::notifier()->id(key)] = Value();
204 202
    }
205 203

	
206 204
    /// \brief Erase more keys from the map.
207 205
    ///
208 206
    /// Erase more keys from the map. It called by the observer notifier
209 207
    /// and it overrides the erase() member function of the observer base.
210 208
    virtual void erase(const std::vector<Key>& keys) {
211 209
      for (int i = 0; i < int(keys.size()); ++i) {
212 210
        container[Parent::notifier()->id(keys[i])] = Value();
213 211
      }
214 212
    }
215 213

	
216 214
    /// \brief Buildes the map.
217 215
    ///
218 216
    /// It buildes the map. It called by the observer notifier
219 217
    /// and it overrides the build() member function of the observer base.
220 218
    virtual void build() {
221 219
      int size = Parent::notifier()->maxId() + 1;
222 220
      container.reserve(size);
223 221
      container.resize(size);
224 222
    }
225 223

	
226 224
    /// \brief Clear the map.
227 225
    ///
228 226
    /// It erase all items from the map. It called by the observer notifier
229 227
    /// and it overrides the clear() member function of the observer base.
230 228
    virtual void clear() {
231 229
      container.clear();
232 230
    }
233 231

	
234 232
  private:
235 233

	
236 234
    Container container;
237 235

	
238 236
  };
239 237

	
240 238
}
241 239

	
242 240
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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_CONCEPT_DIGRAPH_H
20 20
#define LEMON_CONCEPT_DIGRAPH_H
21 21

	
22 22
///\ingroup graph_concepts
23 23
///\file
24 24
///\brief The concept of directed graphs.
25 25

	
26
#include <lemon/bits/invalid.h>
27
#include <lemon/bits/utility.h>
26
#include <lemon/core.h>
28 27
#include <lemon/concepts/maps.h>
29 28
#include <lemon/concept_check.h>
30 29
#include <lemon/concepts/graph_components.h>
31 30

	
32 31
namespace lemon {
33 32
  namespace concepts {
34 33

	
35 34
    /// \ingroup graph_concepts
36 35
    ///
37 36
    /// \brief Class describing the concept of directed graphs.
38 37
    ///
39 38
    /// This class describes the \ref concept "concept" of the
40 39
    /// immutable directed digraphs.
41 40
    ///
42 41
    /// Note that actual digraph implementation like @ref ListDigraph or
43 42
    /// @ref SmartDigraph may have several additional functionality.
44 43
    ///
45 44
    /// \sa concept
46 45
    class Digraph {
47 46
    private:
48 47
      ///Digraphs are \e not copy constructible. Use DigraphCopy() instead.
49 48

	
50 49
      ///Digraphs are \e not copy constructible. Use DigraphCopy() instead.
51 50
      ///
52 51
      Digraph(const Digraph &) {};
53 52
      ///\brief Assignment of \ref Digraph "Digraph"s to another ones are
54 53
      ///\e not allowed. Use DigraphCopy() instead.
55 54

	
56 55
      ///Assignment of \ref Digraph "Digraph"s to another ones are
57 56
      ///\e not allowed.  Use DigraphCopy() instead.
58 57

	
59 58
      void operator=(const Digraph &) {}
60 59
    public:
61 60
      ///\e
62 61

	
63 62
      /// Defalult constructor.
64 63

	
65 64
      /// Defalult constructor.
66 65
      ///
67 66
      Digraph() { }
68 67
      /// Class for identifying a node of the digraph
69 68

	
70 69
      /// This class identifies a node of the digraph. It also serves
71 70
      /// as a base class of the node iterators,
72 71
      /// thus they will convert to this type.
73 72
      class Node {
74 73
      public:
75 74
        /// Default constructor
76 75

	
77 76
        /// @warning The default constructor sets the iterator
78 77
        /// to an undefined value.
79 78
        Node() { }
80 79
        /// Copy constructor.
81 80

	
82 81
        /// Copy constructor.
83 82
        ///
84 83
        Node(const Node&) { }
85 84

	
86 85
        /// Invalid constructor \& conversion.
87 86

	
88 87
        /// This constructor initializes the iterator to be invalid.
89 88
        /// \sa Invalid for more details.
90 89
        Node(Invalid) { }
91 90
        /// Equality operator
92 91

	
93 92
        /// Two iterators are equal if and only if they point to the
94 93
        /// same object or both are invalid.
95 94
        bool operator==(Node) const { return true; }
96 95

	
97 96
        /// Inequality operator
98 97

	
99 98
        /// \sa operator==(Node n)
100 99
        ///
101 100
        bool operator!=(Node) const { return true; }
102 101

	
103 102
        /// Artificial ordering operator.
104 103

	
105 104
        /// To allow the use of digraph descriptors as key type in std::map or
106 105
        /// similar associative container we require this.
107 106
        ///
108 107
        /// \note This operator only have to define some strict ordering of
109 108
        /// the items; this order has nothing to do with the iteration
110 109
        /// ordering of the items.
111 110
        bool operator<(Node) const { return false; }
112 111

	
113 112
      };
114 113

	
115 114
      /// This iterator goes through each node.
116 115

	
117 116
      /// This iterator goes through each node.
118 117
      /// Its usage is quite simple, for example you can count the number
119 118
      /// of nodes in digraph \c g of type \c Digraph like this:
120 119
      ///\code
121 120
      /// int count=0;
122 121
      /// for (Digraph::NodeIt n(g); n!=INVALID; ++n) ++count;
123 122
      ///\endcode
124 123
      class NodeIt : public Node {
125 124
      public:
126 125
        /// Default constructor
127 126

	
128 127
        /// @warning The default constructor sets the iterator
129 128
        /// to an undefined value.
130 129
        NodeIt() { }
131 130
        /// Copy constructor.
132 131

	
133 132
        /// Copy constructor.
134 133
        ///
135 134
        NodeIt(const NodeIt& n) : Node(n) { }
136 135
        /// Invalid constructor \& conversion.
137 136

	
138 137
        /// Initialize the iterator to be invalid.
139 138
        /// \sa Invalid for more details.
140 139
        NodeIt(Invalid) { }
141 140
        /// Sets the iterator to the first node.
142 141

	
143 142
        /// Sets the iterator to the first node of \c g.
144 143
        ///
145 144
        NodeIt(const Digraph&) { }
146 145
        /// Node -> NodeIt conversion.
147 146

	
148 147
        /// Sets the iterator to the node of \c the digraph pointed by
149 148
        /// the trivial iterator.
150 149
        /// This feature necessitates that each time we
151 150
        /// iterate the arc-set, the iteration order is the same.
152 151
        NodeIt(const Digraph&, const Node&) { }
153 152
        /// Next node.
154 153

	
155 154
        /// Assign the iterator to the next node.
156 155
        ///
157 156
        NodeIt& operator++() { return *this; }
158 157
      };
159 158

	
160 159

	
161 160
      /// Class for identifying an arc of the digraph
162 161

	
163 162
      /// This class identifies an arc of the digraph. It also serves
164 163
      /// as a base class of the arc iterators,
165 164
      /// thus they will convert to this type.
166 165
      class Arc {
167 166
      public:
168 167
        /// Default constructor
169 168

	
170 169
        /// @warning The default constructor sets the iterator
171 170
        /// to an undefined value.
172 171
        Arc() { }
173 172
        /// Copy constructor.
174 173

	
175 174
        /// Copy constructor.
176 175
        ///
177 176
        Arc(const Arc&) { }
178 177
        /// Initialize the iterator to be invalid.
179 178

	
180 179
        /// Initialize the iterator to be invalid.
181 180
        ///
182 181
        Arc(Invalid) { }
183 182
        /// Equality operator
184 183

	
185 184
        /// Two iterators are equal if and only if they point to the
186 185
        /// same object or both are invalid.
187 186
        bool operator==(Arc) const { return true; }
188 187
        /// Inequality operator
189 188

	
190 189
        /// \sa operator==(Arc n)
191 190
        ///
192 191
        bool operator!=(Arc) const { return true; }
193 192

	
194 193
        /// Artificial ordering operator.
195 194

	
196 195
        /// To allow the use of digraph descriptors as key type in std::map or
197 196
        /// similar associative container we require this.
198 197
        ///
199 198
        /// \note This operator only have to define some strict ordering of
200 199
        /// the items; this order has nothing to do with the iteration
201 200
        /// ordering of the items.
202 201
        bool operator<(Arc) const { return false; }
203 202
      };
204 203

	
205 204
      /// This iterator goes trough the outgoing arcs of a node.
206 205

	
207 206
      /// This iterator goes trough the \e outgoing arcs of a certain node
208 207
      /// of a digraph.
209 208
      /// Its usage is quite simple, for example you can count the number
210 209
      /// of outgoing arcs of a node \c n
211 210
      /// in digraph \c g of type \c Digraph as follows.
212 211
      ///\code
213 212
      /// int count=0;
214 213
      /// for (Digraph::OutArcIt e(g, n); e!=INVALID; ++e) ++count;
215 214
      ///\endcode
216 215

	
217 216
      class OutArcIt : public Arc {
218 217
      public:
219 218
        /// Default constructor
220 219

	
221 220
        /// @warning The default constructor sets the iterator
222 221
        /// to an undefined value.
223 222
        OutArcIt() { }
224 223
        /// Copy constructor.
225 224

	
226 225
        /// Copy constructor.
227 226
        ///
228 227
        OutArcIt(const OutArcIt& e) : Arc(e) { }
229 228
        /// Initialize the iterator to be invalid.
230 229

	
231 230
        /// Initialize the iterator to be invalid.
232 231
        ///
233 232
        OutArcIt(Invalid) { }
234 233
        /// This constructor sets the iterator to the first outgoing arc.
235 234

	
236 235
        /// This constructor sets the iterator to the first outgoing arc of
237 236
        /// the node.
238 237
        OutArcIt(const Digraph&, const Node&) { }
239 238
        /// Arc -> OutArcIt conversion
240 239

	
241 240
        /// Sets the iterator to the value of the trivial iterator.
242 241
        /// This feature necessitates that each time we
243 242
        /// iterate the arc-set, the iteration order is the same.
244 243
        OutArcIt(const Digraph&, const Arc&) { }
245 244
        ///Next outgoing arc
246 245

	
247 246
        /// Assign the iterator to the next
248 247
        /// outgoing arc of the corresponding node.
249 248
        OutArcIt& operator++() { return *this; }
250 249
      };
251 250

	
252 251
      /// This iterator goes trough the incoming arcs of a node.
253 252

	
254 253
      /// This iterator goes trough the \e incoming arcs of a certain node
255 254
      /// of a digraph.
256 255
      /// Its usage is quite simple, for example you can count the number
257 256
      /// of outgoing arcs of a node \c n
258 257
      /// in digraph \c g of type \c Digraph as follows.
259 258
      ///\code
260 259
      /// int count=0;
261 260
      /// for(Digraph::InArcIt e(g, n); e!=INVALID; ++e) ++count;
262 261
      ///\endcode
263 262

	
264 263
      class InArcIt : public Arc {
265 264
      public:
266 265
        /// Default constructor
267 266

	
268 267
        /// @warning The default constructor sets the iterator
269 268
        /// to an undefined value.
270 269
        InArcIt() { }
271 270
        /// Copy constructor.
272 271

	
273 272
        /// Copy constructor.
274 273
        ///
275 274
        InArcIt(const InArcIt& e) : Arc(e) { }
276 275
        /// Initialize the iterator to be invalid.
277 276

	
278 277
        /// Initialize the iterator to be invalid.
279 278
        ///
280 279
        InArcIt(Invalid) { }
281 280
        /// This constructor sets the iterator to first incoming arc.
282 281

	
283 282
        /// This constructor set the iterator to the first incoming arc of
284 283
        /// the node.
285 284
        InArcIt(const Digraph&, const Node&) { }
286 285
        /// Arc -> InArcIt conversion
287 286

	
288 287
        /// Sets the iterator to the value of the trivial iterator \c e.
289 288
        /// This feature necessitates that each time we
290 289
        /// iterate the arc-set, the iteration order is the same.
291 290
        InArcIt(const Digraph&, const Arc&) { }
292 291
        /// Next incoming arc
293 292

	
294 293
        /// Assign the iterator to the next inarc of the corresponding node.
295 294
        ///
296 295
        InArcIt& operator++() { return *this; }
297 296
      };
298 297
      /// This iterator goes through each arc.
299 298

	
300 299
      /// This iterator goes through each arc of a digraph.
301 300
      /// Its usage is quite simple, for example you can count the number
302 301
      /// of arcs in a digraph \c g of type \c Digraph as follows:
303 302
      ///\code
304 303
      /// int count=0;
305 304
      /// for(Digraph::ArcIt e(g); e!=INVALID; ++e) ++count;
306 305
      ///\endcode
307 306
      class ArcIt : public Arc {
308 307
      public:
309 308
        /// Default constructor
310 309

	
311 310
        /// @warning The default constructor sets the iterator
312 311
        /// to an undefined value.
313 312
        ArcIt() { }
314 313
        /// Copy constructor.
315 314

	
316 315
        /// Copy constructor.
317 316
        ///
318 317
        ArcIt(const ArcIt& e) : Arc(e) { }
319 318
        /// Initialize the iterator to be invalid.
320 319

	
321 320
        /// Initialize the iterator to be invalid.
322 321
        ///
323 322
        ArcIt(Invalid) { }
324 323
        /// This constructor sets the iterator to the first arc.
325 324

	
326 325
        /// This constructor sets the iterator to the first arc of \c g.
327 326
        ///@param g the digraph
328 327
        ArcIt(const Digraph& g) { ignore_unused_variable_warning(g); }
329 328
        /// Arc -> ArcIt conversion
330 329

	
331 330
        /// Sets the iterator to the value of the trivial iterator \c e.
332 331
        /// This feature necessitates that each time we
333 332
        /// iterate the arc-set, the iteration order is the same.
334 333
        ArcIt(const Digraph&, const Arc&) { }
335 334
        ///Next arc
336 335

	
337 336
        /// Assign the iterator to the next arc.
338 337
        ArcIt& operator++() { return *this; }
339 338
      };
340 339
      ///Gives back the target node of an arc.
341 340

	
342 341
      ///Gives back the target node of an arc.
343 342
      ///
344 343
      Node target(Arc) const { return INVALID; }
345 344
      ///Gives back the source node of an arc.
346 345

	
347 346
      ///Gives back the source node of an arc.
348 347
      ///
349 348
      Node source(Arc) const { return INVALID; }
350 349

	
351 350
      /// \brief Returns the ID of the node.
352 351
      int id(Node) const { return -1; }
353 352

	
354 353
      /// \brief Returns the ID of the arc.
355 354
      int id(Arc) const { return -1; }
356 355

	
357 356
      /// \brief Returns the node with the given ID.
358 357
      ///
359 358
      /// \pre The argument should be a valid node ID in the graph.
360 359
      Node nodeFromId(int) const { return INVALID; }
361 360

	
362 361
      /// \brief Returns the arc with the given ID.
363 362
      ///
364 363
      /// \pre The argument should be a valid arc ID in the graph.
365 364
      Arc arcFromId(int) const { return INVALID; }
366 365

	
367 366
      /// \brief Returns an upper bound on the node IDs.
368 367
      int maxNodeId() const { return -1; }
369 368

	
370 369
      /// \brief Returns an upper bound on the arc IDs.
371 370
      int maxArcId() const { return -1; }
372 371

	
373 372
      void first(Node&) const {}
374 373
      void next(Node&) const {}
375 374

	
376 375
      void first(Arc&) const {}
377 376
      void next(Arc&) const {}
378 377

	
379 378

	
380 379
      void firstIn(Arc&, const Node&) const {}
381 380
      void nextIn(Arc&) const {}
382 381

	
383 382
      void firstOut(Arc&, const Node&) const {}
384 383
      void nextOut(Arc&) const {}
385 384

	
386 385
      // The second parameter is dummy.
387 386
      Node fromId(int, Node) const { return INVALID; }
388 387
      // The second parameter is dummy.
389 388
      Arc fromId(int, Arc) const { return INVALID; }
390 389

	
391 390
      // Dummy parameter.
392 391
      int maxId(Node) const { return -1; }
393 392
      // Dummy parameter.
394 393
      int maxId(Arc) const { return -1; }
395 394

	
396 395
      /// \brief The base node of the iterator.
397 396
      ///
398 397
      /// Gives back the base node of the iterator.
399 398
      /// It is always the target of the pointed arc.
400 399
      Node baseNode(const InArcIt&) const { return INVALID; }
401 400

	
402 401
      /// \brief The running node of the iterator.
403 402
      ///
404 403
      /// Gives back the running node of the iterator.
405 404
      /// It is always the source of the pointed arc.
406 405
      Node runningNode(const InArcIt&) const { return INVALID; }
407 406

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

	
19 19
///\ingroup graph_concepts
20 20
///\file
21 21
///\brief The concept of Undirected Graphs.
22 22

	
23 23
#ifndef LEMON_CONCEPT_GRAPH_H
24 24
#define LEMON_CONCEPT_GRAPH_H
25 25

	
26 26
#include <lemon/concepts/graph_components.h>
27 27
#include <lemon/concepts/graph.h>
28
#include <lemon/bits/utility.h>
28
#include <lemon/core.h>
29 29

	
30 30
namespace lemon {
31 31
  namespace concepts {
32 32

	
33 33
    /// \ingroup graph_concepts
34 34
    ///
35 35
    /// \brief Class describing the concept of Undirected Graphs.
36 36
    ///
37 37
    /// This class describes the common interface of all Undirected
38 38
    /// Graphs.
39 39
    ///
40 40
    /// As all concept describing classes it provides only interface
41 41
    /// without any sensible implementation. So any algorithm for
42 42
    /// undirected graph should compile with this class, but it will not
43 43
    /// run properly, of course.
44 44
    ///
45 45
    /// The LEMON undirected graphs also fulfill the concept of
46 46
    /// directed graphs (\ref lemon::concepts::Digraph "Digraph
47 47
    /// Concept"). Each edges can be seen as two opposite
48 48
    /// directed arc and consequently the undirected graph can be
49 49
    /// seen as the direceted graph of these directed arcs. The
50 50
    /// Graph has the Edge inner class for the edges and
51 51
    /// the Arc type for the directed arcs. The Arc type is
52 52
    /// convertible to Edge or inherited from it so from a directed
53 53
    /// arc we can get the represented edge.
54 54
    ///
55 55
    /// In the sense of the LEMON each edge has a default
56 56
    /// direction (it should be in every computer implementation,
57 57
    /// because the order of edge's nodes defines an
58 58
    /// orientation). With the default orientation we can define that
59 59
    /// the directed arc is forward or backward directed. With the \c
60 60
    /// direction() and \c direct() function we can get the direction
61 61
    /// of the directed arc and we can direct an edge.
62 62
    ///
63 63
    /// The EdgeIt is an iterator for the edges. We can use
64 64
    /// the EdgeMap to map values for the edges. The InArcIt and
65 65
    /// OutArcIt iterates on the same edges but with opposite
66 66
    /// direction. The IncEdgeIt iterates also on the same edges
67 67
    /// as the OutArcIt and InArcIt but it is not convertible to Arc just
68 68
    /// to Edge.
69 69
    class Graph {
70 70
    public:
71 71
      /// \brief The undirected graph should be tagged by the
72 72
      /// UndirectedTag.
73 73
      ///
74 74
      /// The undirected graph should be tagged by the UndirectedTag. This
75 75
      /// tag helps the enable_if technics to make compile time
76 76
      /// specializations for undirected graphs.
77 77
      typedef True UndirectedTag;
78 78

	
79 79
      /// \brief The base type of node iterators,
80 80
      /// or in other words, the trivial node iterator.
81 81
      ///
82 82
      /// This is the base type of each node iterator,
83 83
      /// thus each kind of node iterator converts to this.
84 84
      /// More precisely each kind of node iterator should be inherited
85 85
      /// from the trivial node iterator.
86 86
      class Node {
87 87
      public:
88 88
        /// Default constructor
89 89

	
90 90
        /// @warning The default constructor sets the iterator
91 91
        /// to an undefined value.
92 92
        Node() { }
93 93
        /// Copy constructor.
94 94

	
95 95
        /// Copy constructor.
96 96
        ///
97 97
        Node(const Node&) { }
98 98

	
99 99
        /// Invalid constructor \& conversion.
100 100

	
101 101
        /// This constructor initializes the iterator to be invalid.
102 102
        /// \sa Invalid for more details.
103 103
        Node(Invalid) { }
104 104
        /// Equality operator
105 105

	
106 106
        /// Two iterators are equal if and only if they point to the
107 107
        /// same object or both are invalid.
108 108
        bool operator==(Node) const { return true; }
109 109

	
110 110
        /// Inequality operator
111 111

	
112 112
        /// \sa operator==(Node n)
113 113
        ///
114 114
        bool operator!=(Node) const { return true; }
115 115

	
116 116
        /// Artificial ordering operator.
117 117

	
118 118
        /// To allow the use of graph descriptors as key type in std::map or
119 119
        /// similar associative container we require this.
120 120
        ///
121 121
        /// \note This operator only have to define some strict ordering of
122 122
        /// the items; this order has nothing to do with the iteration
123 123
        /// ordering of the items.
124 124
        bool operator<(Node) const { return false; }
125 125

	
126 126
      };
127 127

	
128 128
      /// This iterator goes through each node.
129 129

	
130 130
      /// This iterator goes through each node.
131 131
      /// Its usage is quite simple, for example you can count the number
132 132
      /// of nodes in graph \c g of type \c Graph like this:
133 133
      ///\code
134 134
      /// int count=0;
135 135
      /// for (Graph::NodeIt n(g); n!=INVALID; ++n) ++count;
136 136
      ///\endcode
137 137
      class NodeIt : public Node {
138 138
      public:
139 139
        /// Default constructor
140 140

	
141 141
        /// @warning The default constructor sets the iterator
142 142
        /// to an undefined value.
143 143
        NodeIt() { }
144 144
        /// Copy constructor.
145 145

	
146 146
        /// Copy constructor.
147 147
        ///
148 148
        NodeIt(const NodeIt& n) : Node(n) { }
149 149
        /// Invalid constructor \& conversion.
150 150

	
151 151
        /// Initialize the iterator to be invalid.
152 152
        /// \sa Invalid for more details.
153 153
        NodeIt(Invalid) { }
154 154
        /// Sets the iterator to the first node.
155 155

	
156 156
        /// Sets the iterator to the first node of \c g.
157 157
        ///
158 158
        NodeIt(const Graph&) { }
159 159
        /// Node -> NodeIt conversion.
160 160

	
161 161
        /// Sets the iterator to the node of \c the graph pointed by
162 162
        /// the trivial iterator.
163 163
        /// This feature necessitates that each time we
164 164
        /// iterate the arc-set, the iteration order is the same.
165 165
        NodeIt(const Graph&, const Node&) { }
166 166
        /// Next node.
167 167

	
168 168
        /// Assign the iterator to the next node.
169 169
        ///
170 170
        NodeIt& operator++() { return *this; }
171 171
      };
172 172

	
173 173

	
174 174
      /// The base type of the edge iterators.
175 175

	
176 176
      /// The base type of the edge iterators.
177 177
      ///
178 178
      class Edge {
179 179
      public:
180 180
        /// Default constructor
181 181

	
182 182
        /// @warning The default constructor sets the iterator
183 183
        /// to an undefined value.
184 184
        Edge() { }
185 185
        /// Copy constructor.
186 186

	
187 187
        /// Copy constructor.
188 188
        ///
189 189
        Edge(const Edge&) { }
190 190
        /// Initialize the iterator to be invalid.
191 191

	
192 192
        /// Initialize the iterator to be invalid.
193 193
        ///
194 194
        Edge(Invalid) { }
195 195
        /// Equality operator
196 196

	
197 197
        /// Two iterators are equal if and only if they point to the
198 198
        /// same object or both are invalid.
199 199
        bool operator==(Edge) const { return true; }
200 200
        /// Inequality operator
201 201

	
202 202
        /// \sa operator==(Edge n)
203 203
        ///
204 204
        bool operator!=(Edge) const { return true; }
205 205

	
206 206
        /// Artificial ordering operator.
207 207

	
208 208
        /// To allow the use of graph descriptors as key type in std::map or
209 209
        /// similar associative container we require this.
210 210
        ///
211 211
        /// \note This operator only have to define some strict ordering of
212 212
        /// the items; this order has nothing to do with the iteration
213 213
        /// ordering of the items.
214 214
        bool operator<(Edge) const { return false; }
215 215
      };
216 216

	
217 217
      /// This iterator goes through each edge.
218 218

	
219 219
      /// This iterator goes through each edge of a graph.
220 220
      /// Its usage is quite simple, for example you can count the number
221 221
      /// of edges in a graph \c g of type \c Graph as follows:
222 222
      ///\code
223 223
      /// int count=0;
224 224
      /// for(Graph::EdgeIt e(g); e!=INVALID; ++e) ++count;
225 225
      ///\endcode
226 226
      class EdgeIt : public Edge {
227 227
      public:
228 228
        /// Default constructor
229 229

	
230 230
        /// @warning The default constructor sets the iterator
231 231
        /// to an undefined value.
232 232
        EdgeIt() { }
233 233
        /// Copy constructor.
234 234

	
235 235
        /// Copy constructor.
236 236
        ///
237 237
        EdgeIt(const EdgeIt& e) : Edge(e) { }
238 238
        /// Initialize the iterator to be invalid.
239 239

	
240 240
        /// Initialize the iterator to be invalid.
241 241
        ///
242 242
        EdgeIt(Invalid) { }
243 243
        /// This constructor sets the iterator to the first edge.
244 244

	
245 245
        /// This constructor sets the iterator to the first edge.
246 246
        EdgeIt(const Graph&) { }
247 247
        /// Edge -> EdgeIt conversion
248 248

	
249 249
        /// Sets the iterator to the value of the trivial iterator.
250 250
        /// This feature necessitates that each time we
251 251
        /// iterate the edge-set, the iteration order is the
252 252
        /// same.
253 253
        EdgeIt(const Graph&, const Edge&) { }
254 254
        /// Next edge
255 255

	
256 256
        /// Assign the iterator to the next edge.
257 257
        EdgeIt& operator++() { return *this; }
258 258
      };
259 259

	
260 260
      /// \brief This iterator goes trough the incident undirected
261 261
      /// arcs of a node.
262 262
      ///
263 263
      /// This iterator goes trough the incident edges
264 264
      /// of a certain node of a graph. You should assume that the
265 265
      /// loop arcs will be iterated twice.
266 266
      ///
267 267
      /// Its usage is quite simple, for example you can compute the
268 268
      /// degree (i.e. count the number of incident arcs of a node \c n
269 269
      /// in graph \c g of type \c Graph as follows.
270 270
      ///
271 271
      ///\code
272 272
      /// int count=0;
273 273
      /// for(Graph::IncEdgeIt e(g, n); e!=INVALID; ++e) ++count;
274 274
      ///\endcode
275 275
      class IncEdgeIt : public Edge {
276 276
      public:
277 277
        /// Default constructor
278 278

	
279 279
        /// @warning The default constructor sets the iterator
280 280
        /// to an undefined value.
281 281
        IncEdgeIt() { }
282 282
        /// Copy constructor.
283 283

	
284 284
        /// Copy constructor.
285 285
        ///
286 286
        IncEdgeIt(const IncEdgeIt& e) : Edge(e) { }
287 287
        /// Initialize the iterator to be invalid.
288 288

	
289 289
        /// Initialize the iterator to be invalid.
290 290
        ///
291 291
        IncEdgeIt(Invalid) { }
292 292
        /// This constructor sets the iterator to first incident arc.
293 293

	
294 294
        /// This constructor set the iterator to the first incident arc of
295 295
        /// the node.
296 296
        IncEdgeIt(const Graph&, const Node&) { }
297 297
        /// Edge -> IncEdgeIt conversion
298 298

	
299 299
        /// Sets the iterator to the value of the trivial iterator \c e.
300 300
        /// This feature necessitates that each time we
301 301
        /// iterate the arc-set, the iteration order is the same.
302 302
        IncEdgeIt(const Graph&, const Edge&) { }
303 303
        /// Next incident arc
304 304

	
305 305
        /// Assign the iterator to the next incident arc
306 306
        /// of the corresponding node.
307 307
        IncEdgeIt& operator++() { return *this; }
308 308
      };
309 309

	
310 310
      /// The directed arc type.
311 311

	
312 312
      /// The directed arc type. It can be converted to the
313 313
      /// edge or it should be inherited from the undirected
314 314
      /// arc.
315 315
      class Arc : public Edge {
316 316
      public:
317 317
        /// Default constructor
318 318

	
319 319
        /// @warning The default constructor sets the iterator
320 320
        /// to an undefined value.
321 321
        Arc() { }
322 322
        /// Copy constructor.
323 323

	
324 324
        /// Copy constructor.
325 325
        ///
326 326
        Arc(const Arc& e) : Edge(e) { }
327 327
        /// Initialize the iterator to be invalid.
328 328

	
329 329
        /// Initialize the iterator to be invalid.
330 330
        ///
331 331
        Arc(Invalid) { }
332 332
        /// Equality operator
333 333

	
334 334
        /// Two iterators are equal if and only if they point to the
335 335
        /// same object or both are invalid.
336 336
        bool operator==(Arc) const { return true; }
337 337
        /// Inequality operator
338 338

	
339 339
        /// \sa operator==(Arc n)
340 340
        ///
341 341
        bool operator!=(Arc) const { return true; }
342 342

	
343 343
        /// Artificial ordering operator.
344 344

	
345 345
        /// To allow the use of graph descriptors as key type in std::map or
346 346
        /// similar associative container we require this.
347 347
        ///
348 348
        /// \note This operator only have to define some strict ordering of
349 349
        /// the items; this order has nothing to do with the iteration
350 350
        /// ordering of the items.
351 351
        bool operator<(Arc) const { return false; }
352 352

	
353 353
      };
354 354
      /// This iterator goes through each directed arc.
355 355

	
356 356
      /// This iterator goes through each arc of a graph.
357 357
      /// Its usage is quite simple, for example you can count the number
358 358
      /// of arcs in a graph \c g of type \c Graph as follows:
359 359
      ///\code
360 360
      /// int count=0;
361 361
      /// for(Graph::ArcIt e(g); e!=INVALID; ++e) ++count;
362 362
      ///\endcode
363 363
      class ArcIt : public Arc {
364 364
      public:
365 365
        /// Default constructor
366 366

	
367 367
        /// @warning The default constructor sets the iterator
368 368
        /// to an undefined value.
369 369
        ArcIt() { }
370 370
        /// Copy constructor.
371 371

	
372 372
        /// Copy constructor.
373 373
        ///
374 374
        ArcIt(const ArcIt& e) : Arc(e) { }
375 375
        /// Initialize the iterator to be invalid.
376 376

	
377 377
        /// Initialize the iterator to be invalid.
378 378
        ///
379 379
        ArcIt(Invalid) { }
380 380
        /// This constructor sets the iterator to the first arc.
381 381

	
382 382
        /// This constructor sets the iterator to the first arc of \c g.
383 383
        ///@param g the graph
384 384
        ArcIt(const Graph &g) { ignore_unused_variable_warning(g); }
385 385
        /// Arc -> ArcIt conversion
386 386

	
387 387
        /// Sets the iterator to the value of the trivial iterator \c e.
388 388
        /// This feature necessitates that each time we
389 389
        /// iterate the arc-set, the iteration order is the same.
390 390
        ArcIt(const Graph&, const Arc&) { }
391 391
        ///Next arc
392 392

	
393 393
        /// Assign the iterator to the next arc.
394 394
        ArcIt& operator++() { return *this; }
395 395
      };
396 396

	
397 397
      /// This iterator goes trough the outgoing directed arcs of a node.
398 398

	
399 399
      /// This iterator goes trough the \e outgoing arcs of a certain node
400 400
      /// of a graph.
401 401
      /// Its usage is quite simple, for example you can count the number
402 402
      /// of outgoing arcs of a node \c n
403 403
      /// in graph \c g of type \c Graph as follows.
404 404
      ///\code
405 405
      /// int count=0;
406 406
      /// for (Graph::OutArcIt e(g, n); e!=INVALID; ++e) ++count;
407 407
      ///\endcode
408 408

	
409 409
      class OutArcIt : public Arc {
410 410
      public:
411 411
        /// Default constructor
412 412

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

	
19 19
///\ingroup graph_concepts
20 20
///\file
21 21
///\brief The concept of graph components.
22 22

	
23 23

	
24 24
#ifndef LEMON_CONCEPT_GRAPH_COMPONENTS_H
25 25
#define LEMON_CONCEPT_GRAPH_COMPONENTS_H
26 26

	
27
#include <lemon/bits/invalid.h>
27
#include <lemon/core.h>
28 28
#include <lemon/concepts/maps.h>
29 29

	
30 30
#include <lemon/bits/alteration_notifier.h>
31 31

	
32 32
namespace lemon {
33 33
  namespace concepts {
34 34

	
35 35
    /// \brief Skeleton class for graph Node and Arc types
36 36
    ///
37 37
    /// This class describes the interface of Node and Arc (and Edge
38 38
    /// in undirected graphs) subtypes of graph types.
39 39
    ///
40 40
    /// \note This class is a template class so that we can use it to
41 41
    /// create graph skeleton classes. The reason for this is than Node
42 42
    /// and Arc types should \em not derive from the same base class.
43 43
    /// For Node you should instantiate it with character 'n' and for Arc
44 44
    /// with 'a'.
45 45

	
46 46
#ifndef DOXYGEN
47 47
    template <char _selector = '0'>
48 48
#endif
49 49
    class GraphItem {
50 50
    public:
51 51
      /// \brief Default constructor.
52 52
      ///
53 53
      /// \warning The default constructor is not required to set
54 54
      /// the item to some well-defined value. So you should consider it
55 55
      /// as uninitialized.
56 56
      GraphItem() {}
57 57
      /// \brief Copy constructor.
58 58
      ///
59 59
      /// Copy constructor.
60 60
      ///
61 61
      GraphItem(const GraphItem &) {}
62 62
      /// \brief Invalid constructor \& conversion.
63 63
      ///
64 64
      /// This constructor initializes the item to be invalid.
65 65
      /// \sa Invalid for more details.
66 66
      GraphItem(Invalid) {}
67 67
      /// \brief Assign operator for nodes.
68 68
      ///
69 69
      /// The nodes are assignable.
70 70
      ///
71 71
      GraphItem& operator=(GraphItem const&) { return *this; }
72 72
      /// \brief Equality operator.
73 73
      ///
74 74
      /// Two iterators are equal if and only if they represents the
75 75
      /// same node in the graph or both are invalid.
76 76
      bool operator==(GraphItem) const { return false; }
77 77
      /// \brief Inequality operator.
78 78
      ///
79 79
      /// \sa operator==(const Node& n)
80 80
      ///
81 81
      bool operator!=(GraphItem) const { return false; }
82 82

	
83 83
      /// \brief Artificial ordering operator.
84 84
      ///
85 85
      /// To allow the use of graph descriptors as key type in std::map or
86 86
      /// similar associative container we require this.
87 87
      ///
88 88
      /// \note This operator only have to define some strict ordering of
89 89
      /// the items; this order has nothing to do with the iteration
90 90
      /// ordering of the items.
91 91
      bool operator<(GraphItem) const { return false; }
92 92

	
93 93
      template<typename _GraphItem>
94 94
      struct Constraints {
95 95
        void constraints() {
96 96
          _GraphItem i1;
97 97
          _GraphItem i2 = i1;
98 98
          _GraphItem i3 = INVALID;
99 99

	
100 100
          i1 = i2 = i3;
101 101

	
102 102
          bool b;
103 103
          //          b = (ia == ib) && (ia != ib) && (ia < ib);
104 104
          b = (ia == ib) && (ia != ib);
105 105
          b = (ia == INVALID) && (ib != INVALID);
106 106
          b = (ia < ib);
107 107
        }
108 108

	
109 109
        const _GraphItem &ia;
110 110
        const _GraphItem &ib;
111 111
      };
112 112
    };
113 113

	
114 114
    /// \brief An empty base directed graph class.
115 115
    ///
116 116
    /// This class provides the minimal set of features needed for a
117 117
    /// directed graph structure. All digraph concepts have to be
118 118
    /// conform to this base directed graph. It just provides types
119 119
    /// for nodes and arcs and functions to get the source and the
120 120
    /// target of the arcs.
121 121
    class BaseDigraphComponent {
122 122
    public:
123 123

	
124 124
      typedef BaseDigraphComponent Digraph;
125 125

	
126 126
      /// \brief Node class of the digraph.
127 127
      ///
128 128
      /// This class represents the Nodes of the digraph.
129 129
      ///
130 130
      typedef GraphItem<'n'> Node;
131 131

	
132 132
      /// \brief Arc class of the digraph.
133 133
      ///
134 134
      /// This class represents the Arcs of the digraph.
135 135
      ///
136 136
      typedef GraphItem<'e'> Arc;
137 137

	
138 138
      /// \brief Gives back the target node of an arc.
139 139
      ///
140 140
      /// Gives back the target node of an arc.
141 141
      ///
142 142
      Node target(const Arc&) const { return INVALID;}
143 143

	
144 144
      /// \brief Gives back the source node of an arc.
145 145
      ///
146 146
      /// Gives back the source node of an arc.
147 147
      ///
148 148
      Node source(const Arc&) const { return INVALID;}
149 149

	
150 150
      /// \brief Gives back the opposite node on the given arc.
151 151
      ///
152 152
      /// Gives back the opposite node on the given arc.
153 153
      Node oppositeNode(const Node&, const Arc&) const {
154 154
        return INVALID;
155 155
      }
156 156

	
157 157
      template <typename _Digraph>
158 158
      struct Constraints {
159 159
        typedef typename _Digraph::Node Node;
160 160
        typedef typename _Digraph::Arc Arc;
161 161

	
162 162
        void constraints() {
163 163
          checkConcept<GraphItem<'n'>, Node>();
164 164
          checkConcept<GraphItem<'a'>, Arc>();
165 165
          {
166 166
            Node n;
167 167
            Arc e(INVALID);
168 168
            n = digraph.source(e);
169 169
            n = digraph.target(e);
170 170
            n = digraph.oppositeNode(n, e);
171 171
          }
172 172
        }
173 173

	
174 174
        const _Digraph& digraph;
175 175
      };
176 176
    };
177 177

	
178 178
    /// \brief An empty base undirected graph class.
179 179
    ///
180 180
    /// This class provides the minimal set of features needed for an
181 181
    /// undirected graph structure. All undirected graph concepts have
182 182
    /// to be conform to this base graph. It just provides types for
183 183
    /// nodes, arcs and edges and functions to get the
184 184
    /// source and the target of the arcs and edges,
185 185
    /// conversion from arcs to edges and function to get
186 186
    /// both direction of the edges.
187 187
    class BaseGraphComponent : public BaseDigraphComponent {
188 188
    public:
189 189
      typedef BaseDigraphComponent::Node Node;
190 190
      typedef BaseDigraphComponent::Arc Arc;
191 191
      /// \brief Undirected arc class of the graph.
192 192
      ///
193 193
      /// This class represents the edges of the graph.
194 194
      /// The undirected graphs can be used as a directed graph which
195 195
      /// for each arc contains the opposite arc too so the graph is
196 196
      /// bidirected. The edge represents two opposite
197 197
      /// directed arcs.
198 198
      class Edge : public GraphItem<'u'> {
199 199
      public:
200 200
        typedef GraphItem<'u'> Parent;
201 201
        /// \brief Default constructor.
202 202
        ///
203 203
        /// \warning The default constructor is not required to set
204 204
        /// the item to some well-defined value. So you should consider it
205 205
        /// as uninitialized.
206 206
        Edge() {}
207 207
        /// \brief Copy constructor.
208 208
        ///
209 209
        /// Copy constructor.
210 210
        ///
211 211
        Edge(const Edge &) : Parent() {}
212 212
        /// \brief Invalid constructor \& conversion.
213 213
        ///
214 214
        /// This constructor initializes the item to be invalid.
215 215
        /// \sa Invalid for more details.
216 216
        Edge(Invalid) {}
217 217
        /// \brief Converter from arc to edge.
218 218
        ///
219 219
        /// Besides the core graph item functionality each arc should
220 220
        /// be convertible to the represented edge.
221 221
        Edge(const Arc&) {}
222 222
        /// \brief Assign arc to edge.
223 223
        ///
224 224
        /// Besides the core graph item functionality each arc should
225 225
        /// be convertible to the represented edge.
226 226
        Edge& operator=(const Arc&) { return *this; }
227 227
      };
228 228

	
229 229
      /// \brief Returns the direction of the arc.
230 230
      ///
231 231
      /// Returns the direction of the arc. Each arc represents an
232 232
      /// edge with a direction. It gives back the
233 233
      /// direction.
234 234
      bool direction(const Arc&) const { return true; }
235 235

	
236 236
      /// \brief Returns the directed arc.
237 237
      ///
238 238
      /// Returns the directed arc from its direction and the
239 239
      /// represented edge.
240 240
      Arc direct(const Edge&, bool) const { return INVALID;}
241 241

	
242 242
      /// \brief Returns the directed arc.
243 243
      ///
244 244
      /// Returns the directed arc from its source and the
245 245
      /// represented edge.
246 246
      Arc direct(const Edge&, const Node&) const { return INVALID;}
247 247

	
248 248
      /// \brief Returns the opposite arc.
249 249
      ///
250 250
      /// Returns the opposite arc. It is the arc representing the
251 251
      /// same edge and has opposite direction.
252 252
      Arc oppositeArc(const Arc&) const { return INVALID;}
253 253

	
254 254
      /// \brief Gives back one ending of an edge.
255 255
      ///
256 256
      /// Gives back one ending of an edge.
257 257
      Node u(const Edge&) const { return INVALID;}
258 258

	
259 259
      /// \brief Gives back the other ending of an edge.
260 260
      ///
261 261
      /// Gives back the other ending of an edge.
262 262
      Node v(const Edge&) const { return INVALID;}
263 263

	
264 264
      template <typename _Graph>
265 265
      struct Constraints {
266 266
        typedef typename _Graph::Node Node;
267 267
        typedef typename _Graph::Arc Arc;
268 268
        typedef typename _Graph::Edge Edge;
269 269

	
270 270
        void constraints() {
271 271
          checkConcept<BaseDigraphComponent, _Graph>();
272 272
          checkConcept<GraphItem<'u'>, Edge>();
273 273
          {
274 274
            Node n;
275 275
            Edge ue(INVALID);
276 276
            Arc e;
277 277
            n = graph.u(ue);
278 278
            n = graph.v(ue);
279 279
            e = graph.direct(ue, true);
280 280
            e = graph.direct(ue, n);
281 281
            e = graph.oppositeArc(e);
282 282
            ue = e;
283 283
            bool d = graph.direction(e);
284 284
            ignore_unused_variable_warning(d);
285 285
          }
286 286
        }
287 287

	
288 288
        const _Graph& graph;
289 289
      };
290 290

	
291 291
    };
292 292

	
293 293
    /// \brief An empty idable base digraph class.
294 294
    ///
295 295
    /// This class provides beside the core digraph features
296 296
    /// core id functions for the digraph structure.
297 297
    /// The most of the base digraphs should be conform to this concept.
298 298
    /// The id's are unique and immutable.
299 299
    template <typename _Base = BaseDigraphComponent>
300 300
    class IDableDigraphComponent : public _Base {
301 301
    public:
302 302

	
303 303
      typedef _Base Base;
304 304
      typedef typename Base::Node Node;
305 305
      typedef typename Base::Arc Arc;
306 306

	
307 307
      /// \brief Gives back an unique integer id for the Node.
308 308
      ///
309 309
      /// Gives back an unique integer id for the Node.
310 310
      ///
311 311
      int id(const Node&) const { return -1;}
312 312

	
313 313
      /// \brief Gives back the node by the unique id.
314 314
      ///
315 315
      /// Gives back the node by the unique id.
316 316
      /// If the digraph does not contain node with the given id
317 317
      /// then the result of the function is undetermined.
318 318
      Node nodeFromId(int) const { return INVALID;}
319 319

	
320 320
      /// \brief Gives back an unique integer id for the Arc.
321 321
      ///
322 322
      /// Gives back an unique integer id for the Arc.
323 323
      ///
324 324
      int id(const Arc&) const { return -1;}
325 325

	
326 326
      /// \brief Gives back the arc by the unique id.
327 327
      ///
328 328
      /// Gives back the arc by the unique id.
329 329
      /// If the digraph does not contain arc with the given id
330 330
      /// then the result of the function is undetermined.
331 331
      Arc arcFromId(int) const { return INVALID;}
332 332

	
333 333
      /// \brief Gives back an integer greater or equal to the maximum
334 334
      /// Node id.
335 335
      ///
336 336
      /// Gives back an integer greater or equal to the maximum Node
337 337
      /// id.
338 338
      int maxNodeId() const { return -1;}
339 339

	
340 340
      /// \brief Gives back an integer greater or equal to the maximum
341 341
      /// Arc id.
342 342
      ///
343 343
      /// Gives back an integer greater or equal to the maximum Arc
344 344
      /// id.
345 345
      int maxArcId() const { return -1;}
346 346

	
347 347
      template <typename _Digraph>
348 348
      struct Constraints {
349 349

	
350 350
        void constraints() {
351 351
          checkConcept<Base, _Digraph >();
352 352
          typename _Digraph::Node node;
353 353
          int nid = digraph.id(node);
354 354
          nid = digraph.id(node);
355 355
          node = digraph.nodeFromId(nid);
356 356
          typename _Digraph::Arc arc;
357 357
          int eid = digraph.id(arc);
358 358
          eid = digraph.id(arc);
359 359
          arc = digraph.arcFromId(eid);
360 360

	
361 361
          nid = digraph.maxNodeId();
362 362
          ignore_unused_variable_warning(nid);
363 363
          eid = digraph.maxArcId();
364 364
          ignore_unused_variable_warning(eid);
365 365
        }
366 366

	
367 367
        const _Digraph& digraph;
368 368
      };
369 369
    };
370 370

	
371 371
    /// \brief An empty idable base undirected graph class.
372 372
    ///
373 373
    /// This class provides beside the core undirected graph features
374 374
    /// core id functions for the undirected graph structure.  The
375 375
    /// most of the base undirected graphs should be conform to this
376 376
    /// concept.  The id's are unique and immutable.
377 377
    template <typename _Base = BaseGraphComponent>
378 378
    class IDableGraphComponent : public IDableDigraphComponent<_Base> {
379 379
    public:
380 380

	
381 381
      typedef _Base Base;
382 382
      typedef typename Base::Edge Edge;
383 383

	
384 384
      using IDableDigraphComponent<_Base>::id;
385 385

	
386 386
      /// \brief Gives back an unique integer id for the Edge.
387 387
      ///
388 388
      /// Gives back an unique integer id for the Edge.
389 389
      ///
390 390
      int id(const Edge&) const { return -1;}
391 391

	
392 392
      /// \brief Gives back the edge by the unique id.
393 393
      ///
394 394
      /// Gives back the edge by the unique id.  If the
395 395
      /// graph does not contain arc with the given id then the
396 396
      /// result of the function is undetermined.
397 397
      Edge edgeFromId(int) const { return INVALID;}
398 398

	
399 399
      /// \brief Gives back an integer greater or equal to the maximum
400 400
      /// Edge id.
401 401
      ///
402 402
      /// Gives back an integer greater or equal to the maximum Edge
403 403
      /// id.
404 404
      int maxEdgeId() const { return -1;}
405 405

	
406 406
      template <typename _Graph>
407 407
      struct Constraints {
408 408

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

	
19 19
///\ingroup concept
20 20
///\file
21 21
///\brief The concept of heaps.
22 22

	
23 23
#ifndef LEMON_CONCEPT_HEAP_H
24 24
#define LEMON_CONCEPT_HEAP_H
25 25

	
26
#include <lemon/bits/invalid.h>
26
#include <lemon/core.h>
27 27

	
28 28
namespace lemon {
29 29

	
30 30
  namespace concepts {
31 31

	
32 32
    /// \addtogroup concept
33 33
    /// @{
34 34

	
35 35
    /// \brief The heap concept.
36 36
    ///
37 37
    /// Concept class describing the main interface of heaps.
38 38
    template <typename Priority, typename ItemIntMap>
39 39
    class Heap {
40 40
    public:
41 41

	
42 42
      /// Type of the items stored in the heap.
43 43
      typedef typename ItemIntMap::Key Item;
44 44

	
45 45
      /// Type of the priorities.
46 46
      typedef Priority Prio;
47 47

	
48 48
      /// \brief Type to represent the states of the items.
49 49
      ///
50 50
      /// Each item has a state associated to it. It can be "in heap",
51 51
      /// "pre heap" or "post heap". The later two are indifferent
52 52
      /// from the point of view of the heap, but may be useful for
53 53
      /// the user.
54 54
      ///
55 55
      /// The \c ItemIntMap must be initialized in such a way, that it
56 56
      /// assigns \c PRE_HEAP (<tt>-1</tt>) to every item.
57 57
      enum State {
58 58
        IN_HEAP = 0,
59 59
        PRE_HEAP = -1,
60 60
        POST_HEAP = -2
61 61
      };
62 62

	
63 63
      /// \brief The constructor.
64 64
      ///
65 65
      /// The constructor.
66 66
      /// \param map A map that assigns \c int values to keys of type
67 67
      /// \c Item. It is used internally by the heap implementations to
68 68
      /// handle the cross references. The assigned value must be
69 69
      /// \c PRE_HEAP (<tt>-1</tt>) for every item.
70 70
      explicit Heap(ItemIntMap &map) {}
71 71

	
72 72
      /// \brief The number of items stored in the heap.
73 73
      ///
74 74
      /// Returns the number of items stored in the heap.
75 75
      int size() const { return 0; }
76 76

	
77 77
      /// \brief Checks if the heap is empty.
78 78
      ///
79 79
      /// Returns \c true if the heap is empty.
80 80
      bool empty() const { return false; }
81 81

	
82 82
      /// \brief Makes the heap empty.
83 83
      ///
84 84
      /// Makes the heap empty.
85 85
      void clear();
86 86

	
87 87
      /// \brief Inserts an item into the heap with the given priority.
88 88
      ///
89 89
      /// Inserts the given item into the heap with the given priority.
90 90
      /// \param i The item to insert.
91 91
      /// \param p The priority of the item.
92 92
      void push(const Item &i, const Prio &p) {}
93 93

	
94 94
      /// \brief Returns the item having minimum priority.
95 95
      ///
96 96
      /// Returns the item having minimum priority.
97 97
      /// \pre The heap must be non-empty.
98 98
      Item top() const {}
99 99

	
100 100
      /// \brief The minimum priority.
101 101
      ///
102 102
      /// Returns the minimum priority.
103 103
      /// \pre The heap must be non-empty.
104 104
      Prio prio() const {}
105 105

	
106 106
      /// \brief Removes the item having minimum priority.
107 107
      ///
108 108
      /// Removes the item having minimum priority.
109 109
      /// \pre The heap must be non-empty.
110 110
      void pop() {}
111 111

	
112 112
      /// \brief Removes an item from the heap.
113 113
      ///
114 114
      /// Removes the given item from the heap if it is already stored.
115 115
      /// \param i The item to delete.
116 116
      void erase(const Item &i) {}
117 117

	
118 118
      /// \brief The priority of an item.
119 119
      ///
120 120
      /// Returns the priority of the given item.
121 121
      /// \pre \c i must be in the heap.
122 122
      /// \param i The item.
123 123
      Prio operator[](const Item &i) const {}
124 124

	
125 125
      /// \brief Sets the priority of an item or inserts it, if it is
126 126
      /// not stored in the heap.
127 127
      ///
128 128
      /// This method sets the priority of the given item if it is
129 129
      /// already stored in the heap.
130 130
      /// Otherwise it inserts the given item with the given priority.
131 131
      ///
132 132
      /// It may throw an \ref UnderflowPriorityException.
133 133
      /// \param i The item.
134 134
      /// \param p The priority.
135 135
      void set(const Item &i, const Prio &p) {}
136 136

	
137 137
      /// \brief Decreases the priority of an item to the given value.
138 138
      ///
139 139
      /// Decreases the priority of an item to the given value.
140 140
      /// \pre \c i must be stored in the heap with priority at least \c p.
141 141
      /// \param i The item.
142 142
      /// \param p The priority.
143 143
      void decrease(const Item &i, const Prio &p) {}
144 144

	
145 145
      /// \brief Increases the priority of an item to the given value.
146 146
      ///
147 147
      /// Increases the priority of an item to the given value.
148 148
      /// \pre \c i must be stored in the heap with priority at most \c p.
149 149
      /// \param i The item.
150 150
      /// \param p The priority.
151 151
      void increase(const Item &i, const Prio &p) {}
152 152

	
153 153
      /// \brief Returns if an item is in, has already been in, or has
154 154
      /// never been in the heap.
155 155
      ///
156 156
      /// This method returns \c PRE_HEAP if the given item has never
157 157
      /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
158 158
      /// and \c POST_HEAP otherwise.
159 159
      /// In the latter case it is possible that the item will get back
160 160
      /// to the heap again.
161 161
      /// \param i The item.
162 162
      State state(const Item &i) const {}
163 163

	
164 164
      /// \brief Sets the state of an item in the heap.
165 165
      ///
166 166
      /// Sets the state of the given item in the heap. It can be used
167 167
      /// to manually clear the heap when it is important to achive the
168 168
      /// better time complexity.
169 169
      /// \param i The item.
170 170
      /// \param st The state. It should not be \c IN_HEAP.
171 171
      void state(const Item& i, State st) {}
172 172

	
173 173

	
174 174
      template <typename _Heap>
175 175
      struct Constraints {
176 176
      public:
177 177
        void constraints() {
178 178
          typedef typename _Heap::Item OwnItem;
179 179
          typedef typename _Heap::Prio OwnPrio;
180 180
          typedef typename _Heap::State OwnState;
181 181

	
182 182
          Item item;
183 183
          Prio prio;
184 184
          item=Item();
185 185
          prio=Prio();
186 186
          ignore_unused_variable_warning(item);
187 187
          ignore_unused_variable_warning(prio);
188 188

	
189 189
          OwnItem own_item;
190 190
          OwnPrio own_prio;
191 191
          OwnState own_state;
192 192
          own_item=Item();
193 193
          own_prio=Prio();
194 194
          ignore_unused_variable_warning(own_item);
195 195
          ignore_unused_variable_warning(own_prio);
196 196
          ignore_unused_variable_warning(own_state);
197 197

	
198 198
          _Heap heap1(map);
199 199
          _Heap heap2 = heap1;
200 200
          ignore_unused_variable_warning(heap1);
201 201
          ignore_unused_variable_warning(heap2);
202 202

	
203 203
          int s = heap.size();
204 204
          ignore_unused_variable_warning(s);
205 205
          bool e = heap.empty();
206 206
          ignore_unused_variable_warning(e);
207 207

	
208 208
          prio = heap.prio();
209 209
          item = heap.top();
210 210
          prio = heap[item];
211 211
          own_prio = heap.prio();
212 212
          own_item = heap.top();
213 213
          own_prio = heap[own_item];
214 214

	
215 215
          heap.push(item, prio);
216 216
          heap.push(own_item, own_prio);
217 217
          heap.pop();
218 218

	
219 219
          heap.set(item, prio);
220 220
          heap.decrease(item, prio);
221 221
          heap.increase(item, prio);
222 222
          heap.set(own_item, own_prio);
223 223
          heap.decrease(own_item, own_prio);
224 224
          heap.increase(own_item, own_prio);
225 225

	
226 226
          heap.erase(item);
227 227
          heap.erase(own_item);
228 228
          heap.clear();
229 229

	
230 230
          own_state = heap.state(own_item);
231 231
          heap.state(own_item, own_state);
232 232

	
233 233
          own_state = _Heap::PRE_HEAP;
234 234
          own_state = _Heap::IN_HEAP;
235 235
          own_state = _Heap::POST_HEAP;
236 236
        }
237 237

	
238 238
        _Heap& heap;
239 239
        ItemIntMap& map;
240 240
      };
241 241
    };
242 242

	
243 243
    /// @}
244 244
  } // namespace lemon
245 245
}
246 246
#endif // LEMON_CONCEPT_PATH_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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_CONCEPT_MAPS_H
20 20
#define LEMON_CONCEPT_MAPS_H
21 21

	
22
#include <lemon/bits/utility.h>
22
#include <lemon/core.h>
23 23
#include <lemon/concept_check.h>
24 24

	
25 25
///\ingroup concept
26 26
///\file
27 27
///\brief The concept of maps.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  namespace concepts {
32 32

	
33 33
    /// \addtogroup concept
34 34
    /// @{
35 35

	
36 36
    /// Readable map concept
37 37

	
38 38
    /// Readable map concept.
39 39
    ///
40 40
    template<typename K, typename T>
41 41
    class ReadMap
42 42
    {
43 43
    public:
44 44
      /// The key type of the map.
45 45
      typedef K Key;
46 46
      /// \brief The value type of the map.
47 47
      /// (The type of objects associated with the keys).
48 48
      typedef T Value;
49 49

	
50 50
      /// Returns the value associated with the given key.
51 51
      Value operator[](const Key &) const {
52 52
        return *static_cast<Value *>(0);
53 53
      }
54 54

	
55 55
      template<typename _ReadMap>
56 56
      struct Constraints {
57 57
        void constraints() {
58 58
          Value val = m[key];
59 59
          val = m[key];
60 60
          typename _ReadMap::Value own_val = m[own_key];
61 61
          own_val = m[own_key];
62 62

	
63 63
          ignore_unused_variable_warning(key);
64 64
          ignore_unused_variable_warning(val);
65 65
          ignore_unused_variable_warning(own_key);
66 66
          ignore_unused_variable_warning(own_val);
67 67
        }
68 68
        const Key& key;
69 69
        const typename _ReadMap::Key& own_key;
70 70
        const _ReadMap& m;
71 71
      };
72 72

	
73 73
    };
74 74

	
75 75

	
76 76
    /// Writable map concept
77 77

	
78 78
    /// Writable map concept.
79 79
    ///
80 80
    template<typename K, typename T>
81 81
    class WriteMap
82 82
    {
83 83
    public:
84 84
      /// The key type of the map.
85 85
      typedef K Key;
86 86
      /// \brief The value type of the map.
87 87
      /// (The type of objects associated with the keys).
88 88
      typedef T Value;
89 89

	
90 90
      /// Sets the value associated with the given key.
91 91
      void set(const Key &, const Value &) {}
92 92

	
93 93
      /// Default constructor.
94 94
      WriteMap() {}
95 95

	
96 96
      template <typename _WriteMap>
97 97
      struct Constraints {
98 98
        void constraints() {
99 99
          m.set(key, val);
100 100
          m.set(own_key, own_val);
101 101

	
102 102
          ignore_unused_variable_warning(key);
103 103
          ignore_unused_variable_warning(val);
104 104
          ignore_unused_variable_warning(own_key);
105 105
          ignore_unused_variable_warning(own_val);
106 106
        }
107 107
        const Key& key;
108 108
        const Value& val;
109 109
        const typename _WriteMap::Key& own_key;
110 110
        const typename _WriteMap::Value& own_val;
111 111
        _WriteMap& m;
112 112
      };
113 113
    };
114 114

	
115 115
    /// Read/writable map concept
116 116

	
117 117
    /// Read/writable map concept.
118 118
    ///
119 119
    template<typename K, typename T>
120 120
    class ReadWriteMap : public ReadMap<K,T>,
121 121
                         public WriteMap<K,T>
122 122
    {
123 123
    public:
124 124
      /// The key type of the map.
125 125
      typedef K Key;
126 126
      /// \brief The value type of the map.
127 127
      /// (The type of objects associated with the keys).
128 128
      typedef T Value;
129 129

	
130 130
      /// Returns the value associated with the given key.
131 131
      Value operator[](const Key &) const {
132 132
        return *static_cast<Value *>(0);
133 133
      }
134 134

	
135 135
      /// Sets the value associated with the given key.
136 136
      void set(const Key &, const Value &) {}
137 137

	
138 138
      template<typename _ReadWriteMap>
139 139
      struct Constraints {
140 140
        void constraints() {
141 141
          checkConcept<ReadMap<K, T>, _ReadWriteMap >();
142 142
          checkConcept<WriteMap<K, T>, _ReadWriteMap >();
143 143
        }
144 144
      };
145 145
    };
146 146

	
147 147

	
148 148
    /// Dereferable map concept
149 149

	
150 150
    /// Dereferable map concept.
151 151
    ///
152 152
    template<typename K, typename T, typename R, typename CR>
153 153
    class ReferenceMap : public ReadWriteMap<K,T>
154 154
    {
155 155
    public:
156 156
      /// Tag for reference maps.
157 157
      typedef True ReferenceMapTag;
158 158
      /// The key type of the map.
159 159
      typedef K Key;
160 160
      /// \brief The value type of the map.
161 161
      /// (The type of objects associated with the keys).
162 162
      typedef T Value;
163 163
      /// The reference type of the map.
164 164
      typedef R Reference;
165 165
      /// The const reference type of the map.
166 166
      typedef CR ConstReference;
167 167

	
168 168
    public:
169 169

	
170 170
      /// Returns a reference to the value associated with the given key.
171 171
      Reference operator[](const Key &) {
172 172
        return *static_cast<Value *>(0);
173 173
      }
174 174

	
175 175
      /// Returns a const reference to the value associated with the given key.
176 176
      ConstReference operator[](const Key &) const {
177 177
        return *static_cast<Value *>(0);
178 178
      }
179 179

	
180 180
      /// Sets the value associated with the given key.
181 181
      void set(const Key &k,const Value &t) { operator[](k)=t; }
182 182

	
183 183
      template<typename _ReferenceMap>
184 184
      struct Constraints {
185 185
        void constraints() {
186 186
          checkConcept<ReadWriteMap<K, T>, _ReferenceMap >();
187 187
          ref = m[key];
188 188
          m[key] = val;
189 189
          m[key] = ref;
190 190
          m[key] = cref;
191 191
          own_ref = m[own_key];
192 192
          m[own_key] = own_val;
193 193
          m[own_key] = own_ref;
194 194
          m[own_key] = own_cref;
195 195
          m[key] = m[own_key];
196 196
          m[own_key] = m[key];
197 197
        }
198 198
        const Key& key;
199 199
        Value& val;
200 200
        Reference ref;
201 201
        ConstReference cref;
202 202
        const typename _ReferenceMap::Key& own_key;
203 203
        typename _ReferenceMap::Value& own_val;
204 204
        typename _ReferenceMap::Reference own_ref;
205 205
        typename _ReferenceMap::ConstReference own_cref;
206 206
        _ReferenceMap& m;
207 207
      };
208 208
    };
209 209

	
210 210
    // @}
211 211

	
212 212
  } //namespace concepts
213 213

	
214 214
} //namespace lemon
215 215

	
216 216
#endif // LEMON_CONCEPT_MAPS_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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
///\ingroup concept
20 20
///\file
21 21
///\brief Classes for representing paths in digraphs.
22 22
///
23 23
///\todo Iterators have obsolete style
24 24

	
25 25
#ifndef LEMON_CONCEPT_PATH_H
26 26
#define LEMON_CONCEPT_PATH_H
27 27

	
28
#include <lemon/bits/invalid.h>
29
#include <lemon/bits/utility.h>
28
#include <lemon/core.h>
30 29
#include <lemon/concept_check.h>
31 30

	
32 31
namespace lemon {
33 32
  namespace concepts {
34 33

	
35 34
    /// \addtogroup concept
36 35
    /// @{
37 36

	
38 37
    /// \brief A skeleton structure for representing directed paths in
39 38
    /// a digraph.
40 39
    ///
41 40
    /// A skeleton structure for representing directed paths in a
42 41
    /// digraph.
43 42
    /// \tparam _Digraph The digraph type in which the path is.
44 43
    ///
45 44
    /// In a sense, the path can be treated as a list of arcs. The
46 45
    /// lemon path type stores just this list. As a consequence it
47 46
    /// cannot enumerate the nodes in the path and the zero length
48 47
    /// paths cannot store the source.
49 48
    ///
50 49
    template <typename _Digraph>
51 50
    class Path {
52 51
    public:
53 52

	
54 53
      /// Type of the underlying digraph.
55 54
      typedef _Digraph Digraph;
56 55
      /// Arc type of the underlying digraph.
57 56
      typedef typename Digraph::Arc Arc;
58 57

	
59 58
      class ArcIt;
60 59

	
61 60
      /// \brief Default constructor
62 61
      Path() {}
63 62

	
64 63
      /// \brief Template constructor
65 64
      template <typename CPath>
66 65
      Path(const CPath& cpath) {}
67 66

	
68 67
      /// \brief Template assigment
69 68
      template <typename CPath>
70 69
      Path& operator=(const CPath& cpath) {}
71 70

	
72 71
      /// Length of the path ie. the number of arcs in the path.
73 72
      int length() const { return 0;}
74 73

	
75 74
      /// Returns whether the path is empty.
76 75
      bool empty() const { return true;}
77 76

	
78 77
      /// Resets the path to an empty path.
79 78
      void clear() {}
80 79

	
81 80
      /// \brief Lemon style iterator for path arcs
82 81
      ///
83 82
      /// This class is used to iterate on the arcs of the paths.
84 83
      class ArcIt {
85 84
      public:
86 85
        /// Default constructor
87 86
        ArcIt() {}
88 87
        /// Invalid constructor
89 88
        ArcIt(Invalid) {}
90 89
        /// Constructor for first arc
91 90
        ArcIt(const Path &) {}
92 91

	
93 92
        /// Conversion to Arc
94 93
        operator Arc() const { return INVALID; }
95 94

	
96 95
        /// Next arc
97 96
        ArcIt& operator++() {return *this;}
98 97

	
99 98
        /// Comparison operator
100 99
        bool operator==(const ArcIt&) const {return true;}
101 100
        /// Comparison operator
102 101
        bool operator!=(const ArcIt&) const {return true;}
103 102
        /// Comparison operator
104 103
        bool operator<(const ArcIt&) const {return false;}
105 104

	
106 105
      };
107 106

	
108 107
      template <typename _Path>
109 108
      struct Constraints {
110 109
        void constraints() {
111 110
          Path<Digraph> pc;
112 111
          _Path p, pp(pc);
113 112
          int l = p.length();
114 113
          int e = p.empty();
115 114
          p.clear();
116 115

	
117 116
          p = pc;
118 117

	
119 118
          typename _Path::ArcIt id, ii(INVALID), i(p);
120 119

	
121 120
          ++i;
122 121
          typename Digraph::Arc ed = i;
123 122

	
124 123
          e = (i == ii);
125 124
          e = (i != ii);
126 125
          e = (i < ii);
127 126

	
128 127
          ignore_unused_variable_warning(l);
129 128
          ignore_unused_variable_warning(pp);
130 129
          ignore_unused_variable_warning(e);
131 130
          ignore_unused_variable_warning(id);
132 131
          ignore_unused_variable_warning(ii);
133 132
          ignore_unused_variable_warning(ed);
134 133
        }
135 134
      };
136 135

	
137 136
    };
138 137

	
139 138
    namespace _path_bits {
140 139

	
141 140
      template <typename _Digraph, typename _Path, typename RevPathTag = void>
142 141
      struct PathDumperConstraints {
143 142
        void constraints() {
144 143
          int l = p.length();
145 144
          int e = p.empty();
146 145

	
147 146
          typename _Path::ArcIt id, i(p);
148 147

	
149 148
          ++i;
150 149
          typename _Digraph::Arc ed = i;
151 150

	
152 151
          e = (i == INVALID);
153 152
          e = (i != INVALID);
154 153

	
155 154
          ignore_unused_variable_warning(l);
156 155
          ignore_unused_variable_warning(e);
157 156
          ignore_unused_variable_warning(id);
158 157
          ignore_unused_variable_warning(ed);
159 158
        }
160 159
        _Path& p;
161 160
      };
162 161

	
163 162
      template <typename _Digraph, typename _Path>
164 163
      struct PathDumperConstraints<
165 164
        _Digraph, _Path,
166 165
        typename enable_if<typename _Path::RevPathTag, void>::type
167 166
      > {
168 167
        void constraints() {
169 168
          int l = p.length();
170 169
          int e = p.empty();
171 170

	
172 171
          typename _Path::RevArcIt id, i(p);
173 172

	
174 173
          ++i;
175 174
          typename _Digraph::Arc ed = i;
176 175

	
177 176
          e = (i == INVALID);
178 177
          e = (i != INVALID);
179 178

	
180 179
          ignore_unused_variable_warning(l);
181 180
          ignore_unused_variable_warning(e);
182 181
          ignore_unused_variable_warning(id);
183 182
          ignore_unused_variable_warning(ed);
184 183
        }
185 184
        _Path& p;
186 185
      };
187 186

	
188 187
    }
189 188

	
190 189

	
191 190
    /// \brief A skeleton structure for path dumpers.
192 191
    ///
193 192
    /// A skeleton structure for path dumpers. The path dumpers are
194 193
    /// the generalization of the paths. The path dumpers can
195 194
    /// enumerate the arcs of the path wheter in forward or in
196 195
    /// backward order.  In most time these classes are not used
197 196
    /// directly rather it used to assign a dumped class to a real
198 197
    /// path type.
199 198
    ///
200 199
    /// The main purpose of this concept is that the shortest path
201 200
    /// algorithms can enumerate easily the arcs in reverse order.
202 201
    /// If we would like to give back a real path from these
203 202
    /// algorithms then we should create a temporarly path object. In
204 203
    /// Lemon such algorithms gives back a path dumper what can
205 204
    /// assigned to a real path and the dumpers can be implemented as
206 205
    /// an adaptor class to the predecessor map.
207 206

	
208 207
    /// \tparam _Digraph  The digraph type in which the path is.
209 208
    ///
210 209
    /// The paths can be constructed from any path type by a
211 210
    /// template constructor or a template assignment operator.
212 211
    ///
213 212
    template <typename _Digraph>
214 213
    class PathDumper {
215 214
    public:
216 215

	
217 216
      /// Type of the underlying digraph.
218 217
      typedef _Digraph Digraph;
219 218
      /// Arc type of the underlying digraph.
220 219
      typedef typename Digraph::Arc Arc;
221 220

	
222 221
      /// Length of the path ie. the number of arcs in the path.
223 222
      int length() const { return 0;}
224 223

	
225 224
      /// Returns whether the path is empty.
226 225
      bool empty() const { return true;}
227 226

	
228 227
      /// \brief Forward or reverse dumping
229 228
      ///
230 229
      /// If the RevPathTag is defined and true then reverse dumping
231 230
      /// is provided in the path dumper. In this case instead of the
232 231
      /// ArcIt the RevArcIt iterator should be implemented in the
233 232
      /// dumper.
234 233
      typedef False RevPathTag;
235 234

	
236 235
      /// \brief Lemon style iterator for path arcs
237 236
      ///
238 237
      /// This class is used to iterate on the arcs of the paths.
239 238
      class ArcIt {
240 239
      public:
241 240
        /// Default constructor
242 241
        ArcIt() {}
243 242
        /// Invalid constructor
244 243
        ArcIt(Invalid) {}
245 244
        /// Constructor for first arc
246 245
        ArcIt(const PathDumper&) {}
247 246

	
248 247
        /// Conversion to Arc
249 248
        operator Arc() const { return INVALID; }
250 249

	
251 250
        /// Next arc
252 251
        ArcIt& operator++() {return *this;}
253 252

	
254 253
        /// Comparison operator
255 254
        bool operator==(const ArcIt&) const {return true;}
256 255
        /// Comparison operator
257 256
        bool operator!=(const ArcIt&) const {return true;}
258 257
        /// Comparison operator
259 258
        bool operator<(const ArcIt&) const {return false;}
260 259

	
261 260
      };
262 261

	
263 262
      /// \brief Lemon style iterator for path arcs
264 263
      ///
265 264
      /// This class is used to iterate on the arcs of the paths in
266 265
      /// reverse direction.
267 266
      class RevArcIt {
268 267
      public:
269 268
        /// Default constructor
270 269
        RevArcIt() {}
271 270
        /// Invalid constructor
272 271
        RevArcIt(Invalid) {}
273 272
        /// Constructor for first arc
274 273
        RevArcIt(const PathDumper &) {}
275 274

	
276 275
        /// Conversion to Arc
277 276
        operator Arc() const { return INVALID; }
278 277

	
279 278
        /// Next arc
280 279
        RevArcIt& operator++() {return *this;}
281 280

	
282 281
        /// Comparison operator
283 282
        bool operator==(const RevArcIt&) const {return true;}
284 283
        /// Comparison operator
285 284
        bool operator!=(const RevArcIt&) const {return true;}
286 285
        /// Comparison operator
287 286
        bool operator<(const RevArcIt&) const {return false;}
288 287

	
289 288
      };
290 289

	
291 290
      template <typename _Path>
292 291
      struct Constraints {
293 292
        void constraints() {
294 293
          function_requires<_path_bits::
295 294
            PathDumperConstraints<Digraph, _Path> >();
296 295
        }
297 296
      };
298 297

	
299 298
    };
300 299

	
301 300

	
302 301
    ///@}
303 302
  }
304 303

	
305 304
} // namespace lemon
306 305

	
307 306
#endif // LEMON_CONCEPT_PATH_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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_DFS_H
20 20
#define LEMON_DFS_H
21 21

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

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

	
33 32
#include <lemon/concept_check.h>
34 33

	
35 34
namespace lemon {
36 35

	
37 36

	
38 37
  ///Default traits class of Dfs class.
39 38

	
40 39
  ///Default traits class of Dfs class.
41 40
  ///\tparam GR Digraph type.
42 41
  template<class GR>
43 42
  struct DfsDefaultTraits
44 43
  {
45 44
    ///The digraph type the algorithm runs on.
46 45
    typedef GR Digraph;
47 46
    ///\brief The type of the map that stores the last
48 47
    ///arcs of the %DFS paths.
49 48
    ///
50 49
    ///The type of the map that stores the last
51 50
    ///arcs of the %DFS paths.
52 51
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
53 52
    ///
54 53
    typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
55 54
    ///Instantiates a PredMap.
56 55

	
57 56
    ///This function instantiates a \ref PredMap.
58 57
    ///\param G is the digraph, to which we would like to define the PredMap.
59 58
    ///\todo The digraph alone may be insufficient to initialize
60 59
    static PredMap *createPredMap(const GR &G)
61 60
    {
62 61
      return new PredMap(G);
63 62
    }
64 63

	
65 64
    ///The type of the map that indicates which nodes are processed.
66 65

	
67 66
    ///The type of the map that indicates which nodes are processed.
68 67
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
69 68
    ///\todo named parameter to set this type, function to read and write.
70 69
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
71 70
    ///Instantiates a ProcessedMap.
72 71

	
73 72
    ///This function instantiates a \ref ProcessedMap.
74 73
    ///\param g is the digraph, to which
75 74
    ///we would like to define the \ref ProcessedMap
76 75
#ifdef DOXYGEN
77 76
    static ProcessedMap *createProcessedMap(const GR &g)
78 77
#else
79 78
    static ProcessedMap *createProcessedMap(const GR &)
80 79
#endif
81 80
    {
82 81
      return new ProcessedMap();
83 82
    }
84 83
    ///The type of the map that indicates which nodes are reached.
85 84

	
86 85
    ///The type of the map that indicates which nodes are reached.
87 86
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
88 87
    ///\todo named parameter to set this type, function to read and write.
89 88
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
90 89
    ///Instantiates a ReachedMap.
91 90

	
92 91
    ///This function instantiates a \ref ReachedMap.
93 92
    ///\param G is the digraph, to which
94 93
    ///we would like to define the \ref ReachedMap.
95 94
    static ReachedMap *createReachedMap(const GR &G)
96 95
    {
97 96
      return new ReachedMap(G);
98 97
    }
99 98
    ///The type of the map that stores the dists of the nodes.
100 99

	
101 100
    ///The type of the map that stores the dists of the nodes.
102 101
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
103 102
    ///
104 103
    typedef typename Digraph::template NodeMap<int> DistMap;
105 104
    ///Instantiates a DistMap.
106 105

	
107 106
    ///This function instantiates a \ref DistMap.
108 107
    ///\param G is the digraph, to which we would like to define
109 108
    ///the \ref DistMap
110 109
    static DistMap *createDistMap(const GR &G)
111 110
    {
112 111
      return new DistMap(G);
113 112
    }
114 113
  };
115 114

	
116 115
  ///%DFS algorithm class.
117 116

	
118 117
  ///\ingroup search
119 118
  ///This class provides an efficient implementation of the %DFS algorithm.
120 119
  ///
121 120
  ///\tparam GR The digraph type the algorithm runs on. The default value is
122 121
  ///\ref ListDigraph. The value of GR is not used directly by Dfs, it
123 122
  ///is only passed to \ref DfsDefaultTraits.
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 DfsDefaultTraits "DfsDefaultTraits<GR>".
127 126
  ///See \ref DfsDefaultTraits for the documentation of
128 127
  ///a Dfs 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=DfsDefaultTraits<GR> >
135 134
#endif
136 135
  class Dfs {
137 136
  public:
138 137
    /**
139 138
     * \brief \ref Exception for uninitialized parameters.
140 139
     *
141 140
     * This error represents problems in the initialization
142 141
     * of the parameters of the algorithms.
143 142
     */
144 143
    class UninitializedParameter : public lemon::UninitializedParameter {
145 144
    public:
146 145
      virtual const char* what() const throw() {
147 146
        return "lemon::Dfs::UninitializedParameter";
148 147
      }
149 148
    };
150 149

	
151 150
    typedef TR Traits;
152 151
    ///The type of the underlying digraph.
153 152
    typedef typename TR::Digraph Digraph;
154 153
    ///\e
155 154
    typedef typename Digraph::Node Node;
156 155
    ///\e
157 156
    typedef typename Digraph::NodeIt NodeIt;
158 157
    ///\e
159 158
    typedef typename Digraph::Arc Arc;
160 159
    ///\e
161 160
    typedef typename Digraph::OutArcIt OutArcIt;
162 161

	
163 162
    ///\brief The type of the map that stores the last
164 163
    ///arcs of the %DFS paths.
165 164
    typedef typename TR::PredMap PredMap;
166 165
    ///The type of the map indicating which nodes are reached.
167 166
    typedef typename TR::ReachedMap ReachedMap;
168 167
    ///The type of the map indicating which nodes are processed.
169 168
    typedef typename TR::ProcessedMap ProcessedMap;
170 169
    ///The type of the map that stores the dists of the nodes.
171 170
    typedef typename TR::DistMap DistMap;
172 171
  private:
173 172
    /// Pointer to the underlying digraph.
174 173
    const Digraph *G;
175 174
    ///Pointer to the map of predecessors arcs.
176 175
    PredMap *_pred;
177 176
    ///Indicates if \ref _pred is locally allocated (\c true) or not.
178 177
    bool local_pred;
179 178
    ///Pointer to the map of distances.
180 179
    DistMap *_dist;
181 180
    ///Indicates if \ref _dist is locally allocated (\c true) or not.
182 181
    bool local_dist;
183 182
    ///Pointer to the map of reached status of the nodes.
184 183
    ReachedMap *_reached;
185 184
    ///Indicates if \ref _reached is locally allocated (\c true) or not.
186 185
    bool local_reached;
187 186
    ///Pointer to the map of processed status of the nodes.
188 187
    ProcessedMap *_processed;
189 188
    ///Indicates if \ref _processed is locally allocated (\c true) or not.
190 189
    bool local_processed;
191 190

	
192 191
    std::vector<typename Digraph::OutArcIt> _stack;
193 192
    int _stack_head;
194 193

	
195 194
    ///Creates the maps if necessary.
196 195

	
197 196
    ///\todo Better memory allocation (instead of new).
198 197
    void create_maps()
199 198
    {
200 199
      if(!_pred) {
201 200
        local_pred = true;
202 201
        _pred = Traits::createPredMap(*G);
203 202
      }
204 203
      if(!_dist) {
205 204
        local_dist = true;
206 205
        _dist = Traits::createDistMap(*G);
207 206
      }
208 207
      if(!_reached) {
209 208
        local_reached = true;
210 209
        _reached = Traits::createReachedMap(*G);
211 210
      }
212 211
      if(!_processed) {
213 212
        local_processed = true;
214 213
        _processed = Traits::createProcessedMap(*G);
215 214
      }
216 215
    }
217 216

	
218 217
  protected:
219 218

	
220 219
    Dfs() {}
221 220

	
222 221
  public:
223 222

	
224 223
    typedef Dfs Create;
225 224

	
226 225
    ///\name Named template parameters
227 226

	
228 227
    ///@{
229 228

	
230 229
    template <class T>
231 230
    struct DefPredMapTraits : public Traits {
232 231
      typedef T PredMap;
233 232
      static PredMap *createPredMap(const Digraph &G)
234 233
      {
235 234
        throw UninitializedParameter();
236 235
      }
237 236
    };
238 237
    ///\brief \ref named-templ-param "Named parameter" for setting
239 238
    ///PredMap type
240 239
    ///
241 240
    ///\ref named-templ-param "Named parameter" for setting PredMap type
242 241
    ///
243 242
    template <class T>
244 243
    struct DefPredMap : public Dfs<Digraph, DefPredMapTraits<T> > {
245 244
      typedef Dfs<Digraph, DefPredMapTraits<T> > Create;
246 245
    };
247 246

	
248 247

	
249 248
    template <class T>
250 249
    struct DefDistMapTraits : public Traits {
251 250
      typedef T DistMap;
252 251
      static DistMap *createDistMap(const Digraph &)
253 252
      {
254 253
        throw UninitializedParameter();
255 254
      }
256 255
    };
257 256
    ///\brief \ref named-templ-param "Named parameter" for setting
258 257
    ///DistMap type
259 258
    ///
260 259
    ///\ref named-templ-param "Named parameter" for setting DistMap
261 260
    ///type
262 261
    template <class T>
263 262
    struct DefDistMap {
264 263
      typedef Dfs<Digraph, DefDistMapTraits<T> > Create;
265 264
    };
266 265

	
267 266
    template <class T>
268 267
    struct DefReachedMapTraits : public Traits {
269 268
      typedef T ReachedMap;
270 269
      static ReachedMap *createReachedMap(const Digraph &)
271 270
      {
272 271
        throw UninitializedParameter();
273 272
      }
274 273
    };
275 274
    ///\brief \ref named-templ-param "Named parameter" for setting
276 275
    ///ReachedMap type
277 276
    ///
278 277
    ///\ref named-templ-param "Named parameter" for setting ReachedMap type
279 278
    ///
280 279
    template <class T>
281 280
    struct DefReachedMap : public Dfs< Digraph, DefReachedMapTraits<T> > {
282 281
      typedef Dfs< Digraph, DefReachedMapTraits<T> > Create;
283 282
    };
284 283

	
285 284
    template <class T>
286 285
    struct DefProcessedMapTraits : public Traits {
287 286
      typedef T ProcessedMap;
288 287
      static ProcessedMap *createProcessedMap(const Digraph &)
289 288
      {
290 289
        throw UninitializedParameter();
291 290
      }
292 291
    };
293 292
    ///\brief \ref named-templ-param "Named parameter" for setting
294 293
    ///ProcessedMap type
295 294
    ///
296 295
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
297 296
    ///
298 297
    template <class T>
299 298
    struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > {
300 299
      typedef Dfs< Digraph, DefProcessedMapTraits<T> > Create;
301 300
    };
302 301

	
303 302
    struct DefDigraphProcessedMapTraits : public Traits {
304 303
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
305 304
      static ProcessedMap *createProcessedMap(const Digraph &G)
306 305
      {
307 306
        return new ProcessedMap(G);
308 307
      }
309 308
    };
310 309
    ///\brief \ref named-templ-param "Named parameter"
311 310
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
312 311
    ///
313 312
    ///\ref named-templ-param "Named parameter"
314 313
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
315 314
    ///If you don't set it explicitely, it will be automatically allocated.
316 315
    template <class T>
317 316
    class DefProcessedMapToBeDefaultMap :
318 317
      public Dfs< Digraph, DefDigraphProcessedMapTraits> {
319 318
      typedef Dfs< Digraph, DefDigraphProcessedMapTraits> Create;
320 319
    };
321 320

	
322 321
    ///@}
323 322

	
324 323
  public:
325 324

	
326 325
    ///Constructor.
327 326

	
328 327
    ///\param _G the digraph the algorithm will run on.
329 328
    ///
330 329
    Dfs(const Digraph& _G) :
331 330
      G(&_G),
332 331
      _pred(NULL), local_pred(false),
333 332
      _dist(NULL), local_dist(false),
334 333
      _reached(NULL), local_reached(false),
335 334
      _processed(NULL), local_processed(false)
336 335
    { }
337 336

	
338 337
    ///Destructor.
339 338
    ~Dfs()
340 339
    {
341 340
      if(local_pred) delete _pred;
342 341
      if(local_dist) delete _dist;
343 342
      if(local_reached) delete _reached;
344 343
      if(local_processed) delete _processed;
345 344
    }
346 345

	
347 346
    ///Sets the map storing the predecessor arcs.
348 347

	
349 348
    ///Sets the map storing the predecessor arcs.
350 349
    ///If you don't use this function before calling \ref run(),
351 350
    ///it will allocate one. The destuctor deallocates this
352 351
    ///automatically allocated map, of course.
353 352
    ///\return <tt> (*this) </tt>
354 353
    Dfs &predMap(PredMap &m)
355 354
    {
356 355
      if(local_pred) {
357 356
        delete _pred;
358 357
        local_pred=false;
359 358
      }
360 359
      _pred = &m;
361 360
      return *this;
362 361
    }
363 362

	
364 363
    ///Sets the map storing the distances calculated by the algorithm.
365 364

	
366 365
    ///Sets the map storing the distances calculated by the algorithm.
367 366
    ///If you don't use this function before calling \ref run(),
368 367
    ///it will allocate one. The destuctor deallocates this
369 368
    ///automatically allocated map, of course.
370 369
    ///\return <tt> (*this) </tt>
371 370
    Dfs &distMap(DistMap &m)
372 371
    {
373 372
      if(local_dist) {
374 373
        delete _dist;
375 374
        local_dist=false;
376 375
      }
377 376
      _dist = &m;
378 377
      return *this;
379 378
    }
380 379

	
381 380
    ///Sets the map indicating if a node is reached.
382 381

	
383 382
    ///Sets the map indicating if a node is reached.
384 383
    ///If you don't use this function before calling \ref run(),
385 384
    ///it will allocate one. The destuctor deallocates this
386 385
    ///automatically allocated map, of course.
387 386
    ///\return <tt> (*this) </tt>
388 387
    Dfs &reachedMap(ReachedMap &m)
389 388
    {
390 389
      if(local_reached) {
391 390
        delete _reached;
392 391
        local_reached=false;
393 392
      }
394 393
      _reached = &m;
395 394
      return *this;
396 395
    }
397 396

	
398 397
    ///Sets the map indicating if a node is processed.
399 398

	
400 399
    ///Sets the map indicating if a node is processed.
401 400
    ///If you don't use this function before calling \ref run(),
402 401
    ///it will allocate one. The destuctor deallocates this
403 402
    ///automatically allocated map, of course.
404 403
    ///\return <tt> (*this) </tt>
405 404
    Dfs &processedMap(ProcessedMap &m)
406 405
    {
407 406
      if(local_processed) {
408 407
        delete _processed;
409 408
        local_processed=false;
410 409
      }
411 410
      _processed = &m;
412 411
      return *this;
413 412
    }
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DIJKSTRA_H
20 20
#define LEMON_DIJKSTRA_H
21 21

	
22 22
///\ingroup shortest_path
23 23
///\file
24 24
///\brief Dijkstra algorithm.
25 25

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

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default OperationTraits for the Dijkstra algorithm class.
37 37
  ///
38 38
  /// It defines all computational operations and constants which are
39 39
  /// used in the Dijkstra algorithm.
40 40
  template <typename Value>
41 41
  struct DijkstraDefaultOperationTraits {
42 42
    /// \brief Gives back the zero value of the type.
43 43
    static Value zero() {
44 44
      return static_cast<Value>(0);
45 45
    }
46 46
    /// \brief Gives back the sum of the given two elements.
47 47
    static Value plus(const Value& left, const Value& right) {
48 48
      return left + right;
49 49
    }
50 50
    /// \brief Gives back true only if the first value less than the second.
51 51
    static bool less(const Value& left, const Value& right) {
52 52
      return left < right;
53 53
    }
54 54
  };
55 55

	
56 56
  /// \brief Widest path OperationTraits for the Dijkstra algorithm class.
57 57
  ///
58 58
  /// It defines all computational operations and constants which are
59 59
  /// used in the Dijkstra algorithm for widest path computation.
60 60
  template <typename Value>
61 61
  struct DijkstraWidestPathOperationTraits {
62 62
    /// \brief Gives back the maximum value of the type.
63 63
    static Value zero() {
64 64
      return std::numeric_limits<Value>::max();
65 65
    }
66 66
    /// \brief Gives back the minimum of the given two elements.
67 67
    static Value plus(const Value& left, const Value& right) {
68 68
      return std::min(left, right);
69 69
    }
70 70
    /// \brief Gives back true only if the first value less than the second.
71 71
    static bool less(const Value& left, const Value& right) {
72 72
      return left < right;
73 73
    }
74 74
  };
75 75

	
76 76
  ///Default traits class of Dijkstra class.
77 77

	
78 78
  ///Default traits class of Dijkstra class.
79 79
  ///\tparam GR Digraph type.
80 80
  ///\tparam LM Type of length map.
81 81
  template<class GR, class LM>
82 82
  struct DijkstraDefaultTraits
83 83
  {
84 84
    ///The digraph type the algorithm runs on.
85 85
    typedef GR Digraph;
86 86
    ///The type of the map that stores the arc lengths.
87 87

	
88 88
    ///The type of the map that stores the arc lengths.
89 89
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
90 90
    typedef LM LengthMap;
91 91
    //The type of the length of the arcs.
92 92
    typedef typename LM::Value Value;
93 93
    /// Operation traits for Dijkstra algorithm.
94 94

	
95 95
    /// It defines the used operation by the algorithm.
96 96
    /// \see DijkstraDefaultOperationTraits
97 97
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
98 98
    /// The cross reference type used by heap.
99 99

	
100 100

	
101 101
    /// The cross reference type used by heap.
102 102
    /// Usually it is \c Digraph::NodeMap<int>.
103 103
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
104 104
    ///Instantiates a HeapCrossRef.
105 105

	
106 106
    ///This function instantiates a \c HeapCrossRef.
107 107
    /// \param G is the digraph, to which we would like to define the
108 108
    /// HeapCrossRef.
109 109
    static HeapCrossRef *createHeapCrossRef(const GR &G)
110 110
    {
111 111
      return new HeapCrossRef(G);
112 112
    }
113 113

	
114 114
    ///The heap type used by Dijkstra algorithm.
115 115

	
116 116
    ///The heap type used by Dijkstra algorithm.
117 117
    ///
118 118
    ///\sa BinHeap
119 119
    ///\sa Dijkstra
120 120
    typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
121 121

	
122 122
    static Heap *createHeap(HeapCrossRef& R)
123 123
    {
124 124
      return new Heap(R);
125 125
    }
126 126

	
127 127
    ///\brief The type of the map that stores the last
128 128
    ///arcs of the shortest paths.
129 129
    ///
130 130
    ///The type of the map that stores the last
131 131
    ///arcs of the shortest paths.
132 132
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
133 133
    ///
134 134
    typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
135 135
    ///Instantiates a PredMap.
136 136

	
137 137
    ///This function instantiates a \c PredMap.
138 138
    ///\param G is the digraph, to which we would like to define the PredMap.
139 139
    ///\todo The digraph alone may be insufficient for the initialization
140 140
    static PredMap *createPredMap(const GR &G)
141 141
    {
142 142
      return new PredMap(G);
143 143
    }
144 144

	
145 145
    ///The type of the map that stores whether a nodes is processed.
146 146

	
147 147
    ///The type of the map that stores whether a nodes is processed.
148 148
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
149 149
    ///By default it is a NullMap.
150 150
    ///\todo If it is set to a real map,
151 151
    ///Dijkstra::processed() should read this.
152 152
    ///\todo named parameter to set this type, function to read and write.
153 153
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
154 154
    ///Instantiates a ProcessedMap.
155 155

	
156 156
    ///This function instantiates a \c ProcessedMap.
157 157
    ///\param g is the digraph, to which
158 158
    ///we would like to define the \c ProcessedMap
159 159
#ifdef DOXYGEN
160 160
    static ProcessedMap *createProcessedMap(const GR &g)
161 161
#else
162 162
    static ProcessedMap *createProcessedMap(const GR &)
163 163
#endif
164 164
    {
165 165
      return new ProcessedMap();
166 166
    }
167 167
    ///The type of the map that stores the dists of the nodes.
168 168

	
169 169
    ///The type of the map that stores the dists of the nodes.
170 170
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
171 171
    ///
172 172
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
173 173
    ///Instantiates a DistMap.
174 174

	
175 175
    ///This function instantiates a \ref DistMap.
176 176
    ///\param G is the digraph, to which we would like to define
177 177
    ///the \ref DistMap
178 178
    static DistMap *createDistMap(const GR &G)
179 179
    {
180 180
      return new DistMap(G);
181 181
    }
182 182
  };
183 183

	
184 184
  ///%Dijkstra algorithm class.
185 185

	
186 186
  /// \ingroup shortest_path
187 187
  ///This class provides an efficient implementation of %Dijkstra algorithm.
188 188
  ///The arc lengths are passed to the algorithm using a
189 189
  ///\ref concepts::ReadMap "ReadMap",
190 190
  ///so it is easy to change it to any kind of length.
191 191
  ///
192 192
  ///The type of the length is determined by the
193 193
  ///\ref concepts::ReadMap::Value "Value" of the length map.
194 194
  ///
195 195
  ///It is also possible to change the underlying priority heap.
196 196
  ///
197 197
  ///\tparam GR The digraph type the algorithm runs on. The default value
198 198
  ///is \ref ListDigraph. The value of GR is not used directly by
199 199
  ///Dijkstra, it is only passed to \ref DijkstraDefaultTraits.
200 200
  ///\tparam LM This read-only ArcMap determines the lengths of the
201 201
  ///arcs. It is read once for each arc, so the map may involve in
202 202
  ///relatively time consuming process to compute the arc length if
203 203
  ///it is necessary. The default map type is \ref
204 204
  ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".  The value
205 205
  ///of LM is not used directly by Dijkstra, it is only passed to \ref
206 206
  ///DijkstraDefaultTraits.
207 207
  ///\tparam TR Traits class to set
208 208
  ///various data types used by the algorithm.  The default traits
209 209
  ///class is \ref DijkstraDefaultTraits
210 210
  ///"DijkstraDefaultTraits<GR,LM>".  See \ref
211 211
  ///DijkstraDefaultTraits for the documentation of a Dijkstra traits
212 212
  ///class.
213 213

	
214 214
#ifdef DOXYGEN
215 215
  template <typename GR, typename LM, typename TR>
216 216
#else
217 217
  template <typename GR=ListDigraph,
218 218
            typename LM=typename GR::template ArcMap<int>,
219 219
            typename TR=DijkstraDefaultTraits<GR,LM> >
220 220
#endif
221 221
  class Dijkstra {
222 222
  public:
223 223
    /**
224 224
     * \brief \ref Exception for uninitialized parameters.
225 225
     *
226 226
     * This error represents problems in the initialization
227 227
     * of the parameters of the algorithms.
228 228
     */
229 229
    class UninitializedParameter : public lemon::UninitializedParameter {
230 230
    public:
231 231
      virtual const char* what() const throw() {
232 232
        return "lemon::Dijkstra::UninitializedParameter";
233 233
      }
234 234
    };
235 235

	
236 236
    typedef TR Traits;
237 237
    ///The type of the underlying digraph.
238 238
    typedef typename TR::Digraph Digraph;
239 239
    ///\e
240 240
    typedef typename Digraph::Node Node;
241 241
    ///\e
242 242
    typedef typename Digraph::NodeIt NodeIt;
243 243
    ///\e
244 244
    typedef typename Digraph::Arc Arc;
245 245
    ///\e
246 246
    typedef typename Digraph::OutArcIt OutArcIt;
247 247

	
248 248
    ///The type of the length of the arcs.
249 249
    typedef typename TR::LengthMap::Value Value;
250 250
    ///The type of the map that stores the arc lengths.
251 251
    typedef typename TR::LengthMap LengthMap;
252 252
    ///\brief The type of the map that stores the last
253 253
    ///arcs of the shortest paths.
254 254
    typedef typename TR::PredMap PredMap;
255 255
    ///The type of the map indicating if a node is processed.
256 256
    typedef typename TR::ProcessedMap ProcessedMap;
257 257
    ///The type of the map that stores the dists of the nodes.
258 258
    typedef typename TR::DistMap DistMap;
259 259
    ///The cross reference type used for the current heap.
260 260
    typedef typename TR::HeapCrossRef HeapCrossRef;
261 261
    ///The heap type used by the dijkstra algorithm.
262 262
    typedef typename TR::Heap Heap;
263 263
    ///The operation traits.
264 264
    typedef typename TR::OperationTraits OperationTraits;
265 265
  private:
266 266
    /// Pointer to the underlying digraph.
267 267
    const Digraph *G;
268 268
    /// Pointer to the length map
269 269
    const LengthMap *length;
270 270
    ///Pointer to the map of predecessors arcs.
271 271
    PredMap *_pred;
272 272
    ///Indicates if \ref _pred is locally allocated (\c true) or not.
273 273
    bool local_pred;
274 274
    ///Pointer to the map of distances.
275 275
    DistMap *_dist;
276 276
    ///Indicates if \ref _dist is locally allocated (\c true) or not.
277 277
    bool local_dist;
278 278
    ///Pointer to the map of processed status of the nodes.
279 279
    ProcessedMap *_processed;
280 280
    ///Indicates if \ref _processed is locally allocated (\c true) or not.
281 281
    bool local_processed;
282 282
    ///Pointer to the heap cross references.
283 283
    HeapCrossRef *_heap_cross_ref;
284 284
    ///Indicates if \ref _heap_cross_ref is locally allocated (\c true) or not.
285 285
    bool local_heap_cross_ref;
286 286
    ///Pointer to the heap.
287 287
    Heap *_heap;
288 288
    ///Indicates if \ref _heap is locally allocated (\c true) or not.
289 289
    bool local_heap;
290 290

	
291 291
    ///Creates the maps if necessary.
292 292

	
293 293
    ///\todo Better memory allocation (instead of new).
294 294
    void create_maps()
295 295
    {
296 296
      if(!_pred) {
297 297
        local_pred = true;
298 298
        _pred = Traits::createPredMap(*G);
299 299
      }
300 300
      if(!_dist) {
301 301
        local_dist = true;
302 302
        _dist = Traits::createDistMap(*G);
303 303
      }
304 304
      if(!_processed) {
305 305
        local_processed = true;
306 306
        _processed = Traits::createProcessedMap(*G);
307 307
      }
308 308
      if (!_heap_cross_ref) {
309 309
        local_heap_cross_ref = true;
310 310
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
311 311
      }
312 312
      if (!_heap) {
313 313
        local_heap = true;
314 314
        _heap = Traits::createHeap(*_heap_cross_ref);
315 315
      }
316 316
    }
317 317

	
318 318
  public :
319 319

	
320 320
    typedef Dijkstra Create;
321 321

	
322 322
    ///\name Named template parameters
323 323

	
324 324
    ///@{
325 325

	
326 326
    template <class T>
327 327
    struct DefPredMapTraits : public Traits {
328 328
      typedef T PredMap;
329 329
      static PredMap *createPredMap(const Digraph &)
330 330
      {
331 331
        throw UninitializedParameter();
332 332
      }
333 333
    };
334 334
    ///\ref named-templ-param "Named parameter" for setting PredMap type
335 335

	
336 336
    ///\ref named-templ-param "Named parameter" for setting PredMap type
337 337
    ///
338 338
    template <class T>
339 339
    struct DefPredMap
340 340
      : public Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > {
341 341
      typedef Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > Create;
342 342
    };
343 343

	
344 344
    template <class T>
345 345
    struct DefDistMapTraits : public Traits {
346 346
      typedef T DistMap;
347 347
      static DistMap *createDistMap(const Digraph &)
348 348
      {
349 349
        throw UninitializedParameter();
350 350
      }
351 351
    };
352 352
    ///\ref named-templ-param "Named parameter" for setting DistMap type
353 353

	
354 354
    ///\ref named-templ-param "Named parameter" for setting DistMap type
355 355
    ///
356 356
    template <class T>
357 357
    struct DefDistMap
358 358
      : public Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > {
359 359
      typedef Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > Create;
360 360
    };
361 361

	
362 362
    template <class T>
363 363
    struct DefProcessedMapTraits : public Traits {
364 364
      typedef T ProcessedMap;
365 365
      static ProcessedMap *createProcessedMap(const Digraph &G)
366 366
      {
367 367
        throw UninitializedParameter();
368 368
      }
369 369
    };
370 370
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
371 371

	
372 372
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
373 373
    ///
374 374
    template <class T>
375 375
    struct DefProcessedMap
376 376
      : public Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > {
377 377
      typedef Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > Create;
378 378
    };
379 379

	
380 380
    struct DefDigraphProcessedMapTraits : public Traits {
381 381
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
382 382
      static ProcessedMap *createProcessedMap(const Digraph &G)
383 383
      {
384 384
        return new ProcessedMap(G);
385 385
      }
386 386
    };
387 387
    ///\brief \ref named-templ-param "Named parameter"
388 388
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
389 389
    ///
390 390
    ///\ref named-templ-param "Named parameter"
391 391
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
392 392
    ///If you don't set it explicitely, it will be automatically allocated.
393 393
    template <class T>
394 394
    struct DefProcessedMapToBeDefaultMap
395 395
      : public Dijkstra< Digraph, LengthMap, DefDigraphProcessedMapTraits> {
396 396
      typedef Dijkstra< Digraph, LengthMap, DefDigraphProcessedMapTraits>
397 397
      Create;
398 398
    };
399 399

	
400 400
    template <class H, class CR>
401 401
    struct DefHeapTraits : public Traits {
402 402
      typedef CR HeapCrossRef;
403 403
      typedef H Heap;
404 404
      static HeapCrossRef *createHeapCrossRef(const Digraph &) {
405 405
        throw UninitializedParameter();
406 406
      }
407 407
      static Heap *createHeap(HeapCrossRef &)
408 408
      {
409 409
        throw UninitializedParameter();
410 410
      }
411 411
    };
412 412
    ///\brief \ref named-templ-param "Named parameter" for setting
413 413
    ///heap and cross reference type
414 414
    ///
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DIM2_H
20 20
#define LEMON_DIM2_H
21 21

	
22 22
#include <iostream>
23
#include <lemon/bits/utility.h>
23
#include <lemon/core.h>
24 24

	
25 25
///\ingroup misc
26 26
///\file
27 27
///\brief A simple two dimensional vector and a bounding box implementation
28 28
///
29 29
/// The class \ref lemon::dim2::Point "dim2::Point" implements
30 30
/// a two dimensional vector with the usual operations.
31 31
///
32 32
/// The class \ref lemon::dim2::BoundingBox "dim2::BoundingBox"
33 33
/// can be used to determine
34 34
/// the rectangular bounding box of a set of
35 35
/// \ref lemon::dim2::Point "dim2::Point"'s.
36 36

	
37 37
namespace lemon {
38 38

	
39 39
  ///Tools for handling two dimensional coordinates
40 40

	
41 41
  ///This namespace is a storage of several
42 42
  ///tools for handling two dimensional coordinates
43 43
  namespace dim2 {
44 44

	
45 45
  /// \addtogroup misc
46 46
  /// @{
47 47

	
48 48
  /// A simple two dimensional vector (plainvector) implementation
49 49

	
50 50
  /// A simple two dimensional vector (plainvector) implementation
51 51
  /// with the usual vector operations.
52 52
  template<typename T>
53 53
    class Point {
54 54

	
55 55
    public:
56 56

	
57 57
      typedef T Value;
58 58

	
59 59
      ///First coordinate
60 60
      T x;
61 61
      ///Second coordinate
62 62
      T y;
63 63

	
64 64
      ///Default constructor
65 65
      Point() {}
66 66

	
67 67
      ///Construct an instance from coordinates
68 68
      Point(T a, T b) : x(a), y(b) { }
69 69

	
70 70
      ///Returns the dimension of the vector (i.e. returns 2).
71 71

	
72 72
      ///The dimension of the vector.
73 73
      ///This function always returns 2.
74 74
      int size() const { return 2; }
75 75

	
76 76
      ///Subscripting operator
77 77

	
78 78
      ///\c p[0] is \c p.x and \c p[1] is \c p.y
79 79
      ///
80 80
      T& operator[](int idx) { return idx == 0 ? x : y; }
81 81

	
82 82
      ///Const subscripting operator
83 83

	
84 84
      ///\c p[0] is \c p.x and \c p[1] is \c p.y
85 85
      ///
86 86
      const T& operator[](int idx) const { return idx == 0 ? x : y; }
87 87

	
88 88
      ///Conversion constructor
89 89
      template<class TT> Point(const Point<TT> &p) : x(p.x), y(p.y) {}
90 90

	
91 91
      ///Give back the square of the norm of the vector
92 92
      T normSquare() const {
93 93
        return x*x+y*y;
94 94
      }
95 95

	
96 96
      ///Increment the left hand side by \c u
97 97
      Point<T>& operator +=(const Point<T>& u) {
98 98
        x += u.x;
99 99
        y += u.y;
100 100
        return *this;
101 101
      }
102 102

	
103 103
      ///Decrement the left hand side by \c u
104 104
      Point<T>& operator -=(const Point<T>& u) {
105 105
        x -= u.x;
106 106
        y -= u.y;
107 107
        return *this;
108 108
      }
109 109

	
110 110
      ///Multiply the left hand side with a scalar
111 111
      Point<T>& operator *=(const T &u) {
112 112
        x *= u;
113 113
        y *= u;
114 114
        return *this;
115 115
      }
116 116

	
117 117
      ///Divide the left hand side by a scalar
118 118
      Point<T>& operator /=(const T &u) {
119 119
        x /= u;
120 120
        y /= u;
121 121
        return *this;
122 122
      }
123 123

	
124 124
      ///Return the scalar product of two vectors
125 125
      T operator *(const Point<T>& u) const {
126 126
        return x*u.x+y*u.y;
127 127
      }
128 128

	
129 129
      ///Return the sum of two vectors
130 130
      Point<T> operator+(const Point<T> &u) const {
131 131
        Point<T> b=*this;
132 132
        return b+=u;
133 133
      }
134 134

	
135 135
      ///Return the negative of the vector
136 136
      Point<T> operator-() const {
137 137
        Point<T> b=*this;
138 138
        b.x=-b.x; b.y=-b.y;
139 139
        return b;
140 140
      }
141 141

	
142 142
      ///Return the difference of two vectors
143 143
      Point<T> operator-(const Point<T> &u) const {
144 144
        Point<T> b=*this;
145 145
        return b-=u;
146 146
      }
147 147

	
148 148
      ///Return a vector multiplied by a scalar
149 149
      Point<T> operator*(const T &u) const {
150 150
        Point<T> b=*this;
151 151
        return b*=u;
152 152
      }
153 153

	
154 154
      ///Return a vector divided by a scalar
155 155
      Point<T> operator/(const T &u) const {
156 156
        Point<T> b=*this;
157 157
        return b/=u;
158 158
      }
159 159

	
160 160
      ///Test equality
161 161
      bool operator==(const Point<T> &u) const {
162 162
        return (x==u.x) && (y==u.y);
163 163
      }
164 164

	
165 165
      ///Test inequality
166 166
      bool operator!=(Point u) const {
167 167
        return  (x!=u.x) || (y!=u.y);
168 168
      }
169 169

	
170 170
    };
171 171

	
172 172
  ///Return a Point
173 173

	
174 174
  ///Return a Point.
175 175
  ///\relates Point
176 176
  template <typename T>
177 177
  inline Point<T> makePoint(const T& x, const T& y) {
178 178
    return Point<T>(x, y);
179 179
  }
180 180

	
181 181
  ///Return a vector multiplied by a scalar
182 182

	
183 183
  ///Return a vector multiplied by a scalar.
184 184
  ///\relates Point
185 185
  template<typename T> Point<T> operator*(const T &u,const Point<T> &x) {
186 186
    return x*u;
187 187
  }
188 188

	
189 189
  ///Read a plainvector from a stream
190 190

	
191 191
  ///Read a plainvector from a stream.
192 192
  ///\relates Point
193 193
  ///
194 194
  template<typename T>
195 195
  inline std::istream& operator>>(std::istream &is, Point<T> &z) {
196 196
    char c;
197 197
    if (is >> c) {
198 198
      if (c != '(') is.putback(c);
199 199
    } else {
200 200
      is.clear();
201 201
    }
202 202
    if (!(is >> z.x)) return is;
203 203
    if (is >> c) {
204 204
      if (c != ',') is.putback(c);
205 205
    } else {
206 206
      is.clear();
207 207
    }
208 208
    if (!(is >> z.y)) return is;
209 209
    if (is >> c) {
210 210
      if (c != ')') is.putback(c);
211 211
    } else {
212 212
      is.clear();
213 213
    }
214 214
    return is;
215 215
  }
216 216

	
217 217
  ///Write a plainvector to a stream
218 218

	
219 219
  ///Write a plainvector to a stream.
220 220
  ///\relates Point
221 221
  ///
222 222
  template<typename T>
223 223
  inline std::ostream& operator<<(std::ostream &os, const Point<T>& z)
224 224
  {
225 225
    os << "(" << z.x << ", " << z.y << ")";
226 226
    return os;
227 227
  }
228 228

	
229 229
  ///Rotate by 90 degrees
230 230

	
231 231
  ///Returns the parameter rotated by 90 degrees in positive direction.
232 232
  ///\relates Point
233 233
  ///
234 234
  template<typename T>
235 235
  inline Point<T> rot90(const Point<T> &z)
236 236
  {
237 237
    return Point<T>(-z.y,z.x);
238 238
  }
239 239

	
240 240
  ///Rotate by 180 degrees
241 241

	
242 242
  ///Returns the parameter rotated by 180 degrees.
243 243
  ///\relates Point
244 244
  ///
245 245
  template<typename T>
246 246
  inline Point<T> rot180(const Point<T> &z)
247 247
  {
248 248
    return Point<T>(-z.x,-z.y);
249 249
  }
250 250

	
251 251
  ///Rotate by 270 degrees
252 252

	
253 253
  ///Returns the parameter rotated by 90 degrees in negative direction.
254 254
  ///\relates Point
255 255
  ///
256 256
  template<typename T>
257 257
  inline Point<T> rot270(const Point<T> &z)
258 258
  {
259 259
    return Point<T>(z.y,-z.x);
260 260
  }
261 261

	
262 262

	
263 263

	
264 264
  /// A class to calculate or store the bounding box of plainvectors.
265 265

	
266 266
  /// A class to calculate or store the bounding box of plainvectors.
267 267
  ///
268 268
    template<typename T>
269 269
    class BoundingBox {
270 270
      Point<T> bottom_left, top_right;
271 271
      bool _empty;
272 272
    public:
273 273

	
274 274
      ///Default constructor: creates an empty bounding box
275 275
      BoundingBox() { _empty = true; }
276 276

	
277 277
      ///Construct an instance from one point
278 278
      BoundingBox(Point<T> a) { bottom_left=top_right=a; _empty = false; }
279 279

	
280 280
      ///Construct an instance from two points
281 281

	
282 282
      ///Construct an instance from two points.
283 283
      ///\param a The bottom left corner.
284 284
      ///\param b The top right corner.
285 285
      ///\warning The coordinates of the bottom left corner must be no more
286 286
      ///than those of the top right one.
287 287
      BoundingBox(Point<T> a,Point<T> b)
288 288
      {
289 289
        bottom_left=a;
290 290
        top_right=b;
291 291
        _empty = false;
292 292
      }
293 293

	
294 294
      ///Construct an instance from four numbers
295 295

	
296 296
      ///Construct an instance from four numbers.
297 297
      ///\param l The left side of the box.
298 298
      ///\param b The bottom of the box.
299 299
      ///\param r The right side of the box.
300 300
      ///\param t The top of the box.
301 301
      ///\warning The left side must be no more than the right side and
302 302
      ///bottom must be no more than the top.
303 303
      BoundingBox(T l,T b,T r,T t)
304 304
      {
305 305
        bottom_left=Point<T>(l,b);
306 306
        top_right=Point<T>(r,t);
307 307
        _empty = false;
308 308
      }
309 309

	
310 310
      ///Return \c true if the bounding box is empty.
311 311

	
312 312
      ///Return \c true if the bounding box is empty (i.e. return \c false
313 313
      ///if at least one point was added to the box or the coordinates of
314 314
      ///the box were set).
315 315
      ///
316 316
      ///The coordinates of an empty bounding box are not defined.
317 317
      bool empty() const {
318 318
        return _empty;
319 319
      }
320 320

	
321 321
      ///Make the BoundingBox empty
322 322
      void clear() {
323 323
        _empty=1;
324 324
      }
325 325

	
326 326
      ///Give back the bottom left corner of the box
327 327

	
328 328
      ///Give back the bottom left corner of the box.
329 329
      ///If the bounding box is empty, then the return value is not defined.
330 330
      Point<T> bottomLeft() const {
331 331
        return bottom_left;
332 332
      }
333 333

	
334 334
      ///Set the bottom left corner of the box
335 335

	
336 336
      ///Set the bottom left corner of the box.
337 337
      ///It should only be used for non-empty box.
338 338
      void bottomLeft(Point<T> p) {
339 339
        bottom_left = p;
340 340
      }
341 341

	
342 342
      ///Give back the top right corner of the box
343 343

	
344 344
      ///Give back the top right corner of the box.
345 345
      ///If the bounding box is empty, then the return value is not defined.
346 346
      Point<T> topRight() const {
347 347
        return top_right;
348 348
      }
349 349

	
350 350
      ///Set the top right corner of the box
351 351

	
352 352
      ///Set the top right corner of the box.
353 353
      ///It should only be used for non-empty box.
354 354
      void topRight(Point<T> p) {
355 355
        top_right = p;
356 356
      }
357 357

	
358 358
      ///Give back the bottom right corner of the box
359 359

	
360 360
      ///Give back the bottom right corner of the box.
361 361
      ///If the bounding box is empty, then the return value is not defined.
362 362
      Point<T> bottomRight() const {
363 363
        return Point<T>(top_right.x,bottom_left.y);
364 364
      }
365 365

	
366 366
      ///Set the bottom right corner of the box
367 367

	
368 368
      ///Set the bottom right corner of the box.
369 369
      ///It should only be used for non-empty box.
370 370
      void bottomRight(Point<T> p) {
371 371
        top_right.x = p.x;
372 372
        bottom_left.y = p.y;
373 373
      }
374 374

	
375 375
      ///Give back the top left corner of the box
376 376

	
377 377
      ///Give back the top left corner of the box.
378 378
      ///If the bounding box is empty, then the return value is not defined.
379 379
      Point<T> topLeft() const {
380 380
        return Point<T>(bottom_left.x,top_right.y);
381 381
      }
382 382

	
383 383
      ///Set the top left corner of the box
384 384

	
385 385
      ///Set the top left corner of the box.
386 386
      ///It should only be used for non-empty box.
387 387
      void topLeft(Point<T> p) {
388 388
        top_right.y = p.y;
389 389
        bottom_left.x = p.x;
390 390
      }
391 391

	
392 392
      ///Give back the bottom of the box
393 393

	
394 394
      ///Give back the bottom of the box.
395 395
      ///If the bounding box is empty, then the return value is not defined.
396 396
      T bottom() const {
397 397
        return bottom_left.y;
398 398
      }
399 399

	
400 400
      ///Set the bottom of the box
401 401

	
402 402
      ///Set the bottom of the box.
403 403
      ///It should only be used for non-empty box.
404 404
      void bottom(T t) {
405 405
        bottom_left.y = t;
406 406
      }
407 407

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

	
19 19
#ifndef LEMON_GRAPH_TO_EPS_H
20 20
#define LEMON_GRAPH_TO_EPS_H
21 21

	
22 22
#include<iostream>
23 23
#include<fstream>
24 24
#include<sstream>
25 25
#include<algorithm>
26 26
#include<vector>
27 27

	
28 28
#ifndef WIN32
29 29
#include<sys/time.h>
30 30
#include<ctime>
31 31
#else
32 32
#define WIN32_LEAN_AND_MEAN
33 33
#define NOMINMAX
34 34
#include<windows.h>
35 35
#endif
36 36

	
37 37
#include<lemon/math.h>
38
#include<lemon/bits/invalid.h>
38
#include<lemon/core.h>
39 39
#include<lemon/dim2.h>
40 40
#include<lemon/maps.h>
41 41
#include<lemon/color.h>
42 42
#include<lemon/bits/bezier.h>
43 43

	
44 44

	
45 45
///\ingroup eps_io
46 46
///\file
47 47
///\brief A well configurable tool for visualizing graphs
48 48

	
49 49
namespace lemon {
50 50

	
51 51
  namespace _graph_to_eps_bits {
52 52
    template<class MT>
53 53
    class _NegY {
54 54
    public:
55 55
      typedef typename MT::Key Key;
56 56
      typedef typename MT::Value Value;
57 57
      const MT &map;
58 58
      int yscale;
59 59
      _NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {}
60 60
      Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);}
61 61
    };
62 62
  }
63 63

	
64 64
///Default traits class of \ref GraphToEps
65 65

	
66 66
///Default traits class of \ref GraphToEps.
67 67
///
68 68
///\c G is the type of the underlying graph.
69 69
template<class G>
70 70
struct DefaultGraphToEpsTraits
71 71
{
72 72
  typedef G Graph;
73 73
  typedef typename Graph::Node Node;
74 74
  typedef typename Graph::NodeIt NodeIt;
75 75
  typedef typename Graph::Arc Arc;
76 76
  typedef typename Graph::ArcIt ArcIt;
77 77
  typedef typename Graph::InArcIt InArcIt;
78 78
  typedef typename Graph::OutArcIt OutArcIt;
79 79

	
80 80

	
81 81
  const Graph &g;
82 82

	
83 83
  std::ostream& os;
84 84

	
85 85
  typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType;
86 86
  CoordsMapType _coords;
87 87
  ConstMap<typename Graph::Node,double > _nodeSizes;
88 88
  ConstMap<typename Graph::Node,int > _nodeShapes;
89 89

	
90 90
  ConstMap<typename Graph::Node,Color > _nodeColors;
91 91
  ConstMap<typename Graph::Arc,Color > _arcColors;
92 92

	
93 93
  ConstMap<typename Graph::Arc,double > _arcWidths;
94 94

	
95 95
  double _arcWidthScale;
96 96

	
97 97
  double _nodeScale;
98 98
  double _xBorder, _yBorder;
99 99
  double _scale;
100 100
  double _nodeBorderQuotient;
101 101

	
102 102
  bool _drawArrows;
103 103
  double _arrowLength, _arrowWidth;
104 104

	
105 105
  bool _showNodes, _showArcs;
106 106

	
107 107
  bool _enableParallel;
108 108
  double _parArcDist;
109 109

	
110 110
  bool _showNodeText;
111 111
  ConstMap<typename Graph::Node,bool > _nodeTexts;
112 112
  double _nodeTextSize;
113 113

	
114 114
  bool _showNodePsText;
115 115
  ConstMap<typename Graph::Node,bool > _nodePsTexts;
116 116
  char *_nodePsTextsPreamble;
117 117

	
118 118
  bool _undirected;
119 119

	
120 120
  bool _pleaseRemoveOsStream;
121 121

	
122 122
  bool _scaleToA4;
123 123

	
124 124
  std::string _title;
125 125
  std::string _copyright;
126 126

	
127 127
  enum NodeTextColorType
128 128
    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
129 129
  ConstMap<typename Graph::Node,Color > _nodeTextColors;
130 130

	
131 131
  bool _autoNodeScale;
132 132
  bool _autoArcWidthScale;
133 133

	
134 134
  bool _absoluteNodeSizes;
135 135
  bool _absoluteArcWidths;
136 136

	
137 137
  bool _negY;
138 138

	
139 139
  bool _preScale;
140 140
  ///Constructor
141 141

	
142 142
  ///Constructor
143 143
  ///\param _g  Reference to the graph to be printed.
144 144
  ///\param _os Reference to the output stream.
145 145
  ///\param _os Reference to the output stream.
146 146
  ///By default it is <tt>std::cout</tt>.
147 147
  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
148 148
  ///will be explicitly deallocated by the destructor.
149 149
  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
150 150
                          bool _pros=false) :
151 151
    g(_g), os(_os),
152 152
    _coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0),
153 153
    _nodeColors(WHITE), _arcColors(BLACK),
154 154
    _arcWidths(1.0), _arcWidthScale(0.003),
155 155
    _nodeScale(.01), _xBorder(10), _yBorder(10), _scale(1.0),
156 156
    _nodeBorderQuotient(.1),
157 157
    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
158 158
    _showNodes(true), _showArcs(true),
159 159
    _enableParallel(false), _parArcDist(1),
160 160
    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
161 161
    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
162 162
    _undirected(lemon::UndirectedTagIndicator<G>::value),
163 163
    _pleaseRemoveOsStream(_pros), _scaleToA4(false),
164 164
    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
165 165
    _autoNodeScale(false),
166 166
    _autoArcWidthScale(false),
167 167
    _absoluteNodeSizes(false),
168 168
    _absoluteArcWidths(false),
169 169
    _negY(false),
170 170
    _preScale(true)
171 171
  {}
172 172
};
173 173

	
174 174
///Auxiliary class to implement the named parameters of \ref graphToEps()
175 175

	
176 176
///Auxiliary class to implement the named parameters of \ref graphToEps().
177 177
///
178 178
///For detailed examples see the \ref graph_to_eps_demo.cc demo file.
179 179
template<class T> class GraphToEps : public T
180 180
{
181 181
  // Can't believe it is required by the C++ standard
182 182
  using T::g;
183 183
  using T::os;
184 184

	
185 185
  using T::_coords;
186 186
  using T::_nodeSizes;
187 187
  using T::_nodeShapes;
188 188
  using T::_nodeColors;
189 189
  using T::_arcColors;
190 190
  using T::_arcWidths;
191 191

	
192 192
  using T::_arcWidthScale;
193 193
  using T::_nodeScale;
194 194
  using T::_xBorder;
195 195
  using T::_yBorder;
196 196
  using T::_scale;
197 197
  using T::_nodeBorderQuotient;
198 198

	
199 199
  using T::_drawArrows;
200 200
  using T::_arrowLength;
201 201
  using T::_arrowWidth;
202 202

	
203 203
  using T::_showNodes;
204 204
  using T::_showArcs;
205 205

	
206 206
  using T::_enableParallel;
207 207
  using T::_parArcDist;
208 208

	
209 209
  using T::_showNodeText;
210 210
  using T::_nodeTexts;
211 211
  using T::_nodeTextSize;
212 212

	
213 213
  using T::_showNodePsText;
214 214
  using T::_nodePsTexts;
215 215
  using T::_nodePsTextsPreamble;
216 216

	
217 217
  using T::_undirected;
218 218

	
219 219
  using T::_pleaseRemoveOsStream;
220 220

	
221 221
  using T::_scaleToA4;
222 222

	
223 223
  using T::_title;
224 224
  using T::_copyright;
225 225

	
226 226
  using T::NodeTextColorType;
227 227
  using T::CUST_COL;
228 228
  using T::DIST_COL;
229 229
  using T::DIST_BW;
230 230
  using T::_nodeTextColorType;
231 231
  using T::_nodeTextColors;
232 232

	
233 233
  using T::_autoNodeScale;
234 234
  using T::_autoArcWidthScale;
235 235

	
236 236
  using T::_absoluteNodeSizes;
237 237
  using T::_absoluteArcWidths;
238 238

	
239 239

	
240 240
  using T::_negY;
241 241
  using T::_preScale;
242 242

	
243 243
  // dradnats ++C eht yb deriuqer si ti eveileb t'naC
244 244

	
245 245
  typedef typename T::Graph Graph;
246 246
  typedef typename Graph::Node Node;
247 247
  typedef typename Graph::NodeIt NodeIt;
248 248
  typedef typename Graph::Arc Arc;
249 249
  typedef typename Graph::ArcIt ArcIt;
250 250
  typedef typename Graph::InArcIt InArcIt;
251 251
  typedef typename Graph::OutArcIt OutArcIt;
252 252

	
253 253
  static const int INTERPOL_PREC;
254 254
  static const double A4HEIGHT;
255 255
  static const double A4WIDTH;
256 256
  static const double A4BORDER;
257 257

	
258 258
  bool dontPrint;
259 259

	
260 260
public:
261 261
  ///Node shapes
262 262

	
263 263
  ///Node shapes.
264 264
  ///
265 265
  enum NodeShapes {
266 266
    /// = 0
267 267
    ///\image html nodeshape_0.png
268 268
    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
269 269
    CIRCLE=0,
270 270
    /// = 1
271 271
    ///\image html nodeshape_1.png
272 272
    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
273 273
    ///
274 274
    SQUARE=1,
275 275
    /// = 2
276 276
    ///\image html nodeshape_2.png
277 277
    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
278 278
    ///
279 279
    DIAMOND=2,
280 280
    /// = 3
281 281
    ///\image html nodeshape_3.png
282 282
    ///\image latex nodeshape_2.eps "MALE shape (4)" width=2cm
283 283
    ///
284 284
    MALE=3,
285 285
    /// = 4
286 286
    ///\image html nodeshape_4.png
287 287
    ///\image latex nodeshape_2.eps "FEMALE shape (4)" width=2cm
288 288
    ///
289 289
    FEMALE=4
290 290
  };
291 291

	
292 292
private:
293 293
  class arcLess {
294 294
    const Graph &g;
295 295
  public:
296 296
    arcLess(const Graph &_g) : g(_g) {}
297 297
    bool operator()(Arc a,Arc b) const
298 298
    {
299 299
      Node ai=std::min(g.source(a),g.target(a));
300 300
      Node aa=std::max(g.source(a),g.target(a));
301 301
      Node bi=std::min(g.source(b),g.target(b));
302 302
      Node ba=std::max(g.source(b),g.target(b));
303 303
      return ai<bi ||
304 304
        (ai==bi && (aa < ba ||
305 305
                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
306 306
    }
307 307
  };
308 308
  bool isParallel(Arc e,Arc f) const
309 309
  {
310 310
    return (g.source(e)==g.source(f)&&
311 311
            g.target(e)==g.target(f)) ||
312 312
      (g.source(e)==g.target(f)&&
313 313
       g.target(e)==g.source(f));
314 314
  }
315 315
  template<class TT>
316 316
  static std::string psOut(const dim2::Point<TT> &p)
317 317
    {
318 318
      std::ostringstream os;
319 319
      os << p.x << ' ' << p.y;
320 320
      return os.str();
321 321
    }
322 322
  static std::string psOut(const Color &c)
323 323
    {
324 324
      std::ostringstream os;
325 325
      os << c.red() << ' ' << c.green() << ' ' << c.blue();
326 326
      return os.str();
327 327
    }
328 328

	
329 329
public:
330 330
  GraphToEps(const T &t) : T(t), dontPrint(false) {};
331 331

	
332 332
  template<class X> struct CoordsTraits : public T {
333 333
  typedef X CoordsMapType;
334 334
    const X &_coords;
335 335
    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
336 336
  };
337 337
  ///Sets the map of the node coordinates
338 338

	
339 339
  ///Sets the map of the node coordinates.
340 340
  ///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or
341 341
  ///\ref dim2::Point "dim2::Point<int>" values.
342 342
  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
343 343
    dontPrint=true;
344 344
    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
345 345
  }
346 346
  template<class X> struct NodeSizesTraits : public T {
347 347
    const X &_nodeSizes;
348 348
    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
349 349
  };
350 350
  ///Sets the map of the node sizes
351 351

	
352 352
  ///Sets the map of the node sizes.
353 353
  ///\param x must be a node map with \c double (or convertible) values.
354 354
  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
355 355
  {
356 356
    dontPrint=true;
357 357
    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
358 358
  }
359 359
  template<class X> struct NodeShapesTraits : public T {
360 360
    const X &_nodeShapes;
361 361
    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
362 362
  };
363 363
  ///Sets the map of the node shapes
364 364

	
365 365
  ///Sets the map of the node shapes.
366 366
  ///The available shape values
367 367
  ///can be found in \ref NodeShapes "enum NodeShapes".
368 368
  ///\param x must be a node map with \c int (or convertible) values.
369 369
  ///\sa NodeShapes
370 370
  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
371 371
  {
372 372
    dontPrint=true;
373 373
    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
374 374
  }
375 375
  template<class X> struct NodeTextsTraits : public T {
376 376
    const X &_nodeTexts;
377 377
    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
378 378
  };
379 379
  ///Sets the text printed on the nodes
380 380

	
381 381
  ///Sets the text printed on the nodes.
382 382
  ///\param x must be a node map with type that can be pushed to a standard
383 383
  ///\c ostream.
384 384
  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
385 385
  {
386 386
    dontPrint=true;
387 387
    _showNodeText=true;
388 388
    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
389 389
  }
390 390
  template<class X> struct NodePsTextsTraits : public T {
391 391
    const X &_nodePsTexts;
392 392
    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
393 393
  };
394 394
  ///Inserts a PostScript block to the nodes
395 395

	
396 396
  ///With this command it is possible to insert a verbatim PostScript
397 397
  ///block to the nodes.
398 398
  ///The PS current point will be moved to the center of the node before
399 399
  ///the PostScript block inserted.
400 400
  ///
401 401
  ///Before and after the block a newline character is inserted so you
402 402
  ///don't have to bother with the separators.
403 403
  ///
404 404
  ///\param x must be a node map with type that can be pushed to a standard
405 405
  ///\c ostream.
406 406
  ///
407 407
  ///\sa nodePsTextsPreamble()
408 408
  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
409 409
  {
410 410
    dontPrint=true;
411 411
    _showNodePsText=true;
412 412
    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
413 413
  }
414 414
  template<class X> struct ArcWidthsTraits : public T {
415 415
    const X &_arcWidths;
416 416
    ArcWidthsTraits(const T &t,const X &x) : T(t), _arcWidths(x) {}
417 417
  };
418 418
  ///Sets the map of the arc widths
419 419

	
420 420
  ///Sets the map of the arc widths.
421 421
  ///\param x must be an arc map with \c double (or convertible) values.
422 422
  template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x)
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_KRUSKAL_H
20 20
#define LEMON_KRUSKAL_H
21 21

	
22 22
#include <algorithm>
23 23
#include <vector>
24 24
#include <lemon/unionfind.h>
25
// #include <lemon/graph_utils.h>
26 25
#include <lemon/maps.h>
27 26

	
28
// #include <lemon/radix_sort.h>
29

	
30
#include <lemon/bits/utility.h>
27
#include <lemon/core.h>
31 28
#include <lemon/bits/traits.h>
32 29

	
33 30
///\ingroup spantree
34 31
///\file
35 32
///\brief Kruskal's algorithm to compute a minimum cost spanning tree
36 33
///
37 34
///Kruskal's algorithm to compute a minimum cost spanning tree.
38 35
///
39 36

	
40 37
namespace lemon {
41 38

	
42 39
  namespace _kruskal_bits {
43 40

	
44 41
    // Kruskal for directed graphs.
45 42

	
46 43
    template <typename Digraph, typename In, typename Out>
47 44
    typename disable_if<lemon::UndirectedTagIndicator<Digraph>,
48 45
                       typename In::value_type::second_type >::type
49 46
    kruskal(const Digraph& digraph, const In& in, Out& out,dummy<0> = 0) {
50 47
      typedef typename In::value_type::second_type Value;
51 48
      typedef typename Digraph::template NodeMap<int> IndexMap;
52 49
      typedef typename Digraph::Node Node;
53 50

	
54 51
      IndexMap index(digraph);
55 52
      UnionFind<IndexMap> uf(index);
56 53
      for (typename Digraph::NodeIt it(digraph); it != INVALID; ++it) {
57 54
        uf.insert(it);
58 55
      }
59 56

	
60 57
      Value tree_value = 0;
61 58
      for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
62 59
        if (uf.join(digraph.target(it->first),digraph.source(it->first))) {
63 60
          out.set(it->first, true);
64 61
          tree_value += it->second;
65 62
        }
66 63
        else {
67 64
          out.set(it->first, false);
68 65
        }
69 66
      }
70 67
      return tree_value;
71 68
    }
72 69

	
73 70
    // Kruskal for undirected graphs.
74 71

	
75 72
    template <typename Graph, typename In, typename Out>
76 73
    typename enable_if<lemon::UndirectedTagIndicator<Graph>,
77 74
                       typename In::value_type::second_type >::type
78 75
    kruskal(const Graph& graph, const In& in, Out& out,dummy<1> = 1) {
79 76
      typedef typename In::value_type::second_type Value;
80 77
      typedef typename Graph::template NodeMap<int> IndexMap;
81 78
      typedef typename Graph::Node Node;
82 79

	
83 80
      IndexMap index(graph);
84 81
      UnionFind<IndexMap> uf(index);
85 82
      for (typename Graph::NodeIt it(graph); it != INVALID; ++it) {
86 83
        uf.insert(it);
87 84
      }
88 85

	
89 86
      Value tree_value = 0;
90 87
      for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
91 88
        if (uf.join(graph.u(it->first),graph.v(it->first))) {
92 89
          out.set(it->first, true);
93 90
          tree_value += it->second;
94 91
        }
95 92
        else {
96 93
          out.set(it->first, false);
97 94
        }
98 95
      }
99 96
      return tree_value;
100 97
    }
101 98

	
102 99

	
103 100
    template <typename Sequence>
104 101
    struct PairComp {
105 102
      typedef typename Sequence::value_type Value;
106 103
      bool operator()(const Value& left, const Value& right) {
107 104
        return left.second < right.second;
108 105
      }
109 106
    };
110 107

	
111 108
    template <typename In, typename Enable = void>
112 109
    struct SequenceInputIndicator {
113 110
      static const bool value = false;
114 111
    };
115 112

	
116 113
    template <typename In>
117 114
    struct SequenceInputIndicator<In,
118 115
      typename exists<typename In::value_type::first_type>::type> {
119 116
      static const bool value = true;
120 117
    };
121 118

	
122 119
    template <typename In, typename Enable = void>
123 120
    struct MapInputIndicator {
124 121
      static const bool value = false;
125 122
    };
126 123

	
127 124
    template <typename In>
128 125
    struct MapInputIndicator<In,
129 126
      typename exists<typename In::Value>::type> {
130 127
      static const bool value = true;
131 128
    };
132 129

	
133 130
    template <typename In, typename Enable = void>
134 131
    struct SequenceOutputIndicator {
135 132
      static const bool value = false;
136 133
    };
137 134

	
138 135
    template <typename Out>
139 136
    struct SequenceOutputIndicator<Out,
140 137
      typename exists<typename Out::value_type>::type> {
141 138
      static const bool value = true;
142 139
    };
143 140

	
144 141
    template <typename Out, typename Enable = void>
145 142
    struct MapOutputIndicator {
146 143
      static const bool value = false;
147 144
    };
148 145

	
149 146
    template <typename Out>
150 147
    struct MapOutputIndicator<Out,
151 148
      typename exists<typename Out::Value>::type> {
152 149
      static const bool value = true;
153 150
    };
154 151

	
155 152
    template <typename In, typename InEnable = void>
156 153
    struct KruskalValueSelector {};
157 154

	
158 155
    template <typename In>
159 156
    struct KruskalValueSelector<In,
160 157
      typename enable_if<SequenceInputIndicator<In>, void>::type>
161 158
    {
162 159
      typedef typename In::value_type::second_type Value;
163 160
    };
164 161

	
165 162
    template <typename In>
166 163
    struct KruskalValueSelector<In,
167 164
      typename enable_if<MapInputIndicator<In>, void>::type>
168 165
    {
169 166
      typedef typename In::Value Value;
170 167
    };
171 168

	
172 169
    template <typename Graph, typename In, typename Out,
173 170
              typename InEnable = void>
174 171
    struct KruskalInputSelector {};
175 172

	
176 173
    template <typename Graph, typename In, typename Out,
177 174
              typename InEnable = void>
178 175
    struct KruskalOutputSelector {};
179 176

	
180 177
    template <typename Graph, typename In, typename Out>
181 178
    struct KruskalInputSelector<Graph, In, Out,
182 179
      typename enable_if<SequenceInputIndicator<In>, void>::type >
183 180
    {
184 181
      typedef typename In::value_type::second_type Value;
185 182

	
186 183
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
187 184
        return KruskalOutputSelector<Graph, In, Out>::
188 185
          kruskal(graph, in, out);
189 186
      }
190 187

	
191 188
    };
192 189

	
193 190
    template <typename Graph, typename In, typename Out>
194 191
    struct KruskalInputSelector<Graph, In, Out,
195 192
      typename enable_if<MapInputIndicator<In>, void>::type >
196 193
    {
197 194
      typedef typename In::Value Value;
198 195
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
199 196
        typedef typename In::Key MapArc;
200 197
        typedef typename In::Value Value;
201 198
        typedef typename ItemSetTraits<Graph, MapArc>::ItemIt MapArcIt;
202 199
        typedef std::vector<std::pair<MapArc, Value> > Sequence;
203 200
        Sequence seq;
204 201

	
205 202
        for (MapArcIt it(graph); it != INVALID; ++it) {
206 203
          seq.push_back(std::make_pair(it, in[it]));
207 204
        }
208 205

	
209 206
        std::sort(seq.begin(), seq.end(), PairComp<Sequence>());
210 207
        return KruskalOutputSelector<Graph, Sequence, Out>::
211 208
          kruskal(graph, seq, out);
212 209
      }
213 210
    };
214 211

	
215 212
    template <typename T>
216 213
    struct RemoveConst {
217 214
      typedef T type;
218 215
    };
219 216

	
220 217
    template <typename T>
221 218
    struct RemoveConst<const T> {
222 219
      typedef T type;
223 220
    };
224 221

	
225 222
    template <typename Graph, typename In, typename Out>
226 223
    struct KruskalOutputSelector<Graph, In, Out,
227 224
      typename enable_if<SequenceOutputIndicator<Out>, void>::type >
228 225
    {
229 226
      typedef typename In::value_type::second_type Value;
230 227

	
231 228
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
232 229
        typedef LoggerBoolMap<typename RemoveConst<Out>::type> Map;
233 230
        Map map(out);
234 231
        return _kruskal_bits::kruskal(graph, in, map);
235 232
      }
236 233

	
237 234
    };
238 235

	
239 236
    template <typename Graph, typename In, typename Out>
240 237
    struct KruskalOutputSelector<Graph, In, Out,
241 238
      typename enable_if<MapOutputIndicator<Out>, void>::type >
242 239
    {
243 240
      typedef typename In::value_type::second_type Value;
244 241

	
245 242
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
246 243
        return _kruskal_bits::kruskal(graph, in, out);
247 244
      }
248 245
    };
249 246

	
250 247
  }
251 248

	
252 249
  /// \ingroup spantree
253 250
  ///
254 251
  /// \brief Kruskal algorithm to find a minimum cost spanning tree of
255 252
  /// a graph.
256 253
  ///
257 254
  /// This function runs Kruskal's algorithm to find a minimum cost
258 255
  /// spanning tree.
259 256
  /// Due to some C++ hacking, it accepts various input and output types.
260 257
  ///
261 258
  /// \param g The graph the algorithm runs on.
262 259
  /// It can be either \ref concepts::Digraph "directed" or
263 260
  /// \ref concepts::Graph "undirected".
264 261
  /// If the graph is directed, the algorithm consider it to be
265 262
  /// undirected by disregarding the direction of the arcs.
266 263
  ///
267 264
  /// \param in This object is used to describe the arc/edge costs.
268 265
  /// It can be one of the following choices.
269 266
  /// - An STL compatible 'Forward Container' with
270 267
  /// <tt>std::pair<GR::Arc,X></tt> or
271 268
  /// <tt>std::pair<GR::Edge,X></tt> as its <tt>value_type</tt>, where
272 269
  /// \c X is the type of the costs. The pairs indicates the arcs/edges
273 270
  /// along with the assigned cost. <em>They must be in a
274 271
  /// cost-ascending order.</em>
275 272
  /// - Any readable arc/edge map. The values of the map indicate the
276 273
  /// arc/edge costs.
277 274
  ///
278 275
  /// \retval out Here we also have a choice.
279 276
  /// - It can be a writable \c bool arc/edge map. After running the
280 277
  /// algorithm it will contain the found minimum cost spanning
281 278
  /// tree: the value of an arc/edge will be set to \c true if it belongs
282 279
  /// to the tree, otherwise it will be set to \c false. The value of
283 280
  /// each arc/edge will be set exactly once.
284 281
  /// - It can also be an iteraror of an STL Container with
285 282
  /// <tt>GR::Arc</tt> or <tt>GR::Edge</tt> as its
286 283
  /// <tt>value_type</tt>.  The algorithm copies the elements of the
287 284
  /// found tree into this sequence.  For example, if we know that the
288 285
  /// spanning tree of the graph \c g has say 53 arcs, then we can
289 286
  /// put its arcs into an STL vector \c tree with a code like this.
290 287
  ///\code
291 288
  /// std::vector<Arc> tree(53);
292 289
  /// kruskal(g,cost,tree.begin());
293 290
  ///\endcode
294 291
  /// Or if we don't know in advance the size of the tree, we can
295 292
  /// write this.
296 293
  ///\code
297 294
  /// std::vector<Arc> tree;
298 295
  /// kruskal(g,cost,std::back_inserter(tree));
299 296
  ///\endcode
300 297
  ///
301 298
  /// \return The total cost of the found spanning tree.
302 299
  ///
303
  /// \note If the input graph is not (weakly) connected, a spanning 
300
  /// \note If the input graph is not (weakly) connected, a spanning
304 301
  /// forest is calculated instead of a spanning tree.
305 302

	
306 303
#ifdef DOXYGEN
307 304
  template <class Graph, class In, class Out>
308 305
  Value kruskal(GR const& g, const In& in, Out& out)
309 306
#else
310 307
  template <class Graph, class In, class Out>
311 308
  inline typename _kruskal_bits::KruskalValueSelector<In>::Value
312 309
  kruskal(const Graph& graph, const In& in, Out& out)
313 310
#endif
314 311
  {
315 312
    return _kruskal_bits::KruskalInputSelector<Graph, In, Out>::
316 313
      kruskal(graph, in, out);
317 314
  }
318 315

	
319 316

	
320 317

	
321 318

	
322 319
  template <class Graph, class In, class Out>
323 320
  inline typename _kruskal_bits::KruskalValueSelector<In>::Value
324 321
  kruskal(const Graph& graph, const In& in, const Out& out)
325 322
  {
326 323
    return _kruskal_bits::KruskalInputSelector<Graph, In, const Out>::
327 324
      kruskal(graph, in, out);
328 325
  }
329 326

	
330 327
} //namespace lemon
331 328

	
332 329
#endif //LEMON_KRUSKAL_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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
///\ingroup lemon_io
20 20
///\file
21 21
///\brief \ref lgf-format "Lemon Graph Format" reader.
22 22

	
23 23

	
24 24
#ifndef LEMON_LGF_READER_H
25 25
#define LEMON_LGF_READER_H
26 26

	
27 27
#include <iostream>
28 28
#include <fstream>
29 29
#include <sstream>
30 30

	
31 31
#include <set>
32 32
#include <map>
33 33

	
34 34
#include <lemon/assert.h>
35
#include <lemon/graph_utils.h>
35
#include <lemon/core.h>
36 36

	
37 37
#include <lemon/lgf_writer.h>
38 38

	
39 39
#include <lemon/concept_check.h>
40 40
#include <lemon/concepts/maps.h>
41 41

	
42 42
namespace lemon {
43 43

	
44 44
  namespace _reader_bits {
45 45

	
46 46
    template <typename Value>
47 47
    struct DefaultConverter {
48 48
      Value operator()(const std::string& str) {
49 49
        std::istringstream is(str);
50 50
        Value value;
51 51
        is >> value;
52 52

	
53 53
        char c;
54 54
        if (is >> std::ws >> c) {
55 55
          throw DataFormatError("Remaining characters in token");
56 56
        }
57 57
        return value;
58 58
      }
59 59
    };
60 60

	
61 61
    template <>
62 62
    struct DefaultConverter<std::string> {
63 63
      std::string operator()(const std::string& str) {
64 64
        return str;
65 65
      }
66 66
    };
67 67

	
68 68
    template <typename _Item>
69 69
    class MapStorageBase {
70 70
    public:
71 71
      typedef _Item Item;
72 72

	
73 73
    public:
74 74
      MapStorageBase() {}
75 75
      virtual ~MapStorageBase() {}
76 76

	
77 77
      virtual void set(const Item& item, const std::string& value) = 0;
78 78

	
79 79
    };
80 80

	
81 81
    template <typename _Item, typename _Map,
82 82
              typename _Converter = DefaultConverter<typename _Map::Value> >
83 83
    class MapStorage : public MapStorageBase<_Item> {
84 84
    public:
85 85
      typedef _Map Map;
86 86
      typedef _Converter Converter;
87 87
      typedef _Item Item;
88 88

	
89 89
    private:
90 90
      Map& _map;
91 91
      Converter _converter;
92 92

	
93 93
    public:
94 94
      MapStorage(Map& map, const Converter& converter = Converter())
95 95
        : _map(map), _converter(converter) {}
96 96
      virtual ~MapStorage() {}
97 97

	
98 98
      virtual void set(const Item& item ,const std::string& value) {
99 99
        _map.set(item, _converter(value));
100 100
      }
101 101
    };
102 102

	
103 103
    template <typename _Graph, bool _dir, typename _Map,
104 104
              typename _Converter = DefaultConverter<typename _Map::Value> >
105 105
    class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
106 106
    public:
107 107
      typedef _Map Map;
108 108
      typedef _Converter Converter;
109 109
      typedef _Graph Graph;
110 110
      typedef typename Graph::Edge Item;
111 111
      static const bool dir = _dir;
112 112

	
113 113
    private:
114 114
      const Graph& _graph;
115 115
      Map& _map;
116 116
      Converter _converter;
117 117

	
118 118
    public:
119 119
      GraphArcMapStorage(const Graph& graph, Map& map,
120 120
                         const Converter& converter = Converter())
121 121
        : _graph(graph), _map(map), _converter(converter) {}
122 122
      virtual ~GraphArcMapStorage() {}
123 123

	
124 124
      virtual void set(const Item& item ,const std::string& value) {
125 125
        _map.set(_graph.direct(item, dir), _converter(value));
126 126
      }
127 127
    };
128 128

	
129 129
    class ValueStorageBase {
130 130
    public:
131 131
      ValueStorageBase() {}
132 132
      virtual ~ValueStorageBase() {}
133 133

	
134 134
      virtual void set(const std::string&) = 0;
135 135
    };
136 136

	
137 137
    template <typename _Value, typename _Converter = DefaultConverter<_Value> >
138 138
    class ValueStorage : public ValueStorageBase {
139 139
    public:
140 140
      typedef _Value Value;
141 141
      typedef _Converter Converter;
142 142

	
143 143
    private:
144 144
      Value& _value;
145 145
      Converter _converter;
146 146

	
147 147
    public:
148 148
      ValueStorage(Value& value, const Converter& converter = Converter())
149 149
        : _value(value), _converter(converter) {}
150 150

	
151 151
      virtual void set(const std::string& value) {
152 152
        _value = _converter(value);
153 153
      }
154 154
    };
155 155

	
156 156
    template <typename Value>
157 157
    struct MapLookUpConverter {
158 158
      const std::map<std::string, Value>& _map;
159 159

	
160 160
      MapLookUpConverter(const std::map<std::string, Value>& map)
161 161
        : _map(map) {}
162 162

	
163 163
      Value operator()(const std::string& str) {
164 164
        typename std::map<std::string, Value>::const_iterator it =
165 165
          _map.find(str);
166 166
        if (it == _map.end()) {
167 167
          std::ostringstream msg;
168 168
          msg << "Item not found: " << str;
169 169
          throw DataFormatError(msg.str().c_str());
170 170
        }
171 171
        return it->second;
172 172
      }
173 173
    };
174 174

	
175 175
    template <typename Graph>
176 176
    struct GraphArcLookUpConverter {
177 177
      const Graph& _graph;
178 178
      const std::map<std::string, typename Graph::Edge>& _map;
179 179

	
180 180
      GraphArcLookUpConverter(const Graph& graph,
181 181
                              const std::map<std::string,
182 182
                                             typename Graph::Edge>& map)
183 183
        : _graph(graph), _map(map) {}
184 184

	
185 185
      typename Graph::Arc operator()(const std::string& str) {
186 186
        if (str.empty() || (str[0] != '+' && str[0] != '-')) {
187 187
          throw DataFormatError("Item must start with '+' or '-'");
188 188
        }
189 189
        typename std::map<std::string, typename Graph::Edge>
190 190
          ::const_iterator it = _map.find(str.substr(1));
191 191
        if (it == _map.end()) {
192 192
          throw DataFormatError("Item not found");
193 193
        }
194 194
        return _graph.direct(it->second, str[0] == '+');
195 195
      }
196 196
    };
197 197

	
198 198
    inline bool isWhiteSpace(char c) {
199 199
      return c == ' ' || c == '\t' || c == '\v' ||
200 200
        c == '\n' || c == '\r' || c == '\f';
201 201
    }
202 202

	
203 203
    inline bool isOct(char c) {
204 204
      return '0' <= c && c <='7';
205 205
    }
206 206

	
207 207
    inline int valueOct(char c) {
208 208
      LEMON_ASSERT(isOct(c), "The character is not octal.");
209 209
      return c - '0';
210 210
    }
211 211

	
212 212
    inline bool isHex(char c) {
213 213
      return ('0' <= c && c <= '9') ||
214 214
        ('a' <= c && c <= 'z') ||
215 215
        ('A' <= c && c <= 'Z');
216 216
    }
217 217

	
218 218
    inline int valueHex(char c) {
219 219
      LEMON_ASSERT(isHex(c), "The character is not hexadecimal.");
220 220
      if ('0' <= c && c <= '9') return c - '0';
221 221
      if ('a' <= c && c <= 'z') return c - 'a' + 10;
222 222
      return c - 'A' + 10;
223 223
    }
224 224

	
225 225
    inline bool isIdentifierFirstChar(char c) {
226 226
      return ('a' <= c && c <= 'z') ||
227 227
        ('A' <= c && c <= 'Z') || c == '_';
228 228
    }
229 229

	
230 230
    inline bool isIdentifierChar(char c) {
231 231
      return isIdentifierFirstChar(c) ||
232 232
        ('0' <= c && c <= '9');
233 233
    }
234 234

	
235 235
    inline char readEscape(std::istream& is) {
236 236
      char c;
237 237
      if (!is.get(c))
238 238
        throw DataFormatError("Escape format error");
239 239

	
240 240
      switch (c) {
241 241
      case '\\':
242 242
        return '\\';
243 243
      case '\"':
244 244
        return '\"';
245 245
      case '\'':
246 246
        return '\'';
247 247
      case '\?':
248 248
        return '\?';
249 249
      case 'a':
250 250
        return '\a';
251 251
      case 'b':
252 252
        return '\b';
253 253
      case 'f':
254 254
        return '\f';
255 255
      case 'n':
256 256
        return '\n';
257 257
      case 'r':
258 258
        return '\r';
259 259
      case 't':
260 260
        return '\t';
261 261
      case 'v':
262 262
        return '\v';
263 263
      case 'x':
264 264
        {
265 265
          int code;
266 266
          if (!is.get(c) || !isHex(c))
267 267
            throw DataFormatError("Escape format error");
268 268
          else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c);
269 269
          else code = code * 16 + valueHex(c);
270 270
          return code;
271 271
        }
272 272
      default:
273 273
        {
274 274
          int code;
275 275
          if (!isOct(c))
276 276
            throw DataFormatError("Escape format error");
277 277
          else if (code = valueOct(c), !is.get(c) || !isOct(c))
278 278
            is.putback(c);
279 279
          else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c))
280 280
            is.putback(c);
281 281
          else code = code * 8 + valueOct(c);
282 282
          return code;
283 283
        }
284 284
      }
285 285
    }
286 286

	
287 287
    inline std::istream& readToken(std::istream& is, std::string& str) {
288 288
      std::ostringstream os;
289 289

	
290 290
      char c;
291 291
      is >> std::ws;
292 292

	
293 293
      if (!is.get(c))
294 294
        return is;
295 295

	
296 296
      if (c == '\"') {
297 297
        while (is.get(c) && c != '\"') {
298 298
          if (c == '\\')
299 299
            c = readEscape(is);
300 300
          os << c;
301 301
        }
302 302
        if (!is)
303 303
          throw DataFormatError("Quoted format error");
304 304
      } else {
305 305
        is.putback(c);
306 306
        while (is.get(c) && !isWhiteSpace(c)) {
307 307
          if (c == '\\')
308 308
            c = readEscape(is);
309 309
          os << c;
310 310
        }
311 311
        if (!is) {
312 312
          is.clear();
313 313
        } else {
314 314
          is.putback(c);
315 315
        }
316 316
      }
317 317
      str = os.str();
318 318
      return is;
319 319
    }
320 320

	
321 321
    class Section {
322 322
    public:
323 323
      virtual ~Section() {}
324 324
      virtual void process(std::istream& is, int& line_num) = 0;
325 325
    };
326 326

	
327 327
    template <typename Functor>
328 328
    class LineSection : public Section {
329 329
    private:
330 330

	
331 331
      Functor _functor;
332 332

	
333 333
    public:
334 334

	
335 335
      LineSection(const Functor& functor) : _functor(functor) {}
336 336
      virtual ~LineSection() {}
337 337

	
338 338
      virtual void process(std::istream& is, int& line_num) {
339 339
        char c;
340 340
        std::string line;
341 341
        while (is.get(c) && c != '@') {
342 342
          if (c == '\n') {
343 343
            ++line_num;
344 344
          } else if (c == '#') {
345 345
            getline(is, line);
346 346
            ++line_num;
347 347
          } else if (!isWhiteSpace(c)) {
348 348
            is.putback(c);
349 349
            getline(is, line);
350 350
            _functor(line);
351 351
            ++line_num;
352 352
          }
353 353
        }
354 354
        if (is) is.putback(c);
355 355
        else if (is.eof()) is.clear();
356 356
      }
357 357
    };
358 358

	
359 359
    template <typename Functor>
360 360
    class StreamSection : public Section {
361 361
    private:
362 362

	
363 363
      Functor _functor;
364 364

	
365 365
    public:
366 366

	
367 367
      StreamSection(const Functor& functor) : _functor(functor) {}
368 368
      virtual ~StreamSection() {}
369 369

	
370 370
      virtual void process(std::istream& is, int& line_num) {
371 371
        _functor(is, line_num);
372 372
        char c;
373 373
        std::string line;
374 374
        while (is.get(c) && c != '@') {
375 375
          if (c == '\n') {
376 376
            ++line_num;
377 377
          } else if (!isWhiteSpace(c)) {
378 378
            getline(is, line);
379 379
            ++line_num;
380 380
          }
381 381
        }
382 382
        if (is) is.putback(c);
383 383
        else if (is.eof()) is.clear();
384 384
      }
385 385
    };
386 386

	
387 387
  }
388 388

	
389 389
  template <typename Digraph>
390 390
  class DigraphReader;
391 391

	
392 392
  template <typename Digraph>
393 393
  DigraphReader<Digraph> digraphReader(std::istream& is, Digraph& digraph);
394 394

	
395 395
  template <typename Digraph>
396 396
  DigraphReader<Digraph> digraphReader(const std::string& fn, Digraph& digraph);
397 397

	
398 398
  template <typename Digraph>
399 399
  DigraphReader<Digraph> digraphReader(const char *fn, Digraph& digraph);
400 400

	
401 401
  /// \ingroup lemon_io
402 402
  ///
403 403
  /// \brief \ref lgf-format "LGF" reader for directed graphs
404 404
  ///
405 405
  /// This utility reads an \ref lgf-format "LGF" file.
406 406
  ///
407 407
  /// The reading method does a batch processing. The user creates a
408 408
  /// reader object, then various reading rules can be added to the
409 409
  /// reader, and eventually the reading is executed with the \c run()
410 410
  /// member function. A map reading rule can be added to the reader
411 411
  /// with the \c nodeMap() or \c arcMap() members. An optional
412 412
  /// converter parameter can also be added as a standard functor
413 413
  /// converting from \c std::string to the value type of the map. If it
414 414
  /// is set, it will determine how the tokens in the file should be
415 415
  /// converted to the value type of the map. If the functor is not set,
416 416
  /// then a default conversion will be used. One map can be read into
417 417
  /// multiple map objects at the same time. The \c attribute(), \c
418 418
  /// node() and \c arc() functions are used to add attribute reading
419 419
  /// rules.
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup lemon_io
20 20
///\file
21 21
///\brief \ref lgf-format "Lemon Graph Format" writer.
22 22

	
23 23

	
24 24
#ifndef LEMON_LGF_WRITER_H
25 25
#define LEMON_LGF_WRITER_H
26 26

	
27 27
#include <iostream>
28 28
#include <fstream>
29 29
#include <sstream>
30 30

	
31 31
#include <algorithm>
32 32

	
33 33
#include <vector>
34 34
#include <functional>
35 35

	
36 36
#include <lemon/assert.h>
37
#include <lemon/graph_utils.h>
37
#include <lemon/core.h>
38
#include <lemon/maps.h>
38 39

	
39 40
namespace lemon {
40 41

	
41 42
  namespace _writer_bits {
42 43

	
43 44
    template <typename Value>
44 45
    struct DefaultConverter {
45 46
      std::string operator()(const Value& value) {
46 47
        std::ostringstream os;
47 48
        os << value;
48 49
        return os.str();
49 50
      }
50 51
    };
51 52

	
52 53
    template <typename T>
53 54
    bool operator<(const T&, const T&) {
54 55
      throw DataFormatError("Label map is not comparable");
55 56
    }
56 57

	
57 58
    template <typename _Map>
58 59
    class MapLess {
59 60
    public:
60 61
      typedef _Map Map;
61 62
      typedef typename Map::Key Item;
62 63

	
63 64
    private:
64 65
      const Map& _map;
65 66

	
66 67
    public:
67 68
      MapLess(const Map& map) : _map(map) {}
68 69

	
69 70
      bool operator()(const Item& left, const Item& right) {
70 71
        return _map[left] < _map[right];
71 72
      }
72 73
    };
73 74

	
74 75
    template <typename _Graph, bool _dir, typename _Map>
75 76
    class GraphArcMapLess {
76 77
    public:
77 78
      typedef _Map Map;
78 79
      typedef _Graph Graph;
79 80
      typedef typename Graph::Edge Item;
80 81

	
81 82
    private:
82 83
      const Graph& _graph;
83 84
      const Map& _map;
84 85

	
85 86
    public:
86 87
      GraphArcMapLess(const Graph& graph, const Map& map)
87 88
        : _graph(graph), _map(map) {}
88 89

	
89 90
      bool operator()(const Item& left, const Item& right) {
90 91
        return _map[_graph.direct(left, _dir)] <
91 92
          _map[_graph.direct(right, _dir)];
92 93
      }
93 94
    };
94 95

	
95 96
    template <typename _Item>
96 97
    class MapStorageBase {
97 98
    public:
98 99
      typedef _Item Item;
99 100

	
100 101
    public:
101 102
      MapStorageBase() {}
102 103
      virtual ~MapStorageBase() {}
103 104

	
104 105
      virtual std::string get(const Item& item) = 0;
105 106
      virtual void sort(std::vector<Item>&) = 0;
106 107
    };
107 108

	
108 109
    template <typename _Item, typename _Map,
109 110
              typename _Converter = DefaultConverter<typename _Map::Value> >
110 111
    class MapStorage : public MapStorageBase<_Item> {
111 112
    public:
112 113
      typedef _Map Map;
113 114
      typedef _Converter Converter;
114 115
      typedef _Item Item;
115 116

	
116 117
    private:
117 118
      const Map& _map;
118 119
      Converter _converter;
119 120

	
120 121
    public:
121 122
      MapStorage(const Map& map, const Converter& converter = Converter())
122 123
        : _map(map), _converter(converter) {}
123 124
      virtual ~MapStorage() {}
124 125

	
125 126
      virtual std::string get(const Item& item) {
126 127
        return _converter(_map[item]);
127 128
      }
128 129
      virtual void sort(std::vector<Item>& items) {
129 130
        MapLess<Map> less(_map);
130 131
        std::sort(items.begin(), items.end(), less);
131 132
      }
132 133
    };
133 134

	
134 135
    template <typename _Graph, bool _dir, typename _Map,
135 136
              typename _Converter = DefaultConverter<typename _Map::Value> >
136 137
    class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> {
137 138
    public:
138 139
      typedef _Map Map;
139 140
      typedef _Converter Converter;
140 141
      typedef _Graph Graph;
141 142
      typedef typename Graph::Edge Item;
142 143
      static const bool dir = _dir;
143 144

	
144 145
    private:
145 146
      const Graph& _graph;
146 147
      const Map& _map;
147 148
      Converter _converter;
148 149

	
149 150
    public:
150 151
      GraphArcMapStorage(const Graph& graph, const Map& map,
151 152
                         const Converter& converter = Converter())
152 153
        : _graph(graph), _map(map), _converter(converter) {}
153 154
      virtual ~GraphArcMapStorage() {}
154 155

	
155 156
      virtual std::string get(const Item& item) {
156 157
        return _converter(_map[_graph.direct(item, dir)]);
157 158
      }
158 159
      virtual void sort(std::vector<Item>& items) {
159 160
        GraphArcMapLess<Graph, dir, Map> less(_graph, _map);
160 161
        std::sort(items.begin(), items.end(), less);
161 162
      }
162 163
    };
163 164

	
164 165
    class ValueStorageBase {
165 166
    public:
166 167
      ValueStorageBase() {}
167 168
      virtual ~ValueStorageBase() {}
168 169

	
169 170
      virtual std::string get() = 0;
170 171
    };
171 172

	
172 173
    template <typename _Value, typename _Converter = DefaultConverter<_Value> >
173 174
    class ValueStorage : public ValueStorageBase {
174 175
    public:
175 176
      typedef _Value Value;
176 177
      typedef _Converter Converter;
177 178

	
178 179
    private:
179 180
      const Value& _value;
180 181
      Converter _converter;
181 182

	
182 183
    public:
183 184
      ValueStorage(const Value& value, const Converter& converter = Converter())
184 185
        : _value(value), _converter(converter) {}
185 186

	
186 187
      virtual std::string get() {
187 188
        return _converter(_value);
188 189
      }
189 190
    };
190 191

	
191 192
    template <typename Value>
192 193
    struct MapLookUpConverter {
193 194
      const std::map<Value, std::string>& _map;
194 195

	
195 196
      MapLookUpConverter(const std::map<Value, std::string>& map)
196 197
        : _map(map) {}
197 198

	
198 199
      std::string operator()(const Value& str) {
199 200
        typename std::map<Value, std::string>::const_iterator it =
200 201
          _map.find(str);
201 202
        if (it == _map.end()) {
202 203
          throw DataFormatError("Item not found");
203 204
        }
204 205
        return it->second;
205 206
      }
206 207
    };
207 208

	
208 209
    template <typename Graph>
209 210
    struct GraphArcLookUpConverter {
210 211
      const Graph& _graph;
211 212
      const std::map<typename Graph::Edge, std::string>& _map;
212 213

	
213 214
      GraphArcLookUpConverter(const Graph& graph,
214 215
                              const std::map<typename Graph::Edge,
215 216
                                             std::string>& map)
216 217
        : _graph(graph), _map(map) {}
217 218

	
218 219
      std::string operator()(const typename Graph::Arc& val) {
219 220
        typename std::map<typename Graph::Edge, std::string>
220 221
          ::const_iterator it = _map.find(val);
221 222
        if (it == _map.end()) {
222 223
          throw DataFormatError("Item not found");
223 224
        }
224 225
        return (_graph.direction(val) ? '+' : '-') + it->second;
225 226
      }
226 227
    };
227 228

	
228 229
    inline bool isWhiteSpace(char c) {
229 230
      return c == ' ' || c == '\t' || c == '\v' ||
230 231
        c == '\n' || c == '\r' || c == '\f';
231 232
    }
232 233

	
233 234
    inline bool isEscaped(char c) {
234 235
      return c == '\\' || c == '\"' || c == '\'' ||
235 236
        c == '\a' || c == '\b';
236 237
    }
237 238

	
238 239
    inline static void writeEscape(std::ostream& os, char c) {
239 240
      switch (c) {
240 241
      case '\\':
241 242
        os << "\\\\";
242 243
        return;
243 244
      case '\"':
244 245
        os << "\\\"";
245 246
        return;
246 247
      case '\a':
247 248
        os << "\\a";
248 249
        return;
249 250
      case '\b':
250 251
        os << "\\b";
251 252
        return;
252 253
      case '\f':
253 254
        os << "\\f";
254 255
        return;
255 256
      case '\r':
256 257
        os << "\\r";
257 258
        return;
258 259
      case '\n':
259 260
        os << "\\n";
260 261
        return;
261 262
      case '\t':
262 263
        os << "\\t";
263 264
        return;
264 265
      case '\v':
265 266
        os << "\\v";
266 267
        return;
267 268
      default:
268 269
        if (c < 0x20) {
269 270
          std::ios::fmtflags flags = os.flags();
270 271
          os << '\\' << std::oct << static_cast<int>(c);
271 272
          os.flags(flags);
272 273
        } else {
273 274
          os << c;
274 275
        }
275 276
        return;
276 277
      }
277 278
    }
278 279

	
279 280
    inline bool requireEscape(const std::string& str) {
280 281
      if (str.empty() || str[0] == '@') return true;
281 282
      std::istringstream is(str);
282 283
      char c;
283 284
      while (is.get(c)) {
284 285
        if (isWhiteSpace(c) || isEscaped(c)) {
285 286
          return true;
286 287
        }
287 288
      }
288 289
      return false;
289 290
    }
290 291

	
291 292
    inline std::ostream& writeToken(std::ostream& os, const std::string& str) {
292 293

	
293 294
      if (requireEscape(str)) {
294 295
        os << '\"';
295 296
        for (std::string::const_iterator it = str.begin();
296 297
             it != str.end(); ++it) {
297 298
          writeEscape(os, *it);
298 299
        }
299 300
        os << '\"';
300 301
      } else {
301 302
        os << str;
302 303
      }
303 304
      return os;
304 305
    }
305 306

	
306 307
  }
307 308

	
308 309
  template <typename Digraph>
309 310
  class DigraphWriter;
310 311

	
311 312
  template <typename Digraph>
312 313
  DigraphWriter<Digraph> digraphWriter(std::ostream& os,
313 314
                                       const Digraph& digraph);
314 315

	
315 316
  template <typename Digraph>
316 317
  DigraphWriter<Digraph> digraphWriter(const std::string& fn,
317 318
                                       const Digraph& digraph);
318 319

	
319 320
  template <typename Digraph>
320 321
  DigraphWriter<Digraph> digraphWriter(const char *fn,
321 322
                                       const Digraph& digraph);
322 323

	
323 324
  /// \ingroup lemon_io
324 325
  ///
325 326
  /// \brief \ref lgf-format "LGF" writer for directed graphs
326 327
  ///
327 328
  /// This utility writes an \ref lgf-format "LGF" file.
328 329
  ///
329 330
  /// The writing method does a batch processing. The user creates a
330 331
  /// writer object, then various writing rules can be added to the
331 332
  /// writer, and eventually the writing is executed with the \c run()
332 333
  /// member function. A map writing rule can be added to the writer
333 334
  /// with the \c nodeMap() or \c arcMap() members. An optional
334 335
  /// converter parameter can also be added as a standard functor
335 336
  /// converting from the value type of the map to \c std::string. If it
336 337
  /// is set, it will determine how the value type of the map is written to
337 338
  /// the output stream. If the functor is not set, then a default
338 339
  /// conversion will be used. The \c attribute(), \c node() and \c
339 340
  /// arc() functions are used to add attribute writing rules.
340 341
  ///
341 342
  ///\code
342 343
  /// DigraphWriter<Digraph>(std::cout, digraph).
343 344
  ///   nodeMap("coordinates", coord_map).
344 345
  ///   nodeMap("size", size).
345 346
  ///   nodeMap("title", title).
346 347
  ///   arcMap("capacity", cap_map).
347 348
  ///   node("source", src).
348 349
  ///   node("target", trg).
349 350
  ///   attribute("caption", caption).
350 351
  ///   run();
351 352
  ///\endcode
352 353
  ///
353 354
  ///
354 355
  /// By default, the writer does not write additional captions to the
355 356
  /// sections, but they can be give as an optional parameter of
356 357
  /// the \c nodes(), \c arcs() or \c
357 358
  /// attributes() functions.
358 359
  ///
359 360
  /// The \c skipNodes() and \c skipArcs() functions forbid the
360 361
  /// writing of the sections. If two arc sections should be written
361 362
  /// to the output, it can be done in two passes, the first pass
362 363
  /// writes the node section and the first arc section, then the
363 364
  /// second pass skips the node section and writes just the arc
364 365
  /// section to the stream. The output stream can be retrieved with
365 366
  /// the \c ostream() function, hence the second pass can append its
366 367
  /// output to the output of the first pass.
367 368
  template <typename _Digraph>
368 369
  class DigraphWriter {
369 370
  public:
370 371

	
371 372
    typedef _Digraph Digraph;
372 373
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
373 374

	
374 375
  private:
375 376

	
376 377

	
377 378
    std::ostream* _os;
378 379
    bool local_os;
379 380

	
380 381
    const Digraph& _digraph;
381 382

	
382 383
    std::string _nodes_caption;
383 384
    std::string _arcs_caption;
384 385
    std::string _attributes_caption;
385 386

	
386 387
    typedef std::map<Node, std::string> NodeIndex;
387 388
    NodeIndex _node_index;
388 389
    typedef std::map<Arc, std::string> ArcIndex;
389 390
    ArcIndex _arc_index;
390 391

	
391 392
    typedef std::vector<std::pair<std::string,
392 393
      _writer_bits::MapStorageBase<Node>* > > NodeMaps;
393 394
    NodeMaps _node_maps;
394 395

	
395 396
    typedef std::vector<std::pair<std::string,
396 397
      _writer_bits::MapStorageBase<Arc>* > >ArcMaps;
397 398
    ArcMaps _arc_maps;
398 399

	
399 400
    typedef std::vector<std::pair<std::string,
400 401
      _writer_bits::ValueStorageBase*> > Attributes;
401 402
    Attributes _attributes;
402 403

	
403 404
    bool _skip_nodes;
404 405
    bool _skip_arcs;
405 406

	
406 407
  public:
407 408

	
408 409
    /// \brief Constructor
409 410
    ///
410 411
    /// Construct a directed graph writer, which writes to the given
411 412
    /// output stream.
412 413
    DigraphWriter(std::ostream& is, const Digraph& digraph)
413 414
      : _os(&is), local_os(false), _digraph(digraph),
414 415
        _skip_nodes(false), _skip_arcs(false) {}
415 416

	
416 417
    /// \brief Constructor
417 418
    ///
418 419
    /// Construct a directed graph writer, which writes to the given
419 420
    /// output file.
420 421
    DigraphWriter(const std::string& fn, const Digraph& digraph)
421 422
      : _os(new std::ofstream(fn.c_str())), local_os(true), _digraph(digraph),
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_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
#include <lemon/core.h>
27
#include <lemon/error.h>
26 28
#include <lemon/bits/graph_extender.h>
27 29

	
28 30
#include <vector>
29 31
#include <list>
30 32

	
31 33
namespace lemon {
32 34

	
33 35
  class ListDigraphBase {
34 36

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

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

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

	
49 51
    int first_node;
50 52

	
51 53
    int first_free_node;
52 54

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

	
55 57
    int first_free_arc;
56 58

	
57 59
  public:
58 60

	
59 61
    typedef ListDigraphBase Digraph;
60 62

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

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

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

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

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

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

	
91 93

	
92 94

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

	
97 99

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

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

	
104 106

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

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

	
113 115

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

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

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

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

	
148 150

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
234 236
    }
235 237

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

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

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

	
249 251

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

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

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

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

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

	
303 305
  };
304 306

	
305 307
  typedef DigraphExtender<ListDigraphBase> ExtendedListDigraphBase;
306 308

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

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

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

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

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

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

	
341 343
    typedef ExtendedListDigraphBase Parent;
342 344

	
343 345
    /// Constructor
344 346

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

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

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

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

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

	
364 366
    /// Node validity check
365 367

	
366 368
    /// This function gives back true if the given node is valid,
367 369
    /// ie. it is a real node of the graph.
368 370
    ///
369 371
    /// \warning A Node pointing to a removed item
370 372
    /// could become valid again later if new nodes are
371 373
    /// added to the graph.
372 374
    bool valid(Node n) const { return Parent::valid(n); }
373 375

	
374 376
    /// Arc validity check
375 377

	
376 378
    /// This function gives back true if the given arc is valid,
377 379
    /// ie. it is a real arc of the graph.
378 380
    ///
379 381
    /// \warning An Arc pointing to a removed item
380 382
    /// could become valid again later if new nodes are
381 383
    /// added to the graph.
382 384
    bool valid(Arc a) const { return Parent::valid(a); }
383 385

	
384 386
    /// Change the target of \c e to \c n
385 387

	
386 388
    /// Change the target of \c e to \c n
387 389
    ///
388 390
    ///\note The <tt>ArcIt</tt>s and <tt>OutArcIt</tt>s referencing
389 391
    ///the changed arc remain valid. However <tt>InArcIt</tt>s are
390 392
    ///invalidated.
391 393
    ///
392 394
    ///\warning This functionality cannot be used together with the Snapshot
393 395
    ///feature.
394 396
    void changeTarget(Arc e, Node n) {
395 397
      Parent::changeTarget(e,n);
396 398
    }
397 399
    /// Change the source of \c e to \c n
398 400

	
399 401
    /// Change the source of \c e to \c n
400 402
    ///
401 403
    ///\note The <tt>ArcIt</tt>s and <tt>InArcIt</tt>s referencing
402 404
    ///the changed arc remain valid. However <tt>OutArcIt</tt>s are
403 405
    ///invalidated.
404 406
    ///
405 407
    ///\warning This functionality cannot be used together with the Snapshot
406 408
    ///feature.
407 409
    void changeSource(Arc e, Node n) {
408 410
      Parent::changeSource(e,n);
409 411
    }
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_MAPS_H
20 20
#define LEMON_MAPS_H
21 21

	
22 22
#include <iterator>
23 23
#include <functional>
24 24
#include <vector>
25 25

	
26
#include <lemon/bits/utility.h>
27
#include <lemon/bits/traits.h>
26
#include <lemon/core.h>
28 27

	
29 28
///\file
30 29
///\ingroup maps
31 30
///\brief Miscellaneous property maps
32 31

	
33 32
#include <map>
34 33

	
35 34
namespace lemon {
36 35

	
37 36
  /// \addtogroup maps
38 37
  /// @{
39 38

	
40 39
  /// Base class of maps.
41 40

	
42 41
  /// Base class of maps. It provides the necessary type definitions
43 42
  /// required by the map %concepts.
44 43
  template<typename K, typename V>
45 44
  class MapBase {
46 45
  public:
47 46
    /// \biref The key type of the map.
48 47
    typedef K Key;
49 48
    /// \brief The value type of the map.
50 49
    /// (The type of objects associated with the keys).
51 50
    typedef V Value;
52 51
  };
53 52

	
54 53

	
55 54
  /// Null map. (a.k.a. DoNothingMap)
56 55

	
57 56
  /// This map can be used if you have to provide a map only for
58 57
  /// its type definitions, or if you have to provide a writable map,
59 58
  /// but data written to it is not required (i.e. it will be sent to
60 59
  /// <tt>/dev/null</tt>).
61 60
  /// It conforms the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
62 61
  ///
63 62
  /// \sa ConstMap
64 63
  template<typename K, typename V>
65 64
  class NullMap : public MapBase<K, V> {
66 65
  public:
67 66
    typedef MapBase<K, V> Parent;
68 67
    typedef typename Parent::Key Key;
69 68
    typedef typename Parent::Value Value;
70 69

	
71 70
    /// Gives back a default constructed element.
72 71
    Value operator[](const Key&) const { return Value(); }
73 72
    /// Absorbs the value.
74 73
    void set(const Key&, const Value&) {}
75 74
  };
76 75

	
77 76
  /// Returns a \ref NullMap class
78 77

	
79 78
  /// This function just returns a \ref NullMap class.
80 79
  /// \relates NullMap
81 80
  template <typename K, typename V>
82 81
  NullMap<K, V> nullMap() {
83 82
    return NullMap<K, V>();
84 83
  }
85 84

	
86 85

	
87 86
  /// Constant map.
88 87

	
89 88
  /// This \ref concepts::ReadMap "readable map" assigns a specified
90 89
  /// value to each key.
91 90
  ///
92 91
  /// In other aspects it is equivalent to \ref NullMap.
93 92
  /// So it conforms the \ref concepts::ReadWriteMap "ReadWriteMap"
94 93
  /// concept, but it absorbs the data written to it.
95 94
  ///
96 95
  /// The simplest way of using this map is through the constMap()
97 96
  /// function.
98 97
  ///
99 98
  /// \sa NullMap
100 99
  /// \sa IdentityMap
101 100
  template<typename K, typename V>
102 101
  class ConstMap : public MapBase<K, V> {
103 102
  private:
104 103
    V _value;
105 104
  public:
106 105
    typedef MapBase<K, V> Parent;
107 106
    typedef typename Parent::Key Key;
108 107
    typedef typename Parent::Value Value;
109 108

	
110 109
    /// Default constructor
111 110

	
112 111
    /// Default constructor.
113 112
    /// The value of the map will be default constructed.
114 113
    ConstMap() {}
115 114

	
116 115
    /// Constructor with specified initial value
117 116

	
118 117
    /// Constructor with specified initial value.
119 118
    /// \param v The initial value of the map.
120 119
    ConstMap(const Value &v) : _value(v) {}
121 120

	
122 121
    /// Gives back the specified value.
123 122
    Value operator[](const Key&) const { return _value; }
124 123

	
125 124
    /// Absorbs the value.
126 125
    void set(const Key&, const Value&) {}
127 126

	
128 127
    /// Sets the value that is assigned to each key.
129 128
    void setAll(const Value &v) {
130 129
      _value = v;
131 130
    }
132 131

	
133 132
    template<typename V1>
134 133
    ConstMap(const ConstMap<K, V1> &, const Value &v) : _value(v) {}
135 134
  };
136 135

	
137 136
  /// Returns a \ref ConstMap class
138 137

	
139 138
  /// This function just returns a \ref ConstMap class.
140 139
  /// \relates ConstMap
141 140
  template<typename K, typename V>
142 141
  inline ConstMap<K, V> constMap(const V &v) {
143 142
    return ConstMap<K, V>(v);
144 143
  }
145 144

	
146 145
  template<typename K, typename V>
147 146
  inline ConstMap<K, V> constMap() {
148 147
    return ConstMap<K, V>();
149 148
  }
150 149

	
151 150

	
152 151
  template<typename T, T v>
153 152
  struct Const {};
154 153

	
155 154
  /// Constant map with inlined constant value.
156 155

	
157 156
  /// This \ref concepts::ReadMap "readable map" assigns a specified
158 157
  /// value to each key.
159 158
  ///
160 159
  /// In other aspects it is equivalent to \ref NullMap.
161 160
  /// So it conforms the \ref concepts::ReadWriteMap "ReadWriteMap"
162 161
  /// concept, but it absorbs the data written to it.
163 162
  ///
164 163
  /// The simplest way of using this map is through the constMap()
165 164
  /// function.
166 165
  ///
167 166
  /// \sa NullMap
168 167
  /// \sa IdentityMap
169 168
  template<typename K, typename V, V v>
170 169
  class ConstMap<K, Const<V, v> > : public MapBase<K, V> {
171 170
  public:
172 171
    typedef MapBase<K, V> Parent;
173 172
    typedef typename Parent::Key Key;
174 173
    typedef typename Parent::Value Value;
175 174

	
176 175
    /// Constructor.
177 176
    ConstMap() {}
178 177

	
179 178
    /// Gives back the specified value.
180 179
    Value operator[](const Key&) const { return v; }
181 180

	
182 181
    /// Absorbs the value.
183 182
    void set(const Key&, const Value&) {}
184 183
  };
185 184

	
186 185
  /// Returns a \ref ConstMap class with inlined constant value
187 186

	
188 187
  /// This function just returns a \ref ConstMap class with inlined
189 188
  /// constant value.
190 189
  /// \relates ConstMap
191 190
  template<typename K, typename V, V v>
192 191
  inline ConstMap<K, Const<V, v> > constMap() {
193 192
    return ConstMap<K, Const<V, v> >();
194 193
  }
195 194

	
196 195

	
197 196
  /// Identity map.
198 197

	
199 198
  /// This \ref concepts::ReadMap "read-only map" gives back the given
200 199
  /// key as value without any modification.
201 200
  ///
202 201
  /// \sa ConstMap
203 202
  template <typename T>
204 203
  class IdentityMap : public MapBase<T, T> {
205 204
  public:
206 205
    typedef MapBase<T, T> Parent;
207 206
    typedef typename Parent::Key Key;
208 207
    typedef typename Parent::Value Value;
209 208

	
210 209
    /// Gives back the given value without any modification.
211 210
    Value operator[](const Key &k) const {
212 211
      return k;
213 212
    }
214 213
  };
215 214

	
216 215
  /// Returns an \ref IdentityMap class
217 216

	
218 217
  /// This function just returns an \ref IdentityMap class.
219 218
  /// \relates IdentityMap
220 219
  template<typename T>
221 220
  inline IdentityMap<T> identityMap() {
222 221
    return IdentityMap<T>();
223 222
  }
224 223

	
225 224

	
226 225
  /// \brief Map for storing values for integer keys from the range
227 226
  /// <tt>[0..size-1]</tt>.
228 227
  ///
229 228
  /// This map is essentially a wrapper for \c std::vector. It assigns
230 229
  /// values to integer keys from the range <tt>[0..size-1]</tt>.
231 230
  /// It can be used with some data structures, for example
232 231
  /// \ref UnionFind, \ref BinHeap, when the used items are small
233 232
  /// integers. This map conforms the \ref concepts::ReferenceMap
234 233
  /// "ReferenceMap" concept.
235 234
  ///
236 235
  /// The simplest way of using this map is through the rangeMap()
237 236
  /// function.
238 237
  template <typename V>
239 238
  class RangeMap : public MapBase<int, V> {
240 239
    template <typename V1>
241 240
    friend class RangeMap;
242 241
  private:
243 242

	
244 243
    typedef std::vector<V> Vector;
245 244
    Vector _vector;
246 245

	
247 246
  public:
248 247

	
249 248
    typedef MapBase<int, V> Parent;
250 249
    /// Key type
251 250
    typedef typename Parent::Key Key;
252 251
    /// Value type
253 252
    typedef typename Parent::Value Value;
254 253
    /// Reference type
255 254
    typedef typename Vector::reference Reference;
256 255
    /// Const reference type
257 256
    typedef typename Vector::const_reference ConstReference;
258 257

	
259 258
    typedef True ReferenceMapTag;
260 259

	
261 260
  public:
262 261

	
263 262
    /// Constructor with specified default value.
264 263
    RangeMap(int size = 0, const Value &value = Value())
265 264
      : _vector(size, value) {}
266 265

	
267 266
    /// Constructs the map from an appropriate \c std::vector.
268 267
    template <typename V1>
269 268
    RangeMap(const std::vector<V1>& vector)
270 269
      : _vector(vector.begin(), vector.end()) {}
271 270

	
272 271
    /// Constructs the map from another \ref RangeMap.
273 272
    template <typename V1>
274 273
    RangeMap(const RangeMap<V1> &c)
275 274
      : _vector(c._vector.begin(), c._vector.end()) {}
276 275

	
277 276
    /// Returns the size of the map.
278 277
    int size() {
279 278
      return _vector.size();
280 279
    }
281 280

	
282 281
    /// Resizes the map.
283 282

	
284 283
    /// Resizes the underlying \c std::vector container, so changes the
285 284
    /// keyset of the map.
286 285
    /// \param size The new size of the map. The new keyset will be the
287 286
    /// range <tt>[0..size-1]</tt>.
288 287
    /// \param value The default value to assign to the new keys.
289 288
    void resize(int size, const Value &value = Value()) {
290 289
      _vector.resize(size, value);
291 290
    }
292 291

	
293 292
  private:
294 293

	
295 294
    RangeMap& operator=(const RangeMap&);
296 295

	
297 296
  public:
298 297

	
299 298
    ///\e
300 299
    Reference operator[](const Key &k) {
301 300
      return _vector[k];
302 301
    }
303 302

	
304 303
    ///\e
305 304
    ConstReference operator[](const Key &k) const {
306 305
      return _vector[k];
307 306
    }
308 307

	
309 308
    ///\e
310 309
    void set(const Key &k, const Value &v) {
311 310
      _vector[k] = v;
312 311
    }
313 312
  };
314 313

	
315 314
  /// Returns a \ref RangeMap class
316 315

	
317 316
  /// This function just returns a \ref RangeMap class.
318 317
  /// \relates RangeMap
319 318
  template<typename V>
320 319
  inline RangeMap<V> rangeMap(int size = 0, const V &value = V()) {
321 320
    return RangeMap<V>(size, value);
322 321
  }
323 322

	
324 323
  /// \brief Returns a \ref RangeMap class created from an appropriate
325 324
  /// \c std::vector
326 325

	
327 326
  /// This function just returns a \ref RangeMap class created from an
328 327
  /// appropriate \c std::vector.
329 328
  /// \relates RangeMap
330 329
  template<typename V>
331 330
  inline RangeMap<V> rangeMap(const std::vector<V> &vector) {
332 331
    return RangeMap<V>(vector);
333 332
  }
334 333

	
335 334

	
336 335
  /// Map type based on \c std::map
337 336

	
338 337
  /// This map is essentially a wrapper for \c std::map with addition
339 338
  /// that you can specify a default value for the keys that are not
340 339
  /// stored actually. This value can be different from the default
341 340
  /// contructed value (i.e. \c %Value()).
342 341
  /// This type conforms the \ref concepts::ReferenceMap "ReferenceMap"
343 342
  /// concept.
344 343
  ///
345 344
  /// This map is useful if a default value should be assigned to most of
346 345
  /// the keys and different values should be assigned only to a few
347 346
  /// keys (i.e. the map is "sparse").
348 347
  /// The name of this type also refers to this important usage.
349 348
  ///
350 349
  /// Apart form that this map can be used in many other cases since it
351 350
  /// is based on \c std::map, which is a general associative container.
352 351
  /// However keep in mind that it is usually not as efficient as other
353 352
  /// maps.
354 353
  ///
355 354
  /// The simplest way of using this map is through the sparseMap()
356 355
  /// function.
357 356
  template <typename K, typename V, typename Compare = std::less<K> >
358 357
  class SparseMap : public MapBase<K, V> {
359 358
    template <typename K1, typename V1, typename C1>
360 359
    friend class SparseMap;
361 360
  public:
362 361

	
363 362
    typedef MapBase<K, V> Parent;
364 363
    /// Key type
365 364
    typedef typename Parent::Key Key;
366 365
    /// Value type
367 366
    typedef typename Parent::Value Value;
368 367
    /// Reference type
369 368
    typedef Value& Reference;
370 369
    /// Const reference type
371 370
    typedef const Value& ConstReference;
372 371

	
373 372
    typedef True ReferenceMapTag;
374 373

	
375 374
  private:
376 375

	
377 376
    typedef std::map<K, V, Compare> Map;
378 377
    Map _map;
379 378
    Value _value;
380 379

	
381 380
  public:
382 381

	
383 382
    /// \brief Constructor with specified default value.
384 383
    SparseMap(const Value &value = Value()) : _value(value) {}
385 384
    /// \brief Constructs the map from an appropriate \c std::map, and
386 385
    /// explicitly specifies a default value.
387 386
    template <typename V1, typename Comp1>
388 387
    SparseMap(const std::map<Key, V1, Comp1> &map,
389 388
              const Value &value = Value())
390 389
      : _map(map.begin(), map.end()), _value(value) {}
391 390

	
392 391
    /// \brief Constructs the map from another \ref SparseMap.
393 392
    template<typename V1, typename Comp1>
394 393
    SparseMap(const SparseMap<Key, V1, Comp1> &c)
395 394
      : _map(c._map.begin(), c._map.end()), _value(c._value) {}
396 395

	
397 396
  private:
398 397

	
399 398
    SparseMap& operator=(const SparseMap&);
400 399

	
401 400
  public:
402 401

	
403 402
    ///\e
404 403
    Reference operator[](const Key &k) {
405 404
      typename Map::iterator it = _map.lower_bound(k);
406 405
      if (it != _map.end() && !_map.key_comp()(k, it->first))
407 406
        return it->second;
408 407
      else
409 408
        return _map.insert(it, std::make_pair(k, _value))->second;
410 409
    }
411 410

	
... ...
@@ -1399,388 +1398,1308 @@
1399 1398
  /// @}
1400 1399

	
1401 1400
  /// \addtogroup map_adaptors
1402 1401
  /// @{
1403 1402

	
1404 1403
  /// Logical 'and' of two maps
1405 1404

	
1406 1405
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1407 1406
  /// 'and' of the values of the two given maps.
1408 1407
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1409 1408
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1410 1409
  ///
1411 1410
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1412 1411
  /// \code
1413 1412
  ///   AndMap<M1,M2> am(m1,m2);
1414 1413
  /// \endcode
1415 1414
  /// <tt>am[x]</tt> will be equal to <tt>m1[x]&&m2[x]</tt>.
1416 1415
  ///
1417 1416
  /// The simplest way of using this map is through the andMap()
1418 1417
  /// function.
1419 1418
  ///
1420 1419
  /// \sa OrMap
1421 1420
  /// \sa NotMap, NotWriteMap
1422 1421
  template<typename M1, typename M2>
1423 1422
  class AndMap : public MapBase<typename M1::Key, bool> {
1424 1423
    const M1 &_m1;
1425 1424
    const M2 &_m2;
1426 1425
  public:
1427 1426
    typedef MapBase<typename M1::Key, bool> Parent;
1428 1427
    typedef typename Parent::Key Key;
1429 1428
    typedef typename Parent::Value Value;
1430 1429

	
1431 1430
    /// Constructor
1432 1431
    AndMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1433 1432
    /// \e
1434 1433
    Value operator[](const Key &k) const { return _m1[k]&&_m2[k]; }
1435 1434
  };
1436 1435

	
1437 1436
  /// Returns an \ref AndMap class
1438 1437

	
1439 1438
  /// This function just returns an \ref AndMap class.
1440 1439
  ///
1441 1440
  /// For example, if \c m1 and \c m2 are both maps with \c bool values,
1442 1441
  /// then <tt>andMap(m1,m2)[x]</tt> will be equal to
1443 1442
  /// <tt>m1[x]&&m2[x]</tt>.
1444 1443
  ///
1445 1444
  /// \relates AndMap
1446 1445
  template<typename M1, typename M2>
1447 1446
  inline AndMap<M1, M2> andMap(const M1 &m1, const M2 &m2) {
1448 1447
    return AndMap<M1, M2>(m1,m2);
1449 1448
  }
1450 1449

	
1451 1450

	
1452 1451
  /// Logical 'or' of two maps
1453 1452

	
1454 1453
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1455 1454
  /// 'or' of the values of the two given maps.
1456 1455
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1457 1456
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1458 1457
  ///
1459 1458
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1460 1459
  /// \code
1461 1460
  ///   OrMap<M1,M2> om(m1,m2);
1462 1461
  /// \endcode
1463 1462
  /// <tt>om[x]</tt> will be equal to <tt>m1[x]||m2[x]</tt>.
1464 1463
  ///
1465 1464
  /// The simplest way of using this map is through the orMap()
1466 1465
  /// function.
1467 1466
  ///
1468 1467
  /// \sa AndMap
1469 1468
  /// \sa NotMap, NotWriteMap
1470 1469
  template<typename M1, typename M2>
1471 1470
  class OrMap : public MapBase<typename M1::Key, bool> {
1472 1471
    const M1 &_m1;
1473 1472
    const M2 &_m2;
1474 1473
  public:
1475 1474
    typedef MapBase<typename M1::Key, bool> Parent;
1476 1475
    typedef typename Parent::Key Key;
1477 1476
    typedef typename Parent::Value Value;
1478 1477

	
1479 1478
    /// Constructor
1480 1479
    OrMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1481 1480
    /// \e
1482 1481
    Value operator[](const Key &k) const { return _m1[k]||_m2[k]; }
1483 1482
  };
1484 1483

	
1485 1484
  /// Returns an \ref OrMap class
1486 1485

	
1487 1486
  /// This function just returns an \ref OrMap class.
1488 1487
  ///
1489 1488
  /// For example, if \c m1 and \c m2 are both maps with \c bool values,
1490 1489
  /// then <tt>orMap(m1,m2)[x]</tt> will be equal to
1491 1490
  /// <tt>m1[x]||m2[x]</tt>.
1492 1491
  ///
1493 1492
  /// \relates OrMap
1494 1493
  template<typename M1, typename M2>
1495 1494
  inline OrMap<M1, M2> orMap(const M1 &m1, const M2 &m2) {
1496 1495
    return OrMap<M1, M2>(m1,m2);
1497 1496
  }
1498 1497

	
1499 1498

	
1500 1499
  /// Logical 'not' of a map
1501 1500

	
1502 1501
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1503 1502
  /// negation of the values of the given map.
1504 1503
  /// Its \c Key is inherited from \c M and its \c Value is \c bool.
1505 1504
  ///
1506 1505
  /// The simplest way of using this map is through the notMap()
1507 1506
  /// function.
1508 1507
  ///
1509 1508
  /// \sa NotWriteMap
1510 1509
  template <typename M>
1511 1510
  class NotMap : public MapBase<typename M::Key, bool> {
1512 1511
    const M &_m;
1513 1512
  public:
1514 1513
    typedef MapBase<typename M::Key, bool> Parent;
1515 1514
    typedef typename Parent::Key Key;
1516 1515
    typedef typename Parent::Value Value;
1517 1516

	
1518 1517
    /// Constructor
1519 1518
    NotMap(const M &m) : _m(m) {}
1520 1519
    /// \e
1521 1520
    Value operator[](const Key &k) const { return !_m[k]; }
1522 1521
  };
1523 1522

	
1524 1523
  /// Logical 'not' of a map (read-write version)
1525 1524

	
1526 1525
  /// This \ref concepts::ReadWriteMap "read-write map" returns the
1527 1526
  /// logical negation of the values of the given map.
1528 1527
  /// Its \c Key is inherited from \c M and its \c Value is \c bool.
1529 1528
  /// It makes also possible to write the map. When a value is set,
1530 1529
  /// the opposite value is set to the original map.
1531 1530
  ///
1532 1531
  /// The simplest way of using this map is through the notWriteMap()
1533 1532
  /// function.
1534 1533
  ///
1535 1534
  /// \sa NotMap
1536 1535
  template <typename M>
1537 1536
  class NotWriteMap : public MapBase<typename M::Key, bool> {
1538 1537
    M &_m;
1539 1538
  public:
1540 1539
    typedef MapBase<typename M::Key, bool> Parent;
1541 1540
    typedef typename Parent::Key Key;
1542 1541
    typedef typename Parent::Value Value;
1543 1542

	
1544 1543
    /// Constructor
1545 1544
    NotWriteMap(M &m) : _m(m) {}
1546 1545
    /// \e
1547 1546
    Value operator[](const Key &k) const { return !_m[k]; }
1548 1547
    /// \e
1549 1548
    void set(const Key &k, bool v) { _m.set(k, !v); }
1550 1549
  };
1551 1550

	
1552 1551
  /// Returns a \ref NotMap class
1553 1552

	
1554 1553
  /// This function just returns a \ref NotMap class.
1555 1554
  ///
1556 1555
  /// For example, if \c m is a map with \c bool values, then
1557 1556
  /// <tt>notMap(m)[x]</tt> will be equal to <tt>!m[x]</tt>.
1558 1557
  ///
1559 1558
  /// \relates NotMap
1560 1559
  template <typename M>
1561 1560
  inline NotMap<M> notMap(const M &m) {
1562 1561
    return NotMap<M>(m);
1563 1562
  }
1564 1563

	
1565 1564
  /// Returns a \ref NotWriteMap class
1566 1565

	
1567 1566
  /// This function just returns a \ref NotWriteMap class.
1568 1567
  ///
1569 1568
  /// For example, if \c m is a map with \c bool values, then
1570 1569
  /// <tt>notWriteMap(m)[x]</tt> will be equal to <tt>!m[x]</tt>.
1571 1570
  /// Moreover it makes also possible to write the map.
1572 1571
  ///
1573 1572
  /// \relates NotWriteMap
1574 1573
  template <typename M>
1575 1574
  inline NotWriteMap<M> notWriteMap(M &m) {
1576 1575
    return NotWriteMap<M>(m);
1577 1576
  }
1578 1577

	
1579 1578

	
1580 1579
  /// Combination of two maps using the \c == operator
1581 1580

	
1582 1581
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1583 1582
  /// the keys for which the corresponding values of the two maps are
1584 1583
  /// equal.
1585 1584
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1586 1585
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1587 1586
  ///
1588 1587
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1589 1588
  /// \code
1590 1589
  ///   EqualMap<M1,M2> em(m1,m2);
1591 1590
  /// \endcode
1592 1591
  /// <tt>em[x]</tt> will be equal to <tt>m1[x]==m2[x]</tt>.
1593 1592
  ///
1594 1593
  /// The simplest way of using this map is through the equalMap()
1595 1594
  /// function.
1596 1595
  ///
1597 1596
  /// \sa LessMap
1598 1597
  template<typename M1, typename M2>
1599 1598
  class EqualMap : public MapBase<typename M1::Key, bool> {
1600 1599
    const M1 &_m1;
1601 1600
    const M2 &_m2;
1602 1601
  public:
1603 1602
    typedef MapBase<typename M1::Key, bool> Parent;
1604 1603
    typedef typename Parent::Key Key;
1605 1604
    typedef typename Parent::Value Value;
1606 1605

	
1607 1606
    /// Constructor
1608 1607
    EqualMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1609 1608
    /// \e
1610 1609
    Value operator[](const Key &k) const { return _m1[k]==_m2[k]; }
1611 1610
  };
1612 1611

	
1613 1612
  /// Returns an \ref EqualMap class
1614 1613

	
1615 1614
  /// This function just returns an \ref EqualMap class.
1616 1615
  ///
1617 1616
  /// For example, if \c m1 and \c m2 are maps with keys and values of
1618 1617
  /// the same type, then <tt>equalMap(m1,m2)[x]</tt> will be equal to
1619 1618
  /// <tt>m1[x]==m2[x]</tt>.
1620 1619
  ///
1621 1620
  /// \relates EqualMap
1622 1621
  template<typename M1, typename M2>
1623 1622
  inline EqualMap<M1, M2> equalMap(const M1 &m1, const M2 &m2) {
1624 1623
    return EqualMap<M1, M2>(m1,m2);
1625 1624
  }
1626 1625

	
1627 1626

	
1628 1627
  /// Combination of two maps using the \c < operator
1629 1628

	
1630 1629
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1631 1630
  /// the keys for which the corresponding value of the first map is
1632 1631
  /// less then the value of the second map.
1633 1632
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1634 1633
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1635 1634
  ///
1636 1635
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1637 1636
  /// \code
1638 1637
  ///   LessMap<M1,M2> lm(m1,m2);
1639 1638
  /// \endcode
1640 1639
  /// <tt>lm[x]</tt> will be equal to <tt>m1[x]<m2[x]</tt>.
1641 1640
  ///
1642 1641
  /// The simplest way of using this map is through the lessMap()
1643 1642
  /// function.
1644 1643
  ///
1645 1644
  /// \sa EqualMap
1646 1645
  template<typename M1, typename M2>
1647 1646
  class LessMap : public MapBase<typename M1::Key, bool> {
1648 1647
    const M1 &_m1;
1649 1648
    const M2 &_m2;
1650 1649
  public:
1651 1650
    typedef MapBase<typename M1::Key, bool> Parent;
1652 1651
    typedef typename Parent::Key Key;
1653 1652
    typedef typename Parent::Value Value;
1654 1653

	
1655 1654
    /// Constructor
1656 1655
    LessMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1657 1656
    /// \e
1658 1657
    Value operator[](const Key &k) const { return _m1[k]<_m2[k]; }
1659 1658
  };
1660 1659

	
1661 1660
  /// Returns an \ref LessMap class
1662 1661

	
1663 1662
  /// This function just returns an \ref LessMap class.
1664 1663
  ///
1665 1664
  /// For example, if \c m1 and \c m2 are maps with keys and values of
1666 1665
  /// the same type, then <tt>lessMap(m1,m2)[x]</tt> will be equal to
1667 1666
  /// <tt>m1[x]<m2[x]</tt>.
1668 1667
  ///
1669 1668
  /// \relates LessMap
1670 1669
  template<typename M1, typename M2>
1671 1670
  inline LessMap<M1, M2> lessMap(const M1 &m1, const M2 &m2) {
1672 1671
    return LessMap<M1, M2>(m1,m2);
1673 1672
  }
1674 1673

	
1675 1674
  namespace _maps_bits {
1676 1675

	
1677 1676
    template <typename _Iterator, typename Enable = void>
1678 1677
    struct IteratorTraits {
1679 1678
      typedef typename std::iterator_traits<_Iterator>::value_type Value;
1680 1679
    };
1681 1680

	
1682 1681
    template <typename _Iterator>
1683 1682
    struct IteratorTraits<_Iterator,
1684 1683
      typename exists<typename _Iterator::container_type>::type>
1685 1684
    {
1686 1685
      typedef typename _Iterator::container_type::value_type Value;
1687 1686
    };
1688 1687

	
1689 1688
  }
1690 1689

	
1691 1690
  /// \brief Writable bool map for logging each \c true assigned element
1692 1691
  ///
1693 1692
  /// A \ref concepts::WriteMap "writable" bool map for logging
1694 1693
  /// each \c true assigned element, i.e it copies subsequently each
1695 1694
  /// keys set to \c true to the given iterator.
1696 1695
  /// The most important usage of it is storing certain nodes or arcs
1697 1696
  /// that were marked \c true by an algorithm.
1698 1697
  ///
1699 1698
  /// There are several algorithms that provide solutions through bool
1700 1699
  /// maps and most of them assign \c true at most once for each key.
1701 1700
  /// In these cases it is a natural request to store each \c true
1702 1701
  /// assigned elements (in order of the assignment), which can be
1703 1702
  /// easily done with LoggerBoolMap.
1704 1703
  ///
1705 1704
  /// The simplest way of using this map is through the loggerBoolMap()
1706 1705
  /// function.
1707 1706
  ///
1708 1707
  /// \tparam It The type of the iterator.
1709 1708
  /// \tparam Ke The key type of the map. The default value set
1710 1709
  /// according to the iterator type should work in most cases.
1711 1710
  ///
1712 1711
  /// \note The container of the iterator must contain enough space
1713 1712
  /// for the elements or the iterator should be an inserter iterator.
1714 1713
#ifdef DOXYGEN
1715 1714
  template <typename It, typename Ke>
1716 1715
#else
1717 1716
  template <typename It,
1718 1717
            typename Ke=typename _maps_bits::IteratorTraits<It>::Value>
1719 1718
#endif
1720 1719
  class LoggerBoolMap {
1721 1720
  public:
1722 1721
    typedef It Iterator;
1723 1722

	
1724 1723
    typedef Ke Key;
1725 1724
    typedef bool Value;
1726 1725

	
1727 1726
    /// Constructor
1728 1727
    LoggerBoolMap(Iterator it)
1729 1728
      : _begin(it), _end(it) {}
1730 1729

	
1731 1730
    /// Gives back the given iterator set for the first key
1732 1731
    Iterator begin() const {
1733 1732
      return _begin;
1734 1733
    }
1735 1734

	
1736 1735
    /// Gives back the the 'after the last' iterator
1737 1736
    Iterator end() const {
1738 1737
      return _end;
1739 1738
    }
1740 1739

	
1741 1740
    /// The set function of the map
1742 1741
    void set(const Key& key, Value value) {
1743 1742
      if (value) {
1744 1743
        *_end++ = key;
1745 1744
      }
1746 1745
    }
1747 1746

	
1748 1747
  private:
1749 1748
    Iterator _begin;
1750 1749
    Iterator _end;
1751 1750
  };
1752 1751

	
1753 1752
  /// Returns a \ref LoggerBoolMap class
1754 1753

	
1755 1754
  /// This function just returns a \ref LoggerBoolMap class.
1756 1755
  ///
1757 1756
  /// The most important usage of it is storing certain nodes or arcs
1758 1757
  /// that were marked \c true by an algorithm.
1759 1758
  /// For example it makes easier to store the nodes in the processing
1760 1759
  /// order of Dfs algorithm, as the following examples show.
1761 1760
  /// \code
1762 1761
  ///   std::vector<Node> v;
1763 1762
  ///   dfs(g,s).processedMap(loggerBoolMap(std::back_inserter(v))).run();
1764 1763
  /// \endcode
1765 1764
  /// \code
1766 1765
  ///   std::vector<Node> v(countNodes(g));
1767 1766
  ///   dfs(g,s).processedMap(loggerBoolMap(v.begin())).run();
1768 1767
  /// \endcode
1769 1768
  ///
1770 1769
  /// \note The container of the iterator must contain enough space
1771 1770
  /// for the elements or the iterator should be an inserter iterator.
1772 1771
  ///
1773 1772
  /// \note LoggerBoolMap is just \ref concepts::WriteMap "writable", so
1774 1773
  /// it cannot be used when a readable map is needed, for example as
1775 1774
  /// \c ReachedMap for \ref Bfs, \ref Dfs and \ref Dijkstra algorithms.
1776 1775
  ///
1777 1776
  /// \relates LoggerBoolMap
1778 1777
  template<typename Iterator>
1779 1778
  inline LoggerBoolMap<Iterator> loggerBoolMap(Iterator it) {
1780 1779
    return LoggerBoolMap<Iterator>(it);
1781 1780
  }
1782 1781

	
1782
  /// Provides an immutable and unique id for each item in the graph.
1783

	
1784
  /// The IdMap class provides a unique and immutable id for each item of the
1785
  /// same type (e.g. node) in the graph. This id is <ul><li>\b unique:
1786
  /// different items (nodes) get different ids <li>\b immutable: the id of an
1787
  /// item (node) does not change (even if you delete other nodes).  </ul>
1788
  /// Through this map you get access (i.e. can read) the inner id values of
1789
  /// the items stored in the graph. This map can be inverted with its member
1790
  /// class \c InverseMap or with the \c operator() member.
1791
  ///
1792
  template <typename _Graph, typename _Item>
1793
  class IdMap {
1794
  public:
1795
    typedef _Graph Graph;
1796
    typedef int Value;
1797
    typedef _Item Item;
1798
    typedef _Item Key;
1799

	
1800
    /// \brief Constructor.
1801
    ///
1802
    /// Constructor of the map.
1803
    explicit IdMap(const Graph& graph) : _graph(&graph) {}
1804

	
1805
    /// \brief Gives back the \e id of the item.
1806
    ///
1807
    /// Gives back the immutable and unique \e id of the item.
1808
    int operator[](const Item& item) const { return _graph->id(item);}
1809

	
1810
    /// \brief Gives back the item by its id.
1811
    ///
1812
    /// Gives back the item by its id.
1813
    Item operator()(int id) { return _graph->fromId(id, Item()); }
1814

	
1815
  private:
1816
    const Graph* _graph;
1817

	
1818
  public:
1819

	
1820
    /// \brief The class represents the inverse of its owner (IdMap).
1821
    ///
1822
    /// The class represents the inverse of its owner (IdMap).
1823
    /// \see inverse()
1824
    class InverseMap {
1825
    public:
1826

	
1827
      /// \brief Constructor.
1828
      ///
1829
      /// Constructor for creating an id-to-item map.
1830
      explicit InverseMap(const Graph& graph) : _graph(&graph) {}
1831

	
1832
      /// \brief Constructor.
1833
      ///
1834
      /// Constructor for creating an id-to-item map.
1835
      explicit InverseMap(const IdMap& map) : _graph(map._graph) {}
1836

	
1837
      /// \brief Gives back the given item from its id.
1838
      ///
1839
      /// Gives back the given item from its id.
1840
      ///
1841
      Item operator[](int id) const { return _graph->fromId(id, Item());}
1842

	
1843
    private:
1844
      const Graph* _graph;
1845
    };
1846

	
1847
    /// \brief Gives back the inverse of the map.
1848
    ///
1849
    /// Gives back the inverse of the IdMap.
1850
    InverseMap inverse() const { return InverseMap(*_graph);}
1851

	
1852
  };
1853

	
1854

	
1855
  /// \brief General invertable graph-map type.
1856

	
1857
  /// This type provides simple invertable graph-maps.
1858
  /// The InvertableMap wraps an arbitrary ReadWriteMap
1859
  /// and if a key is set to a new value then store it
1860
  /// in the inverse map.
1861
  ///
1862
  /// The values of the map can be accessed
1863
  /// with stl compatible forward iterator.
1864
  ///
1865
  /// \tparam _Graph The graph type.
1866
  /// \tparam _Item The item type of the graph.
1867
  /// \tparam _Value The value type of the map.
1868
  ///
1869
  /// \see IterableValueMap
1870
  template <typename _Graph, typename _Item, typename _Value>
1871
  class InvertableMap
1872
    : protected ItemSetTraits<_Graph, _Item>::template Map<_Value>::Type {
1873
  private:
1874

	
1875
    typedef typename ItemSetTraits<_Graph, _Item>::
1876
    template Map<_Value>::Type Map;
1877
    typedef _Graph Graph;
1878

	
1879
    typedef std::map<_Value, _Item> Container;
1880
    Container _inv_map;
1881

	
1882
  public:
1883

	
1884
    /// The key type of InvertableMap (Node, Arc, Edge).
1885
    typedef typename Map::Key Key;
1886
    /// The value type of the InvertableMap.
1887
    typedef typename Map::Value Value;
1888

	
1889

	
1890

	
1891
    /// \brief Constructor.
1892
    ///
1893
    /// Construct a new InvertableMap for the graph.
1894
    ///
1895
    explicit InvertableMap(const Graph& graph) : Map(graph) {}
1896

	
1897
    /// \brief Forward iterator for values.
1898
    ///
1899
    /// This iterator is an stl compatible forward
1900
    /// iterator on the values of the map. The values can
1901
    /// be accessed in the [beginValue, endValue) range.
1902
    ///
1903
    class ValueIterator
1904
      : public std::iterator<std::forward_iterator_tag, Value> {
1905
      friend class InvertableMap;
1906
    private:
1907
      ValueIterator(typename Container::const_iterator _it)
1908
        : it(_it) {}
1909
    public:
1910

	
1911
      ValueIterator() {}
1912

	
1913
      ValueIterator& operator++() { ++it; return *this; }
1914
      ValueIterator operator++(int) {
1915
        ValueIterator tmp(*this);
1916
        operator++();
1917
        return tmp;
1918
      }
1919

	
1920
      const Value& operator*() const { return it->first; }
1921
      const Value* operator->() const { return &(it->first); }
1922

	
1923
      bool operator==(ValueIterator jt) const { return it == jt.it; }
1924
      bool operator!=(ValueIterator jt) const { return it != jt.it; }
1925

	
1926
    private:
1927
      typename Container::const_iterator it;
1928
    };
1929

	
1930
    /// \brief Returns an iterator to the first value.
1931
    ///
1932
    /// Returns an stl compatible iterator to the
1933
    /// first value of the map. The values of the
1934
    /// map can be accessed in the [beginValue, endValue)
1935
    /// range.
1936
    ValueIterator beginValue() const {
1937
      return ValueIterator(_inv_map.begin());
1938
    }
1939

	
1940
    /// \brief Returns an iterator after the last value.
1941
    ///
1942
    /// Returns an stl compatible iterator after the
1943
    /// last value of the map. The values of the
1944
    /// map can be accessed in the [beginValue, endValue)
1945
    /// range.
1946
    ValueIterator endValue() const {
1947
      return ValueIterator(_inv_map.end());
1948
    }
1949

	
1950
    /// \brief The setter function of the map.
1951
    ///
1952
    /// Sets the mapped value.
1953
    void set(const Key& key, const Value& val) {
1954
      Value oldval = Map::operator[](key);
1955
      typename Container::iterator it = _inv_map.find(oldval);
1956
      if (it != _inv_map.end() && it->second == key) {
1957
        _inv_map.erase(it);
1958
      }
1959
      _inv_map.insert(make_pair(val, key));
1960
      Map::set(key, val);
1961
    }
1962

	
1963
    /// \brief The getter function of the map.
1964
    ///
1965
    /// It gives back the value associated with the key.
1966
    typename MapTraits<Map>::ConstReturnValue
1967
    operator[](const Key& key) const {
1968
      return Map::operator[](key);
1969
    }
1970

	
1971
    /// \brief Gives back the item by its value.
1972
    ///
1973
    /// Gives back the item by its value.
1974
    Key operator()(const Value& key) const {
1975
      typename Container::const_iterator it = _inv_map.find(key);
1976
      return it != _inv_map.end() ? it->second : INVALID;
1977
    }
1978

	
1979
  protected:
1980

	
1981
    /// \brief Erase the key from the map.
1982
    ///
1983
    /// Erase the key to the map. It is called by the
1984
    /// \c AlterationNotifier.
1985
    virtual void erase(const Key& key) {
1986
      Value val = Map::operator[](key);
1987
      typename Container::iterator it = _inv_map.find(val);
1988
      if (it != _inv_map.end() && it->second == key) {
1989
        _inv_map.erase(it);
1990
      }
1991
      Map::erase(key);
1992
    }
1993

	
1994
    /// \brief Erase more keys from the map.
1995
    ///
1996
    /// Erase more keys from the map. It is called by the
1997
    /// \c AlterationNotifier.
1998
    virtual void erase(const std::vector<Key>& keys) {
1999
      for (int i = 0; i < int(keys.size()); ++i) {
2000
        Value val = Map::operator[](keys[i]);
2001
        typename Container::iterator it = _inv_map.find(val);
2002
        if (it != _inv_map.end() && it->second == keys[i]) {
2003
          _inv_map.erase(it);
2004
        }
2005
      }
2006
      Map::erase(keys);
2007
    }
2008

	
2009
    /// \brief Clear the keys from the map and inverse map.
2010
    ///
2011
    /// Clear the keys from the map and inverse map. It is called by the
2012
    /// \c AlterationNotifier.
2013
    virtual void clear() {
2014
      _inv_map.clear();
2015
      Map::clear();
2016
    }
2017

	
2018
  public:
2019

	
2020
    /// \brief The inverse map type.
2021
    ///
2022
    /// The inverse of this map. The subscript operator of the map
2023
    /// gives back always the item what was last assigned to the value.
2024
    class InverseMap {
2025
    public:
2026
      /// \brief Constructor of the InverseMap.
2027
      ///
2028
      /// Constructor of the InverseMap.
2029
      explicit InverseMap(const InvertableMap& inverted)
2030
        : _inverted(inverted) {}
2031

	
2032
      /// The value type of the InverseMap.
2033
      typedef typename InvertableMap::Key Value;
2034
      /// The key type of the InverseMap.
2035
      typedef typename InvertableMap::Value Key;
2036

	
2037
      /// \brief Subscript operator.
2038
      ///
2039
      /// Subscript operator. It gives back always the item
2040
      /// what was last assigned to the value.
2041
      Value operator[](const Key& key) const {
2042
        return _inverted(key);
2043
      }
2044

	
2045
    private:
2046
      const InvertableMap& _inverted;
2047
    };
2048

	
2049
    /// \brief It gives back the just readable inverse map.
2050
    ///
2051
    /// It gives back the just readable inverse map.
2052
    InverseMap inverse() const {
2053
      return InverseMap(*this);
2054
    }
2055

	
2056

	
2057

	
2058
  };
2059

	
2060
  /// \brief Provides a mutable, continuous and unique descriptor for each
2061
  /// item in the graph.
2062
  ///
2063
  /// The DescriptorMap class provides a unique and continuous (but mutable)
2064
  /// descriptor (id) for each item of the same type (e.g. node) in the
2065
  /// graph. This id is <ul><li>\b unique: different items (nodes) get
2066
  /// different ids <li>\b continuous: the range of the ids is the set of
2067
  /// integers between 0 and \c n-1, where \c n is the number of the items of
2068
  /// this type (e.g. nodes) (so the id of a node can change if you delete an
2069
  /// other node, i.e. this id is mutable).  </ul> This map can be inverted
2070
  /// with its member class \c InverseMap, or with the \c operator() member.
2071
  ///
2072
  /// \tparam _Graph The graph class the \c DescriptorMap belongs to.
2073
  /// \tparam _Item The Item is the Key of the Map. It may be Node, Arc or
2074
  /// Edge.
2075
  template <typename _Graph, typename _Item>
2076
  class DescriptorMap
2077
    : protected ItemSetTraits<_Graph, _Item>::template Map<int>::Type {
2078

	
2079
    typedef _Item Item;
2080
    typedef typename ItemSetTraits<_Graph, _Item>::template Map<int>::Type Map;
2081

	
2082
  public:
2083
    /// The graph class of DescriptorMap.
2084
    typedef _Graph Graph;
2085

	
2086
    /// The key type of DescriptorMap (Node, Arc, Edge).
2087
    typedef typename Map::Key Key;
2088
    /// The value type of DescriptorMap.
2089
    typedef typename Map::Value Value;
2090

	
2091
    /// \brief Constructor.
2092
    ///
2093
    /// Constructor for descriptor map.
2094
    explicit DescriptorMap(const Graph& _graph) : Map(_graph) {
2095
      Item it;
2096
      const typename Map::Notifier* nf = Map::notifier();
2097
      for (nf->first(it); it != INVALID; nf->next(it)) {
2098
        Map::set(it, _inv_map.size());
2099
        _inv_map.push_back(it);
2100
      }
2101
    }
2102

	
2103
  protected:
2104

	
2105
    /// \brief Add a new key to the map.
2106
    ///
2107
    /// Add a new key to the map. It is called by the
2108
    /// \c AlterationNotifier.
2109
    virtual void add(const Item& item) {
2110
      Map::add(item);
2111
      Map::set(item, _inv_map.size());
2112
      _inv_map.push_back(item);
2113
    }
2114

	
2115
    /// \brief Add more new keys to the map.
2116
    ///
2117
    /// Add more new keys to the map. It is called by the
2118
    /// \c AlterationNotifier.
2119
    virtual void add(const std::vector<Item>& items) {
2120
      Map::add(items);
2121
      for (int i = 0; i < int(items.size()); ++i) {
2122
        Map::set(items[i], _inv_map.size());
2123
        _inv_map.push_back(items[i]);
2124
      }
2125
    }
2126

	
2127
    /// \brief Erase the key from the map.
2128
    ///
2129
    /// Erase the key from the map. It is called by the
2130
    /// \c AlterationNotifier.
2131
    virtual void erase(const Item& item) {
2132
      Map::set(_inv_map.back(), Map::operator[](item));
2133
      _inv_map[Map::operator[](item)] = _inv_map.back();
2134
      _inv_map.pop_back();
2135
      Map::erase(item);
2136
    }
2137

	
2138
    /// \brief Erase more keys from the map.
2139
    ///
2140
    /// Erase more keys from the map. It is called by the
2141
    /// \c AlterationNotifier.
2142
    virtual void erase(const std::vector<Item>& items) {
2143
      for (int i = 0; i < int(items.size()); ++i) {
2144
        Map::set(_inv_map.back(), Map::operator[](items[i]));
2145
        _inv_map[Map::operator[](items[i])] = _inv_map.back();
2146
        _inv_map.pop_back();
2147
      }
2148
      Map::erase(items);
2149
    }
2150

	
2151
    /// \brief Build the unique map.
2152
    ///
2153
    /// Build the unique map. It is called by the
2154
    /// \c AlterationNotifier.
2155
    virtual void build() {
2156
      Map::build();
2157
      Item it;
2158
      const typename Map::Notifier* nf = Map::notifier();
2159
      for (nf->first(it); it != INVALID; nf->next(it)) {
2160
        Map::set(it, _inv_map.size());
2161
        _inv_map.push_back(it);
2162
      }
2163
    }
2164

	
2165
    /// \brief Clear the keys from the map.
2166
    ///
2167
    /// Clear the keys from the map. It is called by the
2168
    /// \c AlterationNotifier.
2169
    virtual void clear() {
2170
      _inv_map.clear();
2171
      Map::clear();
2172
    }
2173

	
2174
  public:
2175

	
2176
    /// \brief Returns the maximal value plus one.
2177
    ///
2178
    /// Returns the maximal value plus one in the map.
2179
    unsigned int size() const {
2180
      return _inv_map.size();
2181
    }
2182

	
2183
    /// \brief Swaps the position of the two items in the map.
2184
    ///
2185
    /// Swaps the position of the two items in the map.
2186
    void swap(const Item& p, const Item& q) {
2187
      int pi = Map::operator[](p);
2188
      int qi = Map::operator[](q);
2189
      Map::set(p, qi);
2190
      _inv_map[qi] = p;
2191
      Map::set(q, pi);
2192
      _inv_map[pi] = q;
2193
    }
2194

	
2195
    /// \brief Gives back the \e descriptor of the item.
2196
    ///
2197
    /// Gives back the mutable and unique \e descriptor of the map.
2198
    int operator[](const Item& item) const {
2199
      return Map::operator[](item);
2200
    }
2201

	
2202
    /// \brief Gives back the item by its descriptor.
2203
    ///
2204
    /// Gives back th item by its descriptor.
2205
    Item operator()(int id) const {
2206
      return _inv_map[id];
2207
    }
2208

	
2209
  private:
2210

	
2211
    typedef std::vector<Item> Container;
2212
    Container _inv_map;
2213

	
2214
  public:
2215
    /// \brief The inverse map type of DescriptorMap.
2216
    ///
2217
    /// The inverse map type of DescriptorMap.
2218
    class InverseMap {
2219
    public:
2220
      /// \brief Constructor of the InverseMap.
2221
      ///
2222
      /// Constructor of the InverseMap.
2223
      explicit InverseMap(const DescriptorMap& inverted)
2224
        : _inverted(inverted) {}
2225

	
2226

	
2227
      /// The value type of the InverseMap.
2228
      typedef typename DescriptorMap::Key Value;
2229
      /// The key type of the InverseMap.
2230
      typedef typename DescriptorMap::Value Key;
2231

	
2232
      /// \brief Subscript operator.
2233
      ///
2234
      /// Subscript operator. It gives back the item
2235
      /// that the descriptor belongs to currently.
2236
      Value operator[](const Key& key) const {
2237
        return _inverted(key);
2238
      }
2239

	
2240
      /// \brief Size of the map.
2241
      ///
2242
      /// Returns the size of the map.
2243
      unsigned int size() const {
2244
        return _inverted.size();
2245
      }
2246

	
2247
    private:
2248
      const DescriptorMap& _inverted;
2249
    };
2250

	
2251
    /// \brief Gives back the inverse of the map.
2252
    ///
2253
    /// Gives back the inverse of the map.
2254
    const InverseMap inverse() const {
2255
      return InverseMap(*this);
2256
    }
2257
  };
2258

	
2259
  /// \brief Returns the source of the given arc.
2260
  ///
2261
  /// The SourceMap gives back the source Node of the given arc.
2262
  /// \see TargetMap
2263
  template <typename Digraph>
2264
  class SourceMap {
2265
  public:
2266

	
2267
    typedef typename Digraph::Node Value;
2268
    typedef typename Digraph::Arc Key;
2269

	
2270
    /// \brief Constructor
2271
    ///
2272
    /// Constructor
2273
    /// \param _digraph The digraph that the map belongs to.
2274
    explicit SourceMap(const Digraph& digraph) : _digraph(digraph) {}
2275

	
2276
    /// \brief The subscript operator.
2277
    ///
2278
    /// The subscript operator.
2279
    /// \param arc The arc
2280
    /// \return The source of the arc
2281
    Value operator[](const Key& arc) const {
2282
      return _digraph.source(arc);
2283
    }
2284

	
2285
  private:
2286
    const Digraph& _digraph;
2287
  };
2288

	
2289
  /// \brief Returns a \ref SourceMap class.
2290
  ///
2291
  /// This function just returns an \ref SourceMap class.
2292
  /// \relates SourceMap
2293
  template <typename Digraph>
2294
  inline SourceMap<Digraph> sourceMap(const Digraph& digraph) {
2295
    return SourceMap<Digraph>(digraph);
2296
  }
2297

	
2298
  /// \brief Returns the target of the given arc.
2299
  ///
2300
  /// The TargetMap gives back the target Node of the given arc.
2301
  /// \see SourceMap
2302
  template <typename Digraph>
2303
  class TargetMap {
2304
  public:
2305

	
2306
    typedef typename Digraph::Node Value;
2307
    typedef typename Digraph::Arc Key;
2308

	
2309
    /// \brief Constructor
2310
    ///
2311
    /// Constructor
2312
    /// \param _digraph The digraph that the map belongs to.
2313
    explicit TargetMap(const Digraph& digraph) : _digraph(digraph) {}
2314

	
2315
    /// \brief The subscript operator.
2316
    ///
2317
    /// The subscript operator.
2318
    /// \param e The arc
2319
    /// \return The target of the arc
2320
    Value operator[](const Key& e) const {
2321
      return _digraph.target(e);
2322
    }
2323

	
2324
  private:
2325
    const Digraph& _digraph;
2326
  };
2327

	
2328
  /// \brief Returns a \ref TargetMap class.
2329
  ///
2330
  /// This function just returns a \ref TargetMap class.
2331
  /// \relates TargetMap
2332
  template <typename Digraph>
2333
  inline TargetMap<Digraph> targetMap(const Digraph& digraph) {
2334
    return TargetMap<Digraph>(digraph);
2335
  }
2336

	
2337
  /// \brief Returns the "forward" directed arc view of an edge.
2338
  ///
2339
  /// Returns the "forward" directed arc view of an edge.
2340
  /// \see BackwardMap
2341
  template <typename Graph>
2342
  class ForwardMap {
2343
  public:
2344

	
2345
    typedef typename Graph::Arc Value;
2346
    typedef typename Graph::Edge Key;
2347

	
2348
    /// \brief Constructor
2349
    ///
2350
    /// Constructor
2351
    /// \param _graph The graph that the map belongs to.
2352
    explicit ForwardMap(const Graph& graph) : _graph(graph) {}
2353

	
2354
    /// \brief The subscript operator.
2355
    ///
2356
    /// The subscript operator.
2357
    /// \param key An edge
2358
    /// \return The "forward" directed arc view of edge
2359
    Value operator[](const Key& key) const {
2360
      return _graph.direct(key, true);
2361
    }
2362

	
2363
  private:
2364
    const Graph& _graph;
2365
  };
2366

	
2367
  /// \brief Returns a \ref ForwardMap class.
2368
  ///
2369
  /// This function just returns an \ref ForwardMap class.
2370
  /// \relates ForwardMap
2371
  template <typename Graph>
2372
  inline ForwardMap<Graph> forwardMap(const Graph& graph) {
2373
    return ForwardMap<Graph>(graph);
2374
  }
2375

	
2376
  /// \brief Returns the "backward" directed arc view of an edge.
2377
  ///
2378
  /// Returns the "backward" directed arc view of an edge.
2379
  /// \see ForwardMap
2380
  template <typename Graph>
2381
  class BackwardMap {
2382
  public:
2383

	
2384
    typedef typename Graph::Arc Value;
2385
    typedef typename Graph::Edge Key;
2386

	
2387
    /// \brief Constructor
2388
    ///
2389
    /// Constructor
2390
    /// \param _graph The graph that the map belongs to.
2391
    explicit BackwardMap(const Graph& graph) : _graph(graph) {}
2392

	
2393
    /// \brief The subscript operator.
2394
    ///
2395
    /// The subscript operator.
2396
    /// \param key An edge
2397
    /// \return The "backward" directed arc view of edge
2398
    Value operator[](const Key& key) const {
2399
      return _graph.direct(key, false);
2400
    }
2401

	
2402
  private:
2403
    const Graph& _graph;
2404
  };
2405

	
2406
  /// \brief Returns a \ref BackwardMap class
2407

	
2408
  /// This function just returns a \ref BackwardMap class.
2409
  /// \relates BackwardMap
2410
  template <typename Graph>
2411
  inline BackwardMap<Graph> backwardMap(const Graph& graph) {
2412
    return BackwardMap<Graph>(graph);
2413
  }
2414

	
2415
  /// \brief Potential difference map
2416
  ///
2417
  /// If there is an potential map on the nodes then we
2418
  /// can get an arc map as we get the substraction of the
2419
  /// values of the target and source.
2420
  template <typename Digraph, typename NodeMap>
2421
  class PotentialDifferenceMap {
2422
  public:
2423
    typedef typename Digraph::Arc Key;
2424
    typedef typename NodeMap::Value Value;
2425

	
2426
    /// \brief Constructor
2427
    ///
2428
    /// Contructor of the map
2429
    explicit PotentialDifferenceMap(const Digraph& digraph,
2430
                                    const NodeMap& potential)
2431
      : _digraph(digraph), _potential(potential) {}
2432

	
2433
    /// \brief Const subscription operator
2434
    ///
2435
    /// Const subscription operator
2436
    Value operator[](const Key& arc) const {
2437
      return _potential[_digraph.target(arc)] -
2438
        _potential[_digraph.source(arc)];
2439
    }
2440

	
2441
  private:
2442
    const Digraph& _digraph;
2443
    const NodeMap& _potential;
2444
  };
2445

	
2446
  /// \brief Returns a PotentialDifferenceMap.
2447
  ///
2448
  /// This function just returns a PotentialDifferenceMap.
2449
  /// \relates PotentialDifferenceMap
2450
  template <typename Digraph, typename NodeMap>
2451
  PotentialDifferenceMap<Digraph, NodeMap>
2452
  potentialDifferenceMap(const Digraph& digraph, const NodeMap& potential) {
2453
    return PotentialDifferenceMap<Digraph, NodeMap>(digraph, potential);
2454
  }
2455

	
2456
  /// \brief Map of the node in-degrees.
2457
  ///
2458
  /// This map returns the in-degree of a node. Once it is constructed,
2459
  /// the degrees are stored in a standard NodeMap, so each query is done
2460
  /// in constant time. On the other hand, the values are updated automatically
2461
  /// whenever the digraph changes.
2462
  ///
2463
  /// \warning Besides addNode() and addArc(), a digraph structure may provide
2464
  /// alternative ways to modify the digraph. The correct behavior of InDegMap
2465
  /// is not guarantied if these additional features are used. For example
2466
  /// the functions \ref ListDigraph::changeSource() "changeSource()",
2467
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
2468
  /// \ref ListDigraph::reverseArc() "reverseArc()"
2469
  /// of \ref ListDigraph will \e not update the degree values correctly.
2470
  ///
2471
  /// \sa OutDegMap
2472

	
2473
  template <typename _Digraph>
2474
  class InDegMap
2475
    : protected ItemSetTraits<_Digraph, typename _Digraph::Arc>
2476
      ::ItemNotifier::ObserverBase {
2477

	
2478
  public:
2479

	
2480
    typedef _Digraph Digraph;
2481
    typedef int Value;
2482
    typedef typename Digraph::Node Key;
2483

	
2484
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
2485
    ::ItemNotifier::ObserverBase Parent;
2486

	
2487
  private:
2488

	
2489
    class AutoNodeMap
2490
      : public ItemSetTraits<Digraph, Key>::template Map<int>::Type {
2491
    public:
2492

	
2493
      typedef typename ItemSetTraits<Digraph, Key>::
2494
      template Map<int>::Type Parent;
2495

	
2496
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
2497

	
2498
      virtual void add(const Key& key) {
2499
        Parent::add(key);
2500
        Parent::set(key, 0);
2501
      }
2502

	
2503
      virtual void add(const std::vector<Key>& keys) {
2504
        Parent::add(keys);
2505
        for (int i = 0; i < int(keys.size()); ++i) {
2506
          Parent::set(keys[i], 0);
2507
        }
2508
      }
2509

	
2510
      virtual void build() {
2511
        Parent::build();
2512
        Key it;
2513
        typename Parent::Notifier* nf = Parent::notifier();
2514
        for (nf->first(it); it != INVALID; nf->next(it)) {
2515
          Parent::set(it, 0);
2516
        }
2517
      }
2518
    };
2519

	
2520
  public:
2521

	
2522
    /// \brief Constructor.
2523
    ///
2524
    /// Constructor for creating in-degree map.
2525
    explicit InDegMap(const Digraph& digraph)
2526
      : _digraph(digraph), _deg(digraph) {
2527
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2528

	
2529
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2530
        _deg[it] = countInArcs(_digraph, it);
2531
      }
2532
    }
2533

	
2534
    /// Gives back the in-degree of a Node.
2535
    int operator[](const Key& key) const {
2536
      return _deg[key];
2537
    }
2538

	
2539
  protected:
2540

	
2541
    typedef typename Digraph::Arc Arc;
2542

	
2543
    virtual void add(const Arc& arc) {
2544
      ++_deg[_digraph.target(arc)];
2545
    }
2546

	
2547
    virtual void add(const std::vector<Arc>& arcs) {
2548
      for (int i = 0; i < int(arcs.size()); ++i) {
2549
        ++_deg[_digraph.target(arcs[i])];
2550
      }
2551
    }
2552

	
2553
    virtual void erase(const Arc& arc) {
2554
      --_deg[_digraph.target(arc)];
2555
    }
2556

	
2557
    virtual void erase(const std::vector<Arc>& arcs) {
2558
      for (int i = 0; i < int(arcs.size()); ++i) {
2559
        --_deg[_digraph.target(arcs[i])];
2560
      }
2561
    }
2562

	
2563
    virtual void build() {
2564
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2565
        _deg[it] = countInArcs(_digraph, it);
2566
      }
2567
    }
2568

	
2569
    virtual void clear() {
2570
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2571
        _deg[it] = 0;
2572
      }
2573
    }
2574
  private:
2575

	
2576
    const Digraph& _digraph;
2577
    AutoNodeMap _deg;
2578
  };
2579

	
2580
  /// \brief Map of the node out-degrees.
2581
  ///
2582
  /// This map returns the out-degree of a node. Once it is constructed,
2583
  /// the degrees are stored in a standard NodeMap, so each query is done
2584
  /// in constant time. On the other hand, the values are updated automatically
2585
  /// whenever the digraph changes.
2586
  ///
2587
  /// \warning Besides addNode() and addArc(), a digraph structure may provide
2588
  /// alternative ways to modify the digraph. The correct behavior of OutDegMap
2589
  /// is not guarantied if these additional features are used. For example
2590
  /// the functions \ref ListDigraph::changeSource() "changeSource()",
2591
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
2592
  /// \ref ListDigraph::reverseArc() "reverseArc()"
2593
  /// of \ref ListDigraph will \e not update the degree values correctly.
2594
  ///
2595
  /// \sa InDegMap
2596

	
2597
  template <typename _Digraph>
2598
  class OutDegMap
2599
    : protected ItemSetTraits<_Digraph, typename _Digraph::Arc>
2600
      ::ItemNotifier::ObserverBase {
2601

	
2602
  public:
2603

	
2604
    typedef _Digraph Digraph;
2605
    typedef int Value;
2606
    typedef typename Digraph::Node Key;
2607

	
2608
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
2609
    ::ItemNotifier::ObserverBase Parent;
2610

	
2611
  private:
2612

	
2613
    class AutoNodeMap
2614
      : public ItemSetTraits<Digraph, Key>::template Map<int>::Type {
2615
    public:
2616

	
2617
      typedef typename ItemSetTraits<Digraph, Key>::
2618
      template Map<int>::Type Parent;
2619

	
2620
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
2621

	
2622
      virtual void add(const Key& key) {
2623
        Parent::add(key);
2624
        Parent::set(key, 0);
2625
      }
2626
      virtual void add(const std::vector<Key>& keys) {
2627
        Parent::add(keys);
2628
        for (int i = 0; i < int(keys.size()); ++i) {
2629
          Parent::set(keys[i], 0);
2630
        }
2631
      }
2632
      virtual void build() {
2633
        Parent::build();
2634
        Key it;
2635
        typename Parent::Notifier* nf = Parent::notifier();
2636
        for (nf->first(it); it != INVALID; nf->next(it)) {
2637
          Parent::set(it, 0);
2638
        }
2639
      }
2640
    };
2641

	
2642
  public:
2643

	
2644
    /// \brief Constructor.
2645
    ///
2646
    /// Constructor for creating out-degree map.
2647
    explicit OutDegMap(const Digraph& digraph)
2648
      : _digraph(digraph), _deg(digraph) {
2649
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2650

	
2651
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2652
        _deg[it] = countOutArcs(_digraph, it);
2653
      }
2654
    }
2655

	
2656
    /// Gives back the out-degree of a Node.
2657
    int operator[](const Key& key) const {
2658
      return _deg[key];
2659
    }
2660

	
2661
  protected:
2662

	
2663
    typedef typename Digraph::Arc Arc;
2664

	
2665
    virtual void add(const Arc& arc) {
2666
      ++_deg[_digraph.source(arc)];
2667
    }
2668

	
2669
    virtual void add(const std::vector<Arc>& arcs) {
2670
      for (int i = 0; i < int(arcs.size()); ++i) {
2671
        ++_deg[_digraph.source(arcs[i])];
2672
      }
2673
    }
2674

	
2675
    virtual void erase(const Arc& arc) {
2676
      --_deg[_digraph.source(arc)];
2677
    }
2678

	
2679
    virtual void erase(const std::vector<Arc>& arcs) {
2680
      for (int i = 0; i < int(arcs.size()); ++i) {
2681
        --_deg[_digraph.source(arcs[i])];
2682
      }
2683
    }
2684

	
2685
    virtual void build() {
2686
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2687
        _deg[it] = countOutArcs(_digraph, it);
2688
      }
2689
    }
2690

	
2691
    virtual void clear() {
2692
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2693
        _deg[it] = 0;
2694
      }
2695
    }
2696
  private:
2697

	
2698
    const Digraph& _digraph;
2699
    AutoNodeMap _deg;
2700
  };
2701

	
1783 2702
  /// @}
1784 2703
}
1785 2704

	
1786 2705
#endif // LEMON_MAPS_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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
///\ingroup paths
20 20
///\file
21 21
///\brief Classes for representing paths in digraphs.
22 22
///
23 23

	
24 24
#ifndef LEMON_PATH_H
25 25
#define LEMON_PATH_H
26 26

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

	
30 30
#include <lemon/error.h>
31
#include <lemon/bits/invalid.h>
31
#include <lemon/core.h>
32 32
#include <lemon/concepts/path.h>
33 33

	
34 34
namespace lemon {
35 35

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

	
39 39

	
40 40
  /// \brief A structure for representing directed paths in a digraph.
41 41
  ///
42 42
  /// A structure for representing directed path in a digraph.
43 43
  /// \tparam _Digraph The digraph type in which the path is.
44 44
  ///
45 45
  /// In a sense, the path can be treated as a list of arcs. The
46 46
  /// lemon path type stores just this list. As a consequence, it
47 47
  /// cannot enumerate the nodes of the path and the source node of
48 48
  /// a zero length path is undefined.
49 49
  ///
50 50
  /// This implementation is a back and front insertable and erasable
51 51
  /// path type. It can be indexed in O(1) time. The front and back
52 52
  /// insertion and erase is done in O(1) (amortized) time. The
53 53
  /// implementation uses two vectors for storing the front and back
54 54
  /// insertions.
55 55
  template <typename _Digraph>
56 56
  class Path {
57 57
  public:
58 58

	
59 59
    typedef _Digraph Digraph;
60 60
    typedef typename Digraph::Arc Arc;
61 61

	
62 62
    /// \brief Default constructor
63 63
    ///
64 64
    /// Default constructor
65 65
    Path() {}
66 66

	
67 67
    /// \brief Template copy constructor
68 68
    ///
69 69
    /// This constuctor initializes the path from any other path type.
70 70
    /// It simply makes a copy of the given path.
71 71
    template <typename CPath>
72 72
    Path(const CPath& cpath) {
73 73
      copyPath(*this, cpath);
74 74
    }
75 75

	
76 76
    /// \brief Template copy assignment
77 77
    ///
78 78
    /// This operator makes a copy of a path of any other type.
79 79
    template <typename CPath>
80 80
    Path& operator=(const CPath& cpath) {
81 81
      copyPath(*this, cpath);
82 82
      return *this;
83 83
    }
84 84

	
85 85
    /// \brief Lemon style iterator for path arcs
86 86
    ///
87 87
    /// This class is used to iterate on the arcs of the paths.
88 88
    class ArcIt {
89 89
      friend class Path;
90 90
    public:
91 91
      /// \brief Default constructor
92 92
      ArcIt() {}
93 93
      /// \brief Invalid constructor
94 94
      ArcIt(Invalid) : path(0), idx(-1) {}
95 95
      /// \brief Initializate the iterator to the first arc of path
96 96
      ArcIt(const Path &_path)
97 97
        : path(&_path), idx(_path.empty() ? -1 : 0) {}
98 98

	
99 99
    private:
100 100

	
101 101
      ArcIt(const Path &_path, int _idx)
102 102
        : path(&_path), idx(_idx) {}
103 103

	
104 104
    public:
105 105

	
106 106
      /// \brief Conversion to Arc
107 107
      operator const Arc&() const {
108 108
        return path->nth(idx);
109 109
      }
110 110

	
111 111
      /// \brief Next arc
112 112
      ArcIt& operator++() {
113 113
        ++idx;
114 114
        if (idx >= path->length()) idx = -1;
115 115
        return *this;
116 116
      }
117 117

	
118 118
      /// \brief Comparison operator
119 119
      bool operator==(const ArcIt& e) const { return idx==e.idx; }
120 120
      /// \brief Comparison operator
121 121
      bool operator!=(const ArcIt& e) const { return idx!=e.idx; }
122 122
      /// \brief Comparison operator
123 123
      bool operator<(const ArcIt& e) const { return idx<e.idx; }
124 124

	
125 125
    private:
126 126
      const Path *path;
127 127
      int idx;
128 128
    };
129 129

	
130 130
    /// \brief Length of the path.
131 131
    int length() const { return head.size() + tail.size(); }
132 132
    /// \brief Return whether the path is empty.
133 133
    bool empty() const { return head.empty() && tail.empty(); }
134 134

	
135 135
    /// \brief Reset the path to an empty one.
136 136
    void clear() { head.clear(); tail.clear(); }
137 137

	
138 138
    /// \brief The nth arc.
139 139
    ///
140 140
    /// \pre n is in the [0..length() - 1] range
141 141
    const Arc& nth(int n) const {
142 142
      return n < int(head.size()) ? *(head.rbegin() + n) :
143 143
        *(tail.begin() + (n - head.size()));
144 144
    }
145 145

	
146 146
    /// \brief Initialize arc iterator to point to the nth arc
147 147
    ///
148 148
    /// \pre n is in the [0..length() - 1] range
149 149
    ArcIt nthIt(int n) const {
150 150
      return ArcIt(*this, n);
151 151
    }
152 152

	
153 153
    /// \brief The first arc of the path
154 154
    const Arc& front() const {
155 155
      return head.empty() ? tail.front() : head.back();
156 156
    }
157 157

	
158 158
    /// \brief Add a new arc before the current path
159 159
    void addFront(const Arc& arc) {
160 160
      head.push_back(arc);
161 161
    }
162 162

	
163 163
    /// \brief Erase the first arc of the path
164 164
    void eraseFront() {
165 165
      if (!head.empty()) {
166 166
        head.pop_back();
167 167
      } else {
168 168
        head.clear();
169 169
        int halfsize = tail.size() / 2;
170 170
        head.resize(halfsize);
171 171
        std::copy(tail.begin() + 1, tail.begin() + halfsize + 1,
172 172
                  head.rbegin());
173 173
        std::copy(tail.begin() + halfsize + 1, tail.end(), tail.begin());
174 174
        tail.resize(tail.size() - halfsize - 1);
175 175
      }
176 176
    }
177 177

	
178 178
    /// \brief The last arc of the path
179 179
    const Arc& back() const {
180 180
      return tail.empty() ? head.front() : tail.back();
181 181
    }
182 182

	
183 183
    /// \brief Add a new arc behind the current path
184 184
    void addBack(const Arc& arc) {
185 185
      tail.push_back(arc);
186 186
    }
187 187

	
188 188
    /// \brief Erase the last arc of the path
189 189
    void eraseBack() {
190 190
      if (!tail.empty()) {
191 191
        tail.pop_back();
192 192
      } else {
193 193
        int halfsize = head.size() / 2;
194 194
        tail.resize(halfsize);
195 195
        std::copy(head.begin() + 1, head.begin() + halfsize + 1,
196 196
                  tail.rbegin());
197 197
        std::copy(head.begin() + halfsize + 1, head.end(), head.begin());
198 198
        head.resize(head.size() - halfsize - 1);
199 199
      }
200 200
    }
201 201

	
202 202
    typedef True BuildTag;
203 203

	
204 204
    template <typename CPath>
205 205
    void build(const CPath& path) {
206 206
      int len = path.length();
207 207
      tail.reserve(len);
208 208
      for (typename CPath::ArcIt it(path); it != INVALID; ++it) {
209 209
        tail.push_back(it);
210 210
      }
211 211
    }
212 212

	
213 213
    template <typename CPath>
214 214
    void buildRev(const CPath& path) {
215 215
      int len = path.length();
216 216
      head.reserve(len);
217 217
      for (typename CPath::RevArcIt it(path); it != INVALID; ++it) {
218 218
        head.push_back(it);
219 219
      }
220 220
    }
221 221

	
222 222
  protected:
223 223
    typedef std::vector<Arc> Container;
224 224
    Container head, tail;
225 225

	
226 226
  };
227 227

	
228 228
  /// \brief A structure for representing directed paths in a digraph.
229 229
  ///
230 230
  /// A structure for representing directed path in a digraph.
231 231
  /// \tparam _Digraph The digraph type in which the path is.
232 232
  ///
233 233
  /// In a sense, the path can be treated as a list of arcs. The
234 234
  /// lemon path type stores just this list. As a consequence it
235 235
  /// cannot enumerate the nodes in the path and the zero length paths
236 236
  /// cannot store the source.
237 237
  ///
238 238
  /// This implementation is a just back insertable and erasable path
239 239
  /// type. It can be indexed in O(1) time. The back insertion and
240 240
  /// erasure is amortized O(1) time. This implementation is faster
241 241
  /// then the \c Path type because it use just one vector for the
242 242
  /// arcs.
243 243
  template <typename _Digraph>
244 244
  class SimplePath {
245 245
  public:
246 246

	
247 247
    typedef _Digraph Digraph;
248 248
    typedef typename Digraph::Arc Arc;
249 249

	
250 250
    /// \brief Default constructor
251 251
    ///
252 252
    /// Default constructor
253 253
    SimplePath() {}
254 254

	
255 255
    /// \brief Template copy constructor
256 256
    ///
257 257
    /// This path can be initialized with any other path type. It just
258 258
    /// makes a copy of the given path.
259 259
    template <typename CPath>
260 260
    SimplePath(const CPath& cpath) {
261 261
      copyPath(*this, cpath);
262 262
    }
263 263

	
264 264
    /// \brief Template copy assignment
265 265
    ///
266 266
    /// This path can be initialized with any other path type. It just
267 267
    /// makes a copy of the given path.
268 268
    template <typename CPath>
269 269
    SimplePath& operator=(const CPath& cpath) {
270 270
      copyPath(*this, cpath);
271 271
      return *this;
272 272
    }
273 273

	
274 274
    /// \brief Iterator class to iterate on the arcs of the paths
275 275
    ///
276 276
    /// This class is used to iterate on the arcs of the paths
277 277
    ///
278 278
    /// Of course it converts to Digraph::Arc
279 279
    class ArcIt {
280 280
      friend class SimplePath;
281 281
    public:
282 282
      /// Default constructor
283 283
      ArcIt() {}
284 284
      /// Invalid constructor
285 285
      ArcIt(Invalid) : path(0), idx(-1) {}
286 286
      /// \brief Initializate the constructor to the first arc of path
287 287
      ArcIt(const SimplePath &_path)
288 288
        : path(&_path), idx(_path.empty() ? -1 : 0) {}
289 289

	
290 290
    private:
291 291

	
292 292
      /// Constructor with starting point
293 293
      ArcIt(const SimplePath &_path, int _idx)
294 294
        : idx(_idx), path(&_path) {}
295 295

	
296 296
    public:
297 297

	
298 298
      ///Conversion to Digraph::Arc
299 299
      operator const Arc&() const {
300 300
        return path->nth(idx);
301 301
      }
302 302

	
303 303
      /// Next arc
304 304
      ArcIt& operator++() {
305 305
        ++idx;
306 306
        if (idx >= path->length()) idx = -1;
307 307
        return *this;
308 308
      }
309 309

	
310 310
      /// Comparison operator
311 311
      bool operator==(const ArcIt& e) const { return idx==e.idx; }
312 312
      /// Comparison operator
313 313
      bool operator!=(const ArcIt& e) const { return idx!=e.idx; }
314 314
      /// Comparison operator
315 315
      bool operator<(const ArcIt& e) const { return idx<e.idx; }
316 316

	
317 317
    private:
318 318
      const SimplePath *path;
319 319
      int idx;
320 320
    };
321 321

	
322 322
    /// \brief Length of the path.
323 323
    int length() const { return data.size(); }
324 324
    /// \brief Return true if the path is empty.
325 325
    bool empty() const { return data.empty(); }
326 326

	
327 327
    /// \brief Reset the path to an empty one.
328 328
    void clear() { data.clear(); }
329 329

	
330 330
    /// \brief The nth arc.
331 331
    ///
332 332
    /// \pre n is in the [0..length() - 1] range
333 333
    const Arc& nth(int n) const {
334 334
      return data[n];
335 335
    }
336 336

	
337 337
    /// \brief  Initializes arc iterator to point to the nth arc.
338 338
    ArcIt nthIt(int n) const {
339 339
      return ArcIt(*this, n);
340 340
    }
341 341

	
342 342
    /// \brief The first arc of the path.
343 343
    const Arc& front() const {
344 344
      return data.front();
345 345
    }
346 346

	
347 347
    /// \brief The last arc of the path.
348 348
    const Arc& back() const {
349 349
      return data.back();
350 350
    }
351 351

	
352 352
    /// \brief Add a new arc behind the current path.
353 353
    void addBack(const Arc& arc) {
354 354
      data.push_back(arc);
355 355
    }
356 356

	
357 357
    /// \brief Erase the last arc of the path
358 358
    void eraseBack() {
359 359
      data.pop_back();
360 360
    }
361 361

	
362 362
    typedef True BuildTag;
363 363

	
364 364
    template <typename CPath>
365 365
    void build(const CPath& path) {
366 366
      int len = path.length();
367 367
      data.resize(len);
368 368
      int index = 0;
369 369
      for (typename CPath::ArcIt it(path); it != INVALID; ++it) {
370 370
        data[index] = it;;
371 371
        ++index;
372 372
      }
373 373
    }
374 374

	
375 375
    template <typename CPath>
376 376
    void buildRev(const CPath& path) {
377 377
      int len = path.length();
378 378
      data.resize(len);
379 379
      int index = len;
380 380
      for (typename CPath::RevArcIt it(path); it != INVALID; ++it) {
381 381
        --index;
382 382
        data[index] = it;;
383 383
      }
384 384
    }
385 385

	
386 386
  protected:
387 387
    typedef std::vector<Arc> Container;
388 388
    Container data;
389 389

	
390 390
  };
391 391

	
392 392
  /// \brief A structure for representing directed paths in a digraph.
393 393
  ///
394 394
  /// A structure for representing directed path in a digraph.
395 395
  /// \tparam _Digraph The digraph type in which the path is.
396 396
  ///
397 397
  /// In a sense, the path can be treated as a list of arcs. The
398 398
  /// lemon path type stores just this list. As a consequence it
399 399
  /// cannot enumerate the nodes in the path and the zero length paths
400 400
  /// cannot store the source.
401 401
  ///
402 402
  /// This implementation is a back and front insertable and erasable
403 403
  /// path type. It can be indexed in O(k) time, where k is the rank
404 404
  /// of the arc in the path. The length can be computed in O(n)
405 405
  /// time. The front and back insertion and erasure is O(1) time
406 406
  /// and it can be splited and spliced in O(1) time.
407 407
  template <typename _Digraph>
408 408
  class ListPath {
409 409
  public:
410 410

	
411 411
    typedef _Digraph Digraph;
412 412
    typedef typename Digraph::Arc Arc;
413 413

	
414 414
  protected:
415 415

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

	
19 19
#ifndef LEMON_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
#include <lemon/bits/invalid.h>
29

	
30
#include <lemon/bits/base_extender.h>
31
#include <lemon/bits/graph_extender.h>
32

	
33
#include <lemon/bits/utility.h>
28
#include <lemon/core.h>
34 29
#include <lemon/error.h>
35

	
36 30
#include <lemon/bits/graph_extender.h>
37 31

	
38 32
namespace lemon {
39 33

	
40 34
  class SmartDigraph;
41 35
  ///Base of SmartDigraph
42 36

	
43 37
  ///Base of SmartDigraph
44 38
  ///
45 39
  class SmartDigraphBase {
46 40
  protected:
47 41

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

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

	
62 56
  public:
63 57

	
64 58
    typedef SmartDigraphBase Graph;
65 59

	
66 60
    class Node;
67 61
    class Arc;
68 62

	
69 63
  public:
70 64

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

	
75 69
    typedef True NodeNumTag;
76 70
    typedef True EdgeNumTag;
77 71

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

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

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

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

	
101 95
      return Arc(n);
102 96
    }
103 97

	
104 98
    void clear() {
105 99
      arcs.clear();
106 100
      nodes.clear();
107 101
    }
108 102

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

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

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

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

	
125 119
    class Node {
126 120
      friend class SmartDigraphBase;
127 121
      friend class SmartDigraph;
128 122

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

	
140 134

	
141 135
    class Arc {
142 136
      friend class SmartDigraphBase;
143 137
      friend class SmartDigraph;
144 138

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

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

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

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

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

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

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

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

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

	
188 182
  };
189 183

	
190 184
  typedef DigraphExtender<SmartDigraphBase> ExtendedSmartDigraphBase;
191 185

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

	
208 202
    typedef ExtendedSmartDigraphBase Parent;
209 203

	
210 204
  private:
211 205

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

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

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

	
224 218
  public:
225 219

	
226 220
    /// Constructor
227 221

	
228 222
    /// Constructor.
229 223
    ///
230 224
    SmartDigraph() {};
231 225

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

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

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

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

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

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

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

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

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

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

	
287 281
    ///Clear the digraph.
288 282

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

	
295 289
    ///Split a node.
296 290

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

	
320 314
  public:
321 315

	
322 316
    class Snapshot;
323 317

	
324 318
  protected:
325 319

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

	
342 336
  public:
343 337

	
344 338
    ///Class to make a snapshot of the digraph and to restrore to it later.
345 339

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

	
368 362
      ///Default constructor.
369 363
      ///To actually make a snapshot you must call save().
370 364
      ///
371 365
      Snapshot() : _graph(0) {}
372 366
      ///Constructor that immediately makes a snapshot
373 367

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

	
381 375
      ///Make a snapshot.
382 376

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

	
395 389
      ///Undo the changes until a snapshot.
396 390

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

	
409 403

	
410 404
  class SmartGraphBase {
411 405

	
412 406
  protected:
413 407

	
414 408
    struct NodeT {
415 409
      int first_out;
416 410
    };
417 411

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

	
19 19
#ifndef LEMON_UNION_FIND_H
20 20
#define LEMON_UNION_FIND_H
21 21

	
22 22
//!\ingroup auxdat
23 23
//!\file
24 24
//!\brief Union-Find data structures.
25 25
//!
26 26

	
27 27
#include <vector>
28 28
#include <list>
29 29
#include <utility>
30 30
#include <algorithm>
31 31
#include <functional>
32 32

	
33
#include <lemon/bits/invalid.h>
33
#include <lemon/core.h>
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  /// \ingroup auxdat
38 38
  ///
39 39
  /// \brief A \e Union-Find data structure implementation
40 40
  ///
41 41
  /// The class implements the \e Union-Find data structure.
42 42
  /// The union operation uses rank heuristic, while
43 43
  /// the find operation uses path compression.
44 44
  /// This is a very simple but efficient implementation, providing
45 45
  /// only four methods: join (union), find, insert and size.
46 46
  /// For more features see the \ref UnionFindEnum class.
47 47
  ///
48 48
  /// It is primarily used in Kruskal algorithm for finding minimal
49 49
  /// cost spanning tree in a graph.
50 50
  /// \sa kruskal()
51 51
  ///
52 52
  /// \pre You need to add all the elements by the \ref insert()
53 53
  /// method.
54 54
  template <typename _ItemIntMap>
55 55
  class UnionFind {
56 56
  public:
57 57

	
58 58
    typedef _ItemIntMap ItemIntMap;
59 59
    typedef typename ItemIntMap::Key Item;
60 60

	
61 61
  private:
62 62
    // If the items vector stores negative value for an item then
63 63
    // that item is root item and it has -items[it] component size.
64 64
    // Else the items[it] contains the index of the parent.
65 65
    std::vector<int> items;
66 66
    ItemIntMap& index;
67 67

	
68 68
    bool rep(int idx) const {
69 69
      return items[idx] < 0;
70 70
    }
71 71

	
72 72
    int repIndex(int idx) const {
73 73
      int k = idx;
74 74
      while (!rep(k)) {
75 75
        k = items[k] ;
76 76
      }
77 77
      while (idx != k) {
78 78
        int next = items[idx];
79 79
        const_cast<int&>(items[idx]) = k;
80 80
        idx = next;
81 81
      }
82 82
      return k;
83 83
    }
84 84

	
85 85
  public:
86 86

	
87 87
    /// \brief Constructor
88 88
    ///
89 89
    /// Constructor of the UnionFind class. You should give an item to
90 90
    /// integer map which will be used from the data structure. If you
91 91
    /// modify directly this map that may cause segmentation fault,
92 92
    /// invalid data structure, or infinite loop when you use again
93 93
    /// the union-find.
94 94
    UnionFind(ItemIntMap& m) : index(m) {}
95 95

	
96 96
    /// \brief Returns the index of the element's component.
97 97
    ///
98 98
    /// The method returns the index of the element's component.
99 99
    /// This is an integer between zero and the number of inserted elements.
100 100
    ///
101 101
    int find(const Item& a) {
102 102
      return repIndex(index[a]);
103 103
    }
104 104

	
105 105
    /// \brief Clears the union-find data structure
106 106
    ///
107 107
    /// Erase each item from the data structure.
108 108
    void clear() {
109 109
      items.clear();
110 110
    }
111 111

	
112 112
    /// \brief Inserts a new element into the structure.
113 113
    ///
114 114
    /// This method inserts a new element into the data structure.
115 115
    ///
116 116
    /// The method returns the index of the new component.
117 117
    int insert(const Item& a) {
118 118
      int n = items.size();
119 119
      items.push_back(-1);
120 120
      index.set(a,n);
121 121
      return n;
122 122
    }
123 123

	
124 124
    /// \brief Joining the components of element \e a and element \e b.
125 125
    ///
126 126
    /// This is the \e union operation of the Union-Find structure.
127 127
    /// Joins the component of element \e a and component of
128 128
    /// element \e b. If \e a and \e b are in the same component then
129 129
    /// it returns false otherwise it returns true.
130 130
    bool join(const Item& a, const Item& b) {
131 131
      int ka = repIndex(index[a]);
132 132
      int kb = repIndex(index[b]);
133 133

	
134 134
      if ( ka == kb )
135 135
        return false;
136 136

	
137 137
      if (items[ka] < items[kb]) {
138 138
        items[ka] += items[kb];
139 139
        items[kb] = ka;
140 140
      } else {
141 141
        items[kb] += items[ka];
142 142
        items[ka] = kb;
143 143
      }
144 144
      return true;
145 145
    }
146 146

	
147 147
    /// \brief Returns the size of the component of element \e a.
148 148
    ///
149 149
    /// Returns the size of the component of element \e a.
150 150
    int size(const Item& a) {
151 151
      int k = repIndex(index[a]);
152 152
      return - items[k];
153 153
    }
154 154

	
155 155
  };
156 156

	
157 157
  /// \ingroup auxdat
158 158
  ///
159 159
  /// \brief A \e Union-Find data structure implementation which
160 160
  /// is able to enumerate the components.
161 161
  ///
162 162
  /// The class implements a \e Union-Find data structure
163 163
  /// which is able to enumerate the components and the items in
164 164
  /// a component. If you don't need this feature then perhaps it's
165 165
  /// better to use the \ref UnionFind class which is more efficient.
166 166
  ///
167 167
  /// The union operation uses rank heuristic, while
168 168
  /// the find operation uses path compression.
169 169
  ///
170 170
  /// \pre You need to add all the elements by the \ref insert()
171 171
  /// method.
172 172
  ///
173 173
  template <typename _ItemIntMap>
174 174
  class UnionFindEnum {
175 175
  public:
176 176

	
177 177
    typedef _ItemIntMap ItemIntMap;
178 178
    typedef typename ItemIntMap::Key Item;
179 179

	
180 180
  private:
181 181

	
182 182
    ItemIntMap& index;
183 183

	
184 184
    // If the parent stores negative value for an item then that item
185 185
    // is root item and it has ~(items[it].parent) component id.  Else
186 186
    // the items[it].parent contains the index of the parent.
187 187
    //
188 188
    // The \c next and \c prev provides the double-linked
189 189
    // cyclic list of one component's items.
190 190
    struct ItemT {
191 191
      int parent;
192 192
      Item item;
193 193

	
194 194
      int next, prev;
195 195
    };
196 196

	
197 197
    std::vector<ItemT> items;
198 198
    int firstFreeItem;
199 199

	
200 200
    struct ClassT {
201 201
      int size;
202 202
      int firstItem;
203 203
      int next, prev;
204 204
    };
205 205

	
206 206
    std::vector<ClassT> classes;
207 207
    int firstClass, firstFreeClass;
208 208

	
209 209
    int newClass() {
210 210
      if (firstFreeClass == -1) {
211 211
        int cdx = classes.size();
212 212
        classes.push_back(ClassT());
213 213
        return cdx;
214 214
      } else {
215 215
        int cdx = firstFreeClass;
216 216
        firstFreeClass = classes[firstFreeClass].next;
217 217
        return cdx;
218 218
      }
219 219
    }
220 220

	
221 221
    int newItem() {
222 222
      if (firstFreeItem == -1) {
223 223
        int idx = items.size();
224 224
        items.push_back(ItemT());
225 225
        return idx;
226 226
      } else {
227 227
        int idx = firstFreeItem;
228 228
        firstFreeItem = items[firstFreeItem].next;
229 229
        return idx;
230 230
      }
231 231
    }
232 232

	
233 233

	
234 234
    bool rep(int idx) const {
235 235
      return items[idx].parent < 0;
236 236
    }
237 237

	
238 238
    int repIndex(int idx) const {
239 239
      int k = idx;
240 240
      while (!rep(k)) {
241 241
        k = items[k].parent;
242 242
      }
243 243
      while (idx != k) {
244 244
        int next = items[idx].parent;
245 245
        const_cast<int&>(items[idx].parent) = k;
246 246
        idx = next;
247 247
      }
248 248
      return k;
249 249
    }
250 250

	
251 251
    int classIndex(int idx) const {
252 252
      return ~(items[repIndex(idx)].parent);
253 253
    }
254 254

	
255 255
    void singletonItem(int idx) {
256 256
      items[idx].next = idx;
257 257
      items[idx].prev = idx;
258 258
    }
259 259

	
260 260
    void laceItem(int idx, int rdx) {
261 261
      items[idx].prev = rdx;
262 262
      items[idx].next = items[rdx].next;
263 263
      items[items[rdx].next].prev = idx;
264 264
      items[rdx].next = idx;
265 265
    }
266 266

	
267 267
    void unlaceItem(int idx) {
268 268
      items[items[idx].prev].next = items[idx].next;
269 269
      items[items[idx].next].prev = items[idx].prev;
270 270

	
271 271
      items[idx].next = firstFreeItem;
272 272
      firstFreeItem = idx;
273 273
    }
274 274

	
275 275
    void spliceItems(int ak, int bk) {
276 276
      items[items[ak].prev].next = bk;
277 277
      items[items[bk].prev].next = ak;
278 278
      int tmp = items[ak].prev;
279 279
      items[ak].prev = items[bk].prev;
280 280
      items[bk].prev = tmp;
281 281

	
282 282
    }
283 283

	
284 284
    void laceClass(int cls) {
285 285
      if (firstClass != -1) {
286 286
        classes[firstClass].prev = cls;
287 287
      }
288 288
      classes[cls].next = firstClass;
289 289
      classes[cls].prev = -1;
290 290
      firstClass = cls;
291 291
    }
292 292

	
293 293
    void unlaceClass(int cls) {
294 294
      if (classes[cls].prev != -1) {
295 295
        classes[classes[cls].prev].next = classes[cls].next;
296 296
      } else {
297 297
        firstClass = classes[cls].next;
298 298
      }
299 299
      if (classes[cls].next != -1) {
300 300
        classes[classes[cls].next].prev = classes[cls].prev;
301 301
      }
302 302

	
303 303
      classes[cls].next = firstFreeClass;
304 304
      firstFreeClass = cls;
305 305
    }
306 306

	
307 307
  public:
308 308

	
309 309
    UnionFindEnum(ItemIntMap& _index)
310 310
      : index(_index), items(), firstFreeItem(-1),
311 311
        firstClass(-1), firstFreeClass(-1) {}
312 312

	
313 313
    /// \brief Inserts the given element into a new component.
314 314
    ///
315 315
    /// This method creates a new component consisting only of the
316 316
    /// given element.
317 317
    ///
318 318
    int insert(const Item& item) {
319 319
      int idx = newItem();
320 320

	
321 321
      index.set(item, idx);
322 322

	
323 323
      singletonItem(idx);
324 324
      items[idx].item = item;
325 325

	
326 326
      int cdx = newClass();
327 327

	
328 328
      items[idx].parent = ~cdx;
329 329

	
330 330
      laceClass(cdx);
331 331
      classes[cdx].size = 1;
332 332
      classes[cdx].firstItem = idx;
333 333

	
334 334
      firstClass = cdx;
335 335

	
336 336
      return cdx;
337 337
    }
338 338

	
339 339
    /// \brief Inserts the given element into the component of the others.
340 340
    ///
341 341
    /// This methods inserts the element \e a into the component of the
342 342
    /// element \e comp.
343 343
    void insert(const Item& item, int cls) {
344 344
      int rdx = classes[cls].firstItem;
345 345
      int idx = newItem();
346 346

	
347 347
      index.set(item, idx);
348 348

	
349 349
      laceItem(idx, rdx);
350 350

	
351 351
      items[idx].item = item;
352 352
      items[idx].parent = rdx;
353 353

	
354 354
      ++classes[~(items[rdx].parent)].size;
355 355
    }
356 356

	
357 357
    /// \brief Clears the union-find data structure
358 358
    ///
359 359
    /// Erase each item from the data structure.
360 360
    void clear() {
361 361
      items.clear();
362 362
      firstClass = -1;
363 363
      firstFreeItem = -1;
364 364
    }
365 365

	
366 366
    /// \brief Finds the component of the given element.
367 367
    ///
368 368
    /// The method returns the component id of the given element.
369 369
    int find(const Item &item) const {
370 370
      return ~(items[repIndex(index[item])].parent);
371 371
    }
372 372

	
373 373
    /// \brief Joining the component of element \e a and element \e b.
374 374
    ///
375 375
    /// This is the \e union operation of the Union-Find structure.
376 376
    /// Joins the component of element \e a and component of
377 377
    /// element \e b. If \e a and \e b are in the same component then
378 378
    /// returns -1 else returns the remaining class.
379 379
    int join(const Item& a, const Item& b) {
380 380

	
381 381
      int ak = repIndex(index[a]);
382 382
      int bk = repIndex(index[b]);
383 383

	
384 384
      if (ak == bk) {
385 385
        return -1;
386 386
      }
387 387

	
388 388
      int acx = ~(items[ak].parent);
389 389
      int bcx = ~(items[bk].parent);
390 390

	
391 391
      int rcx;
392 392

	
393 393
      if (classes[acx].size > classes[bcx].size) {
394 394
        classes[acx].size += classes[bcx].size;
395 395
        items[bk].parent = ak;
396 396
        unlaceClass(bcx);
397 397
        rcx = acx;
398 398
      } else {
399 399
        classes[bcx].size += classes[acx].size;
400 400
        items[ak].parent = bk;
401 401
        unlaceClass(acx);
402 402
        rcx = bcx;
403 403
      }
404 404
      spliceItems(ak, bk);
405 405

	
406 406
      return rcx;
407 407
    }
408 408

	
409 409
    /// \brief Returns the size of the class.
410 410
    ///
411 411
    /// Returns the size of the class.
412 412
    int size(int cls) const {
413 413
      return classes[cls].size;
414 414
    }
415 415

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

	
19 19
#include <lemon/concepts/digraph.h>
20 20
#include <lemon/smart_graph.h>
21 21
#include <lemon/list_graph.h>
22
#include <lemon/graph_utils.h>
23 22
#include <lemon/dijkstra.h>
24 23
#include <lemon/path.h>
25 24

	
26 25
#include "graph_test.h"
27 26
#include "test_tools.h"
28 27

	
29 28
using namespace lemon;
30 29

	
31 30
void checkDijkstraCompile()
32 31
{
33 32
  typedef int VType;
34 33
  typedef concepts::Digraph Digraph;
35 34
  typedef concepts::ReadMap<Digraph::Arc,VType> LengthMap;
36 35
  typedef Dijkstra<Digraph, LengthMap> DType;
37 36

	
38 37
  Digraph G;
39 38
  Digraph::Node n;
40 39
  Digraph::Arc e;
41 40
  VType l;
42 41
  bool b;
43 42
  DType::DistMap d(G);
44 43
  DType::PredMap p(G);
45 44
  //  DType::PredNodeMap pn(G);
46 45
  LengthMap length;
47 46

	
48 47
  DType dijkstra_test(G,length);
49 48

	
50 49
  dijkstra_test.run(n);
51 50

	
52 51
  l  = dijkstra_test.dist(n);
53 52
  e  = dijkstra_test.predArc(n);
54 53
  n  = dijkstra_test.predNode(n);
55 54
  d  = dijkstra_test.distMap();
56 55
  p  = dijkstra_test.predMap();
57 56
  //  pn = dijkstra_test.predNodeMap();
58 57
  b  = dijkstra_test.reached(n);
59 58

	
60 59
  Path<Digraph> pp = dijkstra_test.path(n);
61 60
}
62 61

	
63 62
void checkDijkstraFunctionCompile()
64 63
{
65 64
  typedef int VType;
66 65
  typedef concepts::Digraph Digraph;
67 66
  typedef Digraph::Arc Arc;
68 67
  typedef Digraph::Node Node;
69 68
  typedef concepts::ReadMap<Digraph::Arc,VType> LengthMap;
70 69

	
71 70
  Digraph g;
72 71
  dijkstra(g,LengthMap(),Node()).run();
73 72
  dijkstra(g,LengthMap()).source(Node()).run();
74 73
  dijkstra(g,LengthMap())
75 74
    .predMap(concepts::WriteMap<Node,Arc>())
76 75
    .distMap(concepts::WriteMap<Node,VType>())
77 76
    .run(Node());
78 77
}
79 78

	
80 79
template <class Digraph>
81 80
void checkDijkstra() {
82 81
  TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
83 82
  typedef typename Digraph::template ArcMap<int> LengthMap;
84 83

	
85 84
  Digraph G;
86 85
  Node s, t;
87 86
  LengthMap length(G);
88 87
  PetStruct<Digraph> ps = addPetersen(G, 5);
89 88

	
90 89
  for(int i=0;i<5;i++) {
91 90
    length[ps.outcir[i]]=4;
92 91
    length[ps.incir[i]]=1;
93 92
    length[ps.chords[i]]=10;
94 93
  }
95 94
  s=ps.outer[0];
96 95
  t=ps.inner[1];
97 96

	
98 97
  Dijkstra<Digraph, LengthMap>
99 98
        dijkstra_test(G, length);
100 99
  dijkstra_test.run(s);
101 100

	
102 101
  check(dijkstra_test.dist(t)==13,"Dijkstra found a wrong path.");
103 102

	
104 103
  Path<Digraph> p = dijkstra_test.path(t);
105 104
  check(p.length()==4,"getPath() found a wrong path.");
106 105
  check(checkPath(G, p),"path() found a wrong path.");
107 106
  check(pathSource(G, p) == s,"path() found a wrong path.");
108 107
  check(pathTarget(G, p) == t,"path() found a wrong path.");
109 108

	
110 109
  for(ArcIt e(G); e!=INVALID; ++e) {
111 110
    Node u=G.source(e);
112 111
    Node v=G.target(e);
113 112
    check( !dijkstra_test.reached(u) ||
114 113
           (dijkstra_test.dist(v) - dijkstra_test.dist(u) <= length[e]),
115 114
           "dist(target)-dist(source)-arc_length= " <<
116 115
           dijkstra_test.dist(v) - dijkstra_test.dist(u) - length[e]);
117 116
  }
118 117

	
119 118
  for(NodeIt v(G); v!=INVALID; ++v){
120 119
    check(dijkstra_test.reached(v),"Each node should be reached.");
121 120
    if ( dijkstra_test.predArc(v)!=INVALID ) {
122 121
      Arc e=dijkstra_test.predArc(v);
123 122
      Node u=G.source(e);
124 123
      check(u==dijkstra_test.predNode(v),"Wrong tree.");
125 124
      check(dijkstra_test.dist(v) - dijkstra_test.dist(u) == length[e],
126 125
            "Wrong distance! Difference: " <<
127 126
            std::abs(dijkstra_test.dist(v)-dijkstra_test.dist(u)-length[e]));
128 127
    }
129 128
  }
130 129

	
131 130
  {
132 131
    NullMap<Node,Arc> myPredMap;
133 132
    dijkstra(G,length).predMap(myPredMap).run(s);
134 133
  }
135 134
}
136 135

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

	
19 19
#include <lemon/smart_graph.h>
20 20
#include <lemon/list_graph.h>
21 21
#include <lemon/lgf_reader.h>
22
#include <lemon/graph_utils.h>
23 22
#include <lemon/error.h>
24 23

	
25 24
#include "test_tools.h"
26 25

	
27 26
using namespace std;
28 27
using namespace lemon;
29 28

	
30 29
void digraph_copy_test() {
31 30
  const int nn = 10;
32 31

	
33 32
  SmartDigraph from;
34 33
  SmartDigraph::NodeMap<int> fnm(from);
35 34
  SmartDigraph::ArcMap<int> fam(from);
36 35
  SmartDigraph::Node fn = INVALID;
37 36
  SmartDigraph::Arc fa = INVALID;
38 37

	
39 38
  std::vector<SmartDigraph::Node> fnv;
40 39
  for (int i = 0; i < nn; ++i) {
41 40
    SmartDigraph::Node node = from.addNode();
42 41
    fnv.push_back(node);
43 42
    fnm[node] = i * i;
44 43
    if (i == 0) fn = node;
45 44
  }
46 45

	
47 46
  for (int i = 0; i < nn; ++i) {
48 47
    for (int j = 0; j < nn; ++j) {
49 48
      SmartDigraph::Arc arc = from.addArc(fnv[i], fnv[j]);
50 49
      fam[arc] = i + j * j;
51 50
      if (i == 0 && j == 0) fa = arc;
52 51
    }
53 52
  }
54 53

	
55 54
  ListDigraph to;
56 55
  ListDigraph::NodeMap<int> tnm(to);
57 56
  ListDigraph::ArcMap<int> tam(to);
58 57
  ListDigraph::Node tn;
59 58
  ListDigraph::Arc ta;
60 59

	
61 60
  SmartDigraph::NodeMap<ListDigraph::Node> nr(from);
62 61
  SmartDigraph::ArcMap<ListDigraph::Arc> er(from);
63 62

	
64 63
  ListDigraph::NodeMap<SmartDigraph::Node> ncr(to);
65 64
  ListDigraph::ArcMap<SmartDigraph::Arc> ecr(to);
66 65

	
67 66
  DigraphCopy<ListDigraph, SmartDigraph>(to, from).
68 67
    nodeMap(tnm, fnm).arcMap(tam, fam).
69 68
    nodeRef(nr).arcRef(er).
70 69
    nodeCrossRef(ncr).arcCrossRef(ecr).
71 70
    node(tn, fn).arc(ta, fa).run();
72 71

	
73 72
  for (SmartDigraph::NodeIt it(from); it != INVALID; ++it) {
74 73
    check(ncr[nr[it]] == it, "Wrong copy.");
75 74
    check(fnm[it] == tnm[nr[it]], "Wrong copy.");
76 75
  }
77 76

	
78 77
  for (SmartDigraph::ArcIt it(from); it != INVALID; ++it) {
79 78
    check(ecr[er[it]] == it, "Wrong copy.");
80 79
    check(fam[it] == tam[er[it]], "Wrong copy.");
81 80
    check(nr[from.source(it)] == to.source(er[it]), "Wrong copy.");
82 81
    check(nr[from.target(it)] == to.target(er[it]), "Wrong copy.");
83 82
  }
84 83

	
85 84
  for (ListDigraph::NodeIt it(to); it != INVALID; ++it) {
86 85
    check(nr[ncr[it]] == it, "Wrong copy.");
87 86
  }
88 87

	
89 88
  for (ListDigraph::ArcIt it(to); it != INVALID; ++it) {
90 89
    check(er[ecr[it]] == it, "Wrong copy.");
91 90
  }
92 91
  check(tn == nr[fn], "Wrong copy.");
93 92
  check(ta == er[fa], "Wrong copy.");
94 93
}
95 94

	
96 95
void graph_copy_test() {
97 96
  const int nn = 10;
98 97

	
99 98
  SmartGraph from;
100 99
  SmartGraph::NodeMap<int> fnm(from);
101 100
  SmartGraph::ArcMap<int> fam(from);
102 101
  SmartGraph::EdgeMap<int> fem(from);
103 102
  SmartGraph::Node fn = INVALID;
104 103
  SmartGraph::Arc fa = INVALID;
105 104
  SmartGraph::Edge fe = INVALID;
106 105

	
107 106
  std::vector<SmartGraph::Node> fnv;
108 107
  for (int i = 0; i < nn; ++i) {
109 108
    SmartGraph::Node node = from.addNode();
110 109
    fnv.push_back(node);
111 110
    fnm[node] = i * i;
112 111
    if (i == 0) fn = node;
113 112
  }
114 113

	
115 114
  for (int i = 0; i < nn; ++i) {
116 115
    for (int j = 0; j < nn; ++j) {
117 116
      SmartGraph::Edge edge = from.addEdge(fnv[i], fnv[j]);
118 117
      fem[edge] = i * i + j * j;
119 118
      fam[from.direct(edge, true)] = i + j * j;
120 119
      fam[from.direct(edge, false)] = i * i + j;
121 120
      if (i == 0 && j == 0) fa = from.direct(edge, true);
122 121
      if (i == 0 && j == 0) fe = edge;
123 122
    }
124 123
  }
125 124

	
126 125
  ListGraph to;
127 126
  ListGraph::NodeMap<int> tnm(to);
128 127
  ListGraph::ArcMap<int> tam(to);
129 128
  ListGraph::EdgeMap<int> tem(to);
130 129
  ListGraph::Node tn;
131 130
  ListGraph::Arc ta;
132 131
  ListGraph::Edge te;
133 132

	
134 133
  SmartGraph::NodeMap<ListGraph::Node> nr(from);
135 134
  SmartGraph::ArcMap<ListGraph::Arc> ar(from);
136 135
  SmartGraph::EdgeMap<ListGraph::Edge> er(from);
137 136

	
138 137
  ListGraph::NodeMap<SmartGraph::Node> ncr(to);
139 138
  ListGraph::ArcMap<SmartGraph::Arc> acr(to);
140 139
  ListGraph::EdgeMap<SmartGraph::Edge> ecr(to);
141 140

	
142 141
  GraphCopy<ListGraph, SmartGraph>(to, from).
143 142
    nodeMap(tnm, fnm).arcMap(tam, fam).edgeMap(tem, fem).
144 143
    nodeRef(nr).arcRef(ar).edgeRef(er).
145 144
    nodeCrossRef(ncr).arcCrossRef(acr).edgeCrossRef(ecr).
146 145
    node(tn, fn).arc(ta, fa).edge(te, fe).run();
147 146

	
148 147
  for (SmartGraph::NodeIt it(from); it != INVALID; ++it) {
149 148
    check(ncr[nr[it]] == it, "Wrong copy.");
150 149
    check(fnm[it] == tnm[nr[it]], "Wrong copy.");
151 150
  }
152 151

	
153 152
  for (SmartGraph::ArcIt it(from); it != INVALID; ++it) {
154 153
    check(acr[ar[it]] == it, "Wrong copy.");
155 154
    check(fam[it] == tam[ar[it]], "Wrong copy.");
156 155
    check(nr[from.source(it)] == to.source(ar[it]), "Wrong copy.");
157 156
    check(nr[from.target(it)] == to.target(ar[it]), "Wrong copy.");
158 157
  }
159 158

	
160 159
  for (SmartGraph::EdgeIt it(from); it != INVALID; ++it) {
161 160
    check(ecr[er[it]] == it, "Wrong copy.");
162 161
    check(fem[it] == tem[er[it]], "Wrong copy.");
163 162
    check(nr[from.u(it)] == to.u(er[it]) || nr[from.u(it)] == to.v(er[it]),
164 163
          "Wrong copy.");
165 164
    check(nr[from.v(it)] == to.u(er[it]) || nr[from.v(it)] == to.v(er[it]),
166 165
          "Wrong copy.");
167 166
    check((from.u(it) != from.v(it)) == (to.u(er[it]) != to.v(er[it])),
168 167
          "Wrong copy.");
169 168
  }
170 169

	
171 170
  for (ListGraph::NodeIt it(to); it != INVALID; ++it) {
172 171
    check(nr[ncr[it]] == it, "Wrong copy.");
173 172
  }
174 173

	
175 174
  for (ListGraph::ArcIt it(to); it != INVALID; ++it) {
176 175
    check(ar[acr[it]] == it, "Wrong copy.");
177 176
  }
178 177
  for (ListGraph::EdgeIt it(to); it != INVALID; ++it) {
179 178
    check(er[ecr[it]] == it, "Wrong copy.");
180 179
  }
181 180
  check(tn == nr[fn], "Wrong copy.");
182 181
  check(ta == ar[fa], "Wrong copy.");
183 182
  check(te == er[fe], "Wrong copy.");
184 183
}
185 184

	
186 185

	
187 186
int main() {
188 187
  digraph_copy_test();
189 188
  graph_copy_test();
190 189

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

	
19 19
#ifndef LEMON_TEST_GRAPH_TEST_H
20 20
#define LEMON_TEST_GRAPH_TEST_H
21 21

	
22
#include <lemon/graph_utils.h>
22
#include <lemon/core.h>
23 23
#include "test_tools.h"
24 24

	
25 25
namespace lemon {
26 26

	
27 27
  template<class Graph>
28 28
  void checkGraphNodeList(const Graph &G, int cnt)
29 29
  {
30 30
    typename Graph::NodeIt n(G);
31 31
    for(int i=0;i<cnt;i++) {
32 32
      check(n!=INVALID,"Wrong Node list linking.");
33 33
      ++n;
34 34
    }
35 35
    check(n==INVALID,"Wrong Node list linking.");
36 36
    check(countNodes(G)==cnt,"Wrong Node number.");
37 37
  }
38 38

	
39 39
  template<class Graph>
40 40
  void checkGraphArcList(const Graph &G, int cnt)
41 41
  {
42 42
    typename Graph::ArcIt e(G);
43 43
    for(int i=0;i<cnt;i++) {
44 44
      check(e!=INVALID,"Wrong Arc list linking.");
45 45
      ++e;
46 46
    }
47 47
    check(e==INVALID,"Wrong Arc list linking.");
48 48
    check(countArcs(G)==cnt,"Wrong Arc number.");
49 49
  }
50 50

	
51 51
  template<class Graph>
52 52
  void checkGraphOutArcList(const Graph &G, typename Graph::Node n, int cnt)
53 53
  {
54 54
    typename Graph::OutArcIt e(G,n);
55 55
    for(int i=0;i<cnt;i++) {
56 56
      check(e!=INVALID,"Wrong OutArc list linking.");
57 57
      check(n==G.source(e),"Wrong OutArc list linking.");
58 58
      ++e;
59 59
    }
60 60
    check(e==INVALID,"Wrong OutArc list linking.");
61 61
    check(countOutArcs(G,n)==cnt,"Wrong OutArc number.");
62 62
  }
63 63

	
64 64
  template<class Graph>
65 65
  void checkGraphInArcList(const Graph &G, typename Graph::Node n, int cnt)
66 66
  {
67 67
    typename Graph::InArcIt e(G,n);
68 68
    for(int i=0;i<cnt;i++) {
69 69
      check(e!=INVALID,"Wrong InArc list linking.");
70 70
      check(n==G.target(e),"Wrong InArc list linking.");
71 71
      ++e;
72 72
    }
73 73
    check(e==INVALID,"Wrong InArc list linking.");
74 74
    check(countInArcs(G,n)==cnt,"Wrong InArc number.");
75 75
  }
76 76

	
77 77
  template<class Graph>
78 78
  void checkGraphEdgeList(const Graph &G, int cnt)
79 79
  {
80 80
    typename Graph::EdgeIt e(G);
81 81
    for(int i=0;i<cnt;i++) {
82 82
      check(e!=INVALID,"Wrong Edge list linking.");
83 83
      ++e;
84 84
    }
85 85
    check(e==INVALID,"Wrong Edge list linking.");
86 86
    check(countEdges(G)==cnt,"Wrong Edge number.");
87 87
  }
88 88

	
89 89
  template<class Graph>
90 90
  void checkGraphIncEdgeList(const Graph &G, typename Graph::Node n, int cnt)
91 91
  {
92 92
    typename Graph::IncEdgeIt e(G,n);
93 93
    for(int i=0;i<cnt;i++) {
94 94
      check(e!=INVALID,"Wrong IncEdge list linking.");
95 95
      check(n==G.u(e) || n==G.v(e),"Wrong IncEdge list linking.");
96 96
      ++e;
97 97
    }
98 98
    check(e==INVALID,"Wrong IncEdge list linking.");
99 99
    check(countIncEdges(G,n)==cnt,"Wrong IncEdge number.");
100 100
  }
101 101

	
102 102
  template <class Digraph>
103 103
  void checkDigraphIterators() {
104 104
    typedef typename Digraph::Node Node;
105 105
    typedef typename Digraph::NodeIt NodeIt;
106 106
    typedef typename Digraph::Arc Arc;
107 107
    typedef typename Digraph::ArcIt ArcIt;
108 108
    typedef typename Digraph::InArcIt InArcIt;
109 109
    typedef typename Digraph::OutArcIt OutArcIt;
110 110
  }
111 111

	
112 112
  template <class Graph>
113 113
  void checkGraphIterators() {
114 114
    checkDigraphIterators<Graph>();
115 115
    typedef typename Graph::Edge Edge;
116 116
    typedef typename Graph::EdgeIt EdgeIt;
117 117
    typedef typename Graph::IncEdgeIt IncEdgeIt;
118 118
  }
119 119

	
120 120
  // Structure returned by addPetersen()
121 121
  template<class Digraph>
122 122
  struct PetStruct
123 123
  {
124 124
    // Vector containing the outer nodes
125 125
    std::vector<typename Digraph::Node> outer;
126 126
    // Vector containing the inner nodes
127 127
    std::vector<typename Digraph::Node> inner;
128 128
    // Vector containing the arcs of the inner circle
129 129
    std::vector<typename Digraph::Arc> incir;
130 130
    // Vector containing the arcs of the outer circle
131 131
    std::vector<typename Digraph::Arc> outcir;
132 132
    // Vector containing the chord arcs
133 133
    std::vector<typename Digraph::Arc> chords;
134 134
  };
135 135

	
136 136
  // Adds the reverse pair of all arcs to a digraph
137 137
  template<class Digraph>
138 138
  void bidirDigraph(Digraph &G)
139 139
  {
140 140
    typedef typename Digraph::Arc Arc;
141 141
    typedef typename Digraph::ArcIt ArcIt;
142 142

	
143 143
    std::vector<Arc> ee;
144 144

	
145 145
    for(ArcIt e(G);e!=INVALID;++e) ee.push_back(e);
146 146

	
147 147
    for(int i=0;i<int(ee.size());++i)
148 148
      G.addArc(G.target(ee[i]),G.source(ee[i]));
149 149
  }
150 150

	
151 151
  // Adds a Petersen digraph to G.
152 152
  // Returns the nodes and arcs of the generated digraph.
153 153
  template<typename Digraph>
154 154
  PetStruct<Digraph> addPetersen(Digraph &G,int num = 5)
155 155
  {
156 156
    PetStruct<Digraph> n;
157 157

	
158 158
    for(int i=0;i<num;i++) {
159 159
      n.outer.push_back(G.addNode());
160 160
      n.inner.push_back(G.addNode());
161 161
    }
162 162

	
163 163
    for(int i=0;i<num;i++) {
164 164
      n.chords.push_back(G.addArc(n.outer[i],n.inner[i]));
165 165
      n.outcir.push_back(G.addArc(n.outer[i],n.outer[(i+1) % num]));
166 166
      n.incir.push_back(G.addArc(n.inner[i],n.inner[(i+2) % num]));
167 167
    }
168 168

	
169 169
    return n;
170 170
  }
171 171

	
172 172
  // Checks the bidirectioned Petersen digraph
173 173
  template<class Digraph>
174 174
  void checkBidirPetersen(const Digraph &G, int num = 5)
175 175
  {
176 176
    typedef typename Digraph::NodeIt NodeIt;
177 177

	
178 178
    checkGraphNodeList(G, 2 * num);
179 179
    checkGraphArcList(G, 6 * num);
180 180

	
181 181
    for(NodeIt n(G);n!=INVALID;++n) {
182 182
      checkGraphInArcList(G, n, 3);
183 183
      checkGraphOutArcList(G, n, 3);
184 184
    }
185 185
  }
186 186

	
187 187
  // Structure returned by addUPetersen()
188 188
  template<class Graph>
189 189
  struct UPetStruct
190 190
  {
191 191
    // Vector containing the outer nodes
192 192
    std::vector<typename Graph::Node> outer;
193 193
    // Vector containing the inner nodes
194 194
    std::vector<typename Graph::Node> inner;
195 195
    // Vector containing the edges of the inner circle
196 196
    std::vector<typename Graph::Edge> incir;
197 197
    // Vector containing the edges of the outer circle
198 198
    std::vector<typename Graph::Edge> outcir;
199 199
    // Vector containing the chord edges
200 200
    std::vector<typename Graph::Edge> chords;
201 201
  };
202 202

	
203 203
  // Adds a Petersen graph to \c G.
204 204
  // Returns the nodes and edges of the generated graph.
205 205
  template<typename Graph>
206 206
  UPetStruct<Graph> addUPetersen(Graph &G,int num=5)
207 207
  {
208 208
    UPetStruct<Graph> n;
209 209

	
210 210
    for(int i=0;i<num;i++) {
211 211
      n.outer.push_back(G.addNode());
212 212
      n.inner.push_back(G.addNode());
213 213
    }
214 214

	
215 215
    for(int i=0;i<num;i++) {
216 216
      n.chords.push_back(G.addEdge(n.outer[i],n.inner[i]));
217 217
      n.outcir.push_back(G.addEdge(n.outer[i],n.outer[(i+1)%num]));
218 218
      n.incir.push_back(G.addEdge(n.inner[i],n.inner[(i+2)%num]));
219 219
    }
220 220

	
221 221
    return n;
222 222
  }
223 223

	
224 224
  // Checks the undirected Petersen graph
225 225
  template<class Graph>
226 226
  void checkUndirPetersen(const Graph &G, int num = 5)
227 227
  {
228 228
    typedef typename Graph::NodeIt NodeIt;
229 229

	
230 230
    checkGraphNodeList(G, 2 * num);
231 231
    checkGraphEdgeList(G, 3 * num);
232 232
    checkGraphArcList(G, 6 * num);
233 233

	
234 234
    for(NodeIt n(G);n!=INVALID;++n) {
235 235
      checkGraphIncEdgeList(G, n, 3);
236 236
    }
237 237
  }
238 238

	
239 239
  template <class Digraph>
240 240
  void checkDigraph() {
241 241
    const int num = 5;
242 242
    Digraph G;
243 243
    checkGraphNodeList(G, 0);
244 244
    checkGraphArcList(G, 0);
245 245
    addPetersen(G, num);
246 246
    bidirDigraph(G);
247 247
    checkBidirPetersen(G, num);
248 248
  }
249 249

	
250 250
  template <class Graph>
251 251
  void checkGraph() {
252 252
    const int num = 5;
253 253
    Graph G;
254 254
    checkGraphNodeList(G, 0);
255 255
    checkGraphEdgeList(G, 0);
256 256
    addUPetersen(G, num);
257 257
    checkUndirPetersen(G, num);
258 258
  }
259 259

	
260 260
} //namespace lemon
261 261

	
262 262
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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
#include <cstdlib>
20 20
#include <ctime>
21 21

	
22 22
#include <lemon/random.h>
23
#include <lemon/graph_utils.h>
24 23
#include <lemon/list_graph.h>
25 24
#include <lemon/smart_graph.h>
25
#include <lemon/maps.h>
26 26

	
27 27
#include "graph_test.h"
28 28
#include "test_tools.h"
29 29

	
30 30
using namespace lemon;
31 31

	
32 32
template <typename Digraph>
33 33
void checkFindArcs() {
34 34
  TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
35 35

	
36 36
  {
37 37
    Digraph digraph;
38 38
    for (int i = 0; i < 10; ++i) {
39 39
      digraph.addNode();
40 40
    }
41 41
    DescriptorMap<Digraph, Node> nodes(digraph);
42 42
    typename DescriptorMap<Digraph, Node>::InverseMap invNodes(nodes);
43 43
    for (int i = 0; i < 100; ++i) {
44 44
      int src = rnd[invNodes.size()];
45 45
      int trg = rnd[invNodes.size()];
46 46
      digraph.addArc(invNodes[src], invNodes[trg]);
47 47
    }
48 48
    typename Digraph::template ArcMap<bool> found(digraph, false);
49 49
    DescriptorMap<Digraph, Arc> arcs(digraph);
50 50
    for (NodeIt src(digraph); src != INVALID; ++src) {
51 51
      for (NodeIt trg(digraph); trg != INVALID; ++trg) {
52 52
        for (ConArcIt<Digraph> con(digraph, src, trg); con != INVALID; ++con) {
53 53
          check(digraph.source(con) == src, "Wrong source.");
54 54
          check(digraph.target(con) == trg, "Wrong target.");
55 55
          check(found[con] == false, "The arc found already.");
56 56
          found[con] = true;
57 57
        }
58 58
      }
59 59
    }
60 60
    for (ArcIt it(digraph); it != INVALID; ++it) {
61 61
      check(found[it] == true, "The arc is not found.");
62 62
    }
63 63
  }
64 64

	
65 65
  {
66 66
    int num = 5;
67 67
    Digraph fg;
68 68
    std::vector<Node> nodes;
69 69
    for (int i = 0; i < num; ++i) {
70 70
      nodes.push_back(fg.addNode());
71 71
    }
72 72
    for (int i = 0; i < num * num; ++i) {
73 73
      fg.addArc(nodes[i / num], nodes[i % num]);
74 74
    }
75 75
    check(countNodes(fg) == num, "Wrong node number.");
76 76
    check(countArcs(fg) == num*num, "Wrong arc number.");
77 77
    for (NodeIt src(fg); src != INVALID; ++src) {
78 78
      for (NodeIt trg(fg); trg != INVALID; ++trg) {
79 79
        ConArcIt<Digraph> con(fg, src, trg);
80 80
        check(con != INVALID, "There is no connecting arc.");
81 81
        check(fg.source(con) == src, "Wrong source.");
82 82
        check(fg.target(con) == trg, "Wrong target.");
83 83
        check(++con == INVALID, "There is more connecting arc.");
84 84
      }
85 85
    }
86 86
    ArcLookUp<Digraph> al1(fg);
87 87
    DynArcLookUp<Digraph> al2(fg);
88 88
    AllArcLookUp<Digraph> al3(fg);
89 89
    for (NodeIt src(fg); src != INVALID; ++src) {
90 90
      for (NodeIt trg(fg); trg != INVALID; ++trg) {
91 91
        Arc con1 = al1(src, trg);
92 92
        Arc con2 = al2(src, trg);
93 93
        Arc con3 = al3(src, trg);
94 94
        Arc con4 = findArc(fg, src, trg);
95 95
        check(con1 == con2 && con2 == con3 && con3 == con4,
96 96
              "Different results.")
97 97
        check(con1 != INVALID, "There is no connecting arc.");
98 98
        check(fg.source(con1) == src, "Wrong source.");
99 99
        check(fg.target(con1) == trg, "Wrong target.");
100 100
        check(al3(src, trg, con3) == INVALID,
101 101
              "There is more connecting arc.");
102 102
        check(findArc(fg, src, trg, con4) == INVALID,
103 103
              "There is more connecting arc.");
104 104
      }
105 105
    }
106 106
  }
107 107
}
108 108

	
109 109
template <typename Graph>
110 110
void checkFindEdges() {
111 111
  TEMPLATE_GRAPH_TYPEDEFS(Graph);
112 112
  Graph graph;
113 113
  for (int i = 0; i < 10; ++i) {
114 114
    graph.addNode();
115 115
  }
116 116
  DescriptorMap<Graph, Node> nodes(graph);
117 117
  typename DescriptorMap<Graph, Node>::InverseMap invNodes(nodes);
118 118
  for (int i = 0; i < 100; ++i) {
119 119
    int src = rnd[invNodes.size()];
120 120
    int trg = rnd[invNodes.size()];
121 121
    graph.addEdge(invNodes[src], invNodes[trg]);
122 122
  }
123 123
  typename Graph::template EdgeMap<int> found(graph, 0);
124 124
  DescriptorMap<Graph, Edge> edges(graph);
125 125
  for (NodeIt src(graph); src != INVALID; ++src) {
126 126
    for (NodeIt trg(graph); trg != INVALID; ++trg) {
127 127
      for (ConEdgeIt<Graph> con(graph, src, trg); con != INVALID; ++con) {
128 128
        check( (graph.u(con) == src && graph.v(con) == trg) ||
129 129
               (graph.v(con) == src && graph.u(con) == trg),
130 130
               "Wrong end nodes.");
131 131
        ++found[con];
132 132
        check(found[con] <= 2, "The edge found more than twice.");
133 133
      }
134 134
    }
135 135
  }
136 136
  for (EdgeIt it(graph); it != INVALID; ++it) {
137 137
    check( (graph.u(it) != graph.v(it) && found[it] == 2) ||
138 138
           (graph.u(it) == graph.v(it) && found[it] == 1),
139 139
           "The edge is not found correctly.");
140 140
  }
141 141
}
142 142

	
143 143
template <class Digraph>
144 144
void checkDeg()
145 145
{
146 146
  TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
147 147

	
148 148
  const int nodeNum = 10;
149 149
  const int arcNum = 100;
150 150
  Digraph digraph;
151 151
  InDegMap<Digraph> inDeg(digraph);
152 152
  OutDegMap<Digraph> outDeg(digraph);
153 153
  std::vector<Node> nodes(nodeNum);
154 154
  for (int i = 0; i < nodeNum; ++i) {
155 155
    nodes[i] = digraph.addNode();
156 156
  }
157 157
  std::vector<Arc> arcs(arcNum);
158 158
  for (int i = 0; i < arcNum; ++i) {
159 159
    arcs[i] = digraph.addArc(nodes[rnd[nodeNum]], nodes[rnd[nodeNum]]);
160 160
  }
161 161
  for (int i = 0; i < nodeNum; ++i) {
162 162
    check(inDeg[nodes[i]] == countInArcs(digraph, nodes[i]),
163 163
          "Wrong in degree map");
164 164
  }
165 165
  for (int i = 0; i < nodeNum; ++i) {
166 166
    check(outDeg[nodes[i]] == countOutArcs(digraph, nodes[i]),
167 167
          "Wrong out degree map");
168 168
  }
169 169
}
170 170

	
171 171
template <class Digraph>
172 172
void checkSnapDeg()
173 173
{
174 174
  TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
175 175

	
176 176
  Digraph g;
177 177
  Node n1=g.addNode();
178 178
  Node n2=g.addNode();
179 179

	
180 180
  InDegMap<Digraph> ind(g);
181 181

	
182 182
  g.addArc(n1,n2);
183 183

	
184 184
  typename Digraph::Snapshot snap(g);
185 185

	
186 186
  OutDegMap<Digraph> outd(g);
187 187

	
188 188
  check(ind[n1]==0 && ind[n2]==1, "Wrong InDegMap value.");
189 189
  check(outd[n1]==1 && outd[n2]==0, "Wrong OutDegMap value.");
190 190

	
191 191
  g.addArc(n1,n2);
192 192
  g.addArc(n2,n1);
193 193

	
194 194
  check(ind[n1]==1 && ind[n2]==2, "Wrong InDegMap value.");
195 195
  check(outd[n1]==2 && outd[n2]==1, "Wrong OutDegMap value.");
196 196

	
197 197
  snap.restore();
198 198

	
199 199
  check(ind[n1]==0 && ind[n2]==1, "Wrong InDegMap value.");
200 200
  check(outd[n1]==1 && outd[n2]==0, "Wrong OutDegMap value.");
201 201
}
202 202

	
203 203
int main() {
204 204
  // Checking ConArcIt, ConEdgeIt, ArcLookUp, AllArcLookUp, and DynArcLookUp
205 205
  checkFindArcs<ListDigraph>();
206 206
  checkFindArcs<SmartDigraph>();
207 207
  checkFindEdges<ListGraph>();
208 208
  checkFindEdges<SmartGraph>();
209 209

	
210 210
  // Checking In/OutDegMap (and Snapshot feature)
211 211
  checkDeg<ListDigraph>();
212 212
  checkDeg<SmartDigraph>();
213 213
  checkSnapDeg<ListDigraph>();
214 214
  checkSnapDeg<SmartDigraph>();
215 215

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

	
19
#ifndef LEMON_BITS_INVALID_H
20
#define LEMON_BITS_INVALID_H
21

	
22
///\file
23
///\brief Definition of INVALID.
24

	
25
namespace lemon {
26

	
27
  /// \brief Dummy type to make it easier to create invalid iterators.
28
  ///
29
  /// Dummy type to make it easier to create invalid iterators.
30
  /// See \ref INVALID for the usage.
31
  struct Invalid {
32
  public:
33
    bool operator==(Invalid) { return true;  }
34
    bool operator!=(Invalid) { return false; }
35
    bool operator< (Invalid) { return false; }
36
  };
37

	
38
  /// \brief Invalid iterators.
39
  ///
40
  /// \ref Invalid is a global type that converts to each iterator
41
  /// in such a way that the value of the target iterator will be invalid.
42

	
43
  //Some people didn't like this:
44
  //const Invalid &INVALID = *(Invalid *)0;
45

	
46
#ifdef LEMON_ONLY_TEMPLATES
47
  const Invalid INVALID = Invalid();
48
#else
49
  extern const Invalid INVALID;
50
#endif
51

	
52
} //namespace lemon
53

	
54
#endif
55

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

	
19
// This file contains a modified version of the enable_if library from BOOST.
20
// See the appropriate copyright notice below.
21

	
22
// Boost enable_if library
23

	
24
// Copyright 2003 (c) The Trustees of Indiana University.
25

	
26
// Use, modification, and distribution is subject to the Boost Software
27
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
28
// http://www.boost.org/LICENSE_1_0.txt)
29

	
30
//    Authors: Jaakko Jarvi (jajarvi at osl.iu.edu)
31
//             Jeremiah Willcock (jewillco at osl.iu.edu)
32
//             Andrew Lumsdaine (lums at osl.iu.edu)
33

	
34

	
35
#ifndef LEMON_BITS_UTILITY_H
36
#define LEMON_BITS_UTILITY_H
37

	
38
///\file
39
///\brief Miscellaneous basic utilities
40
///
41
///\todo Please rethink the organisation of the basic files like this.
42
///E.g. this file might be merged with invalid.h.
43

	
44

	
45
namespace lemon
46
{
47

	
48
  /// Basic type for defining "tags". A "YES" condition for \c enable_if.
49

	
50
  /// Basic type for defining "tags". A "YES" condition for \c enable_if.
51
  ///
52
  ///\sa False
53
  ///
54
  /// \todo This should go to a separate "basic_types.h" (or something)
55
  /// file.
56
  struct True {
57
    ///\e
58
    static const bool value = true;
59
  };
60

	
61
  /// Basic type for defining "tags". A "NO" condition for \c enable_if.
62

	
63
  /// Basic type for defining "tags". A "NO" condition for \c enable_if.
64
  ///
65
  ///\sa True
66
  struct False {
67
    ///\e
68
    static const bool value = false;
69
  };
70

	
71

	
72
  struct InvalidType {
73
  };
74

	
75
  template <typename T>
76
  struct Wrap {
77
    const T &value;
78
    Wrap(const T &t) : value(t) {}
79
  };
80

	
81
  /**************** dummy class to avoid ambiguity ****************/
82

	
83
  template<int T> struct dummy { dummy(int) {} };
84

	
85
  /**************** enable_if from BOOST ****************/
86

	
87
  template <typename Type, typename T = void>
88
  struct exists {
89
    typedef T type;
90
  };
91

	
92

	
93
  template <bool B, class T = void>
94
  struct enable_if_c {
95
    typedef T type;
96
  };
97

	
98
  template <class T>
99
  struct enable_if_c<false, T> {};
100

	
101
  template <class Cond, class T = void>
102
  struct enable_if : public enable_if_c<Cond::value, T> {};
103

	
104
  template <bool B, class T>
105
  struct lazy_enable_if_c {
106
    typedef typename T::type type;
107
  };
108

	
109
  template <class T>
110
  struct lazy_enable_if_c<false, T> {};
111

	
112
  template <class Cond, class T>
113
  struct lazy_enable_if : public lazy_enable_if_c<Cond::value, T> {};
114

	
115

	
116
  template <bool B, class T = void>
117
  struct disable_if_c {
118
    typedef T type;
119
  };
120

	
121
  template <class T>
122
  struct disable_if_c<true, T> {};
123

	
124
  template <class Cond, class T = void>
125
  struct disable_if : public disable_if_c<Cond::value, T> {};
126

	
127
  template <bool B, class T>
128
  struct lazy_disable_if_c {
129
    typedef typename T::type type;
130
  };
131

	
132
  template <class T>
133
  struct lazy_disable_if_c<true, T> {};
134

	
135
  template <class Cond, class T>
136
  struct lazy_disable_if : public lazy_disable_if_c<Cond::value, T> {};
137

	
138
} // namespace lemon
139

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

	
19
#ifndef LEMON_GRAPH_UTILS_H
20
#define LEMON_GRAPH_UTILS_H
21

	
22
#include <iterator>
23
#include <vector>
24
#include <map>
25
#include <cmath>
26
#include <algorithm>
27

	
28
#include <lemon/bits/invalid.h>
29
#include <lemon/bits/utility.h>
30
#include <lemon/maps.h>
31
#include <lemon/bits/traits.h>
32

	
33
#include <lemon/bits/alteration_notifier.h>
34
#include <lemon/bits/default_map.h>
35

	
36
///\ingroup gutils
37
///\file
38
///\brief Graph utilities.
39

	
40
namespace lemon {
41

	
42
  /// \addtogroup gutils
43
  /// @{
44

	
45
  ///Creates convenience typedefs for the digraph types and iterators
46

	
47
  ///This \c \#define creates convenience typedefs for the following types
48
  ///of \c Digraph: \c Node,  \c NodeIt, \c Arc, \c ArcIt, \c InArcIt,
49
  ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap,
50
  ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap.
51
  ///
52
  ///\note If the graph type is a dependent type, ie. the graph type depend
53
  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
54
  ///macro.
55
#define DIGRAPH_TYPEDEFS(Digraph)                                       \
56
  typedef Digraph::Node Node;                                           \
57
  typedef Digraph::NodeIt NodeIt;                                       \
58
  typedef Digraph::Arc Arc;                                             \
59
  typedef Digraph::ArcIt ArcIt;                                         \
60
  typedef Digraph::InArcIt InArcIt;                                     \
61
  typedef Digraph::OutArcIt OutArcIt;                                   \
62
  typedef Digraph::NodeMap<bool> BoolNodeMap;                           \
63
  typedef Digraph::NodeMap<int> IntNodeMap;                             \
64
  typedef Digraph::NodeMap<double> DoubleNodeMap;                       \
65
  typedef Digraph::ArcMap<bool> BoolArcMap;                             \
66
  typedef Digraph::ArcMap<int> IntArcMap;                               \
67
  typedef Digraph::ArcMap<double> DoubleArcMap
68

	
69
  ///Creates convenience typedefs for the digraph types and iterators
70

	
71
  ///\see DIGRAPH_TYPEDEFS
72
  ///
73
  ///\note Use this macro, if the graph type is a dependent type,
74
  ///ie. the graph type depend on a template parameter.
75
#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph)                              \
76
  typedef typename Digraph::Node Node;                                  \
77
  typedef typename Digraph::NodeIt NodeIt;                              \
78
  typedef typename Digraph::Arc Arc;                                    \
79
  typedef typename Digraph::ArcIt ArcIt;                                \
80
  typedef typename Digraph::InArcIt InArcIt;                            \
81
  typedef typename Digraph::OutArcIt OutArcIt;                          \
82
  typedef typename Digraph::template NodeMap<bool> BoolNodeMap;         \
83
  typedef typename Digraph::template NodeMap<int> IntNodeMap;           \
84
  typedef typename Digraph::template NodeMap<double> DoubleNodeMap;     \
85
  typedef typename Digraph::template ArcMap<bool> BoolArcMap;           \
86
  typedef typename Digraph::template ArcMap<int> IntArcMap;             \
87
  typedef typename Digraph::template ArcMap<double> DoubleArcMap
88

	
89
  ///Creates convenience typedefs for the graph types and iterators
90

	
91
  ///This \c \#define creates the same convenience typedefs as defined
92
  ///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates
93
  ///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap,
94
  ///\c DoubleEdgeMap.
95
  ///
96
  ///\note If the graph type is a dependent type, ie. the graph type depend
97
  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
98
  ///macro.
99
#define GRAPH_TYPEDEFS(Graph)                                           \
100
  DIGRAPH_TYPEDEFS(Graph);                                              \
101
  typedef Graph::Edge Edge;                                             \
102
  typedef Graph::EdgeIt EdgeIt;                                         \
103
  typedef Graph::IncEdgeIt IncEdgeIt;                                   \
104
  typedef Graph::EdgeMap<bool> BoolEdgeMap;                             \
105
  typedef Graph::EdgeMap<int> IntEdgeMap;                               \
106
  typedef Graph::EdgeMap<double> DoubleEdgeMap
107

	
108
  ///Creates convenience typedefs for the graph types and iterators
109

	
110
  ///\see GRAPH_TYPEDEFS
111
  ///
112
  ///\note Use this macro, if the graph type is a dependent type,
113
  ///ie. the graph type depend on a template parameter.
114
#define TEMPLATE_GRAPH_TYPEDEFS(Graph)                                  \
115
  TEMPLATE_DIGRAPH_TYPEDEFS(Graph);                                     \
116
  typedef typename Graph::Edge Edge;                                    \
117
  typedef typename Graph::EdgeIt EdgeIt;                                \
118
  typedef typename Graph::IncEdgeIt IncEdgeIt;                          \
119
  typedef typename Graph::template EdgeMap<bool> BoolEdgeMap;           \
120
  typedef typename Graph::template EdgeMap<int> IntEdgeMap;             \
121
  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
122

	
123
  /// \brief Function to count the items in the graph.
124
  ///
125
  /// This function counts the items (nodes, arcs etc) in the graph.
126
  /// The complexity of the function is O(n) because
127
  /// it iterates on all of the items.
128
  template <typename Graph, typename Item>
129
  inline int countItems(const Graph& g) {
130
    typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt;
131
    int num = 0;
132
    for (ItemIt it(g); it != INVALID; ++it) {
133
      ++num;
134
    }
135
    return num;
136
  }
137

	
138
  // Node counting:
139

	
140
  namespace _graph_utils_bits {
141

	
142
    template <typename Graph, typename Enable = void>
143
    struct CountNodesSelector {
144
      static int count(const Graph &g) {
145
        return countItems<Graph, typename Graph::Node>(g);
146
      }
147
    };
148

	
149
    template <typename Graph>
150
    struct CountNodesSelector<
151
      Graph, typename
152
      enable_if<typename Graph::NodeNumTag, void>::type>
153
    {
154
      static int count(const Graph &g) {
155
        return g.nodeNum();
156
      }
157
    };
158
  }
159

	
160
  /// \brief Function to count the nodes in the graph.
161
  ///
162
  /// This function counts the nodes in the graph.
163
  /// The complexity of the function is O(n) but for some
164
  /// graph structures it is specialized to run in O(1).
165
  ///
166
  /// If the graph contains a \e nodeNum() member function and a
167
  /// \e NodeNumTag tag then this function calls directly the member
168
  /// function to query the cardinality of the node set.
169
  template <typename Graph>
170
  inline int countNodes(const Graph& g) {
171
    return _graph_utils_bits::CountNodesSelector<Graph>::count(g);
172
  }
173

	
174
  // Arc counting:
175

	
176
  namespace _graph_utils_bits {
177

	
178
    template <typename Graph, typename Enable = void>
179
    struct CountArcsSelector {
180
      static int count(const Graph &g) {
181
        return countItems<Graph, typename Graph::Arc>(g);
182
      }
183
    };
184

	
185
    template <typename Graph>
186
    struct CountArcsSelector<
187
      Graph,
188
      typename enable_if<typename Graph::ArcNumTag, void>::type>
189
    {
190
      static int count(const Graph &g) {
191
        return g.arcNum();
192
      }
193
    };
194
  }
195

	
196
  /// \brief Function to count the arcs in the graph.
197
  ///
198
  /// This function counts the arcs in the graph.
199
  /// The complexity of the function is O(e) but for some
200
  /// graph structures it is specialized to run in O(1).
201
  ///
202
  /// If the graph contains a \e arcNum() member function and a
203
  /// \e EdgeNumTag tag then this function calls directly the member
204
  /// function to query the cardinality of the arc set.
205
  template <typename Graph>
206
  inline int countArcs(const Graph& g) {
207
    return _graph_utils_bits::CountArcsSelector<Graph>::count(g);
208
  }
209

	
210
  // Edge counting:
211
  namespace _graph_utils_bits {
212

	
213
    template <typename Graph, typename Enable = void>
214
    struct CountEdgesSelector {
215
      static int count(const Graph &g) {
216
        return countItems<Graph, typename Graph::Edge>(g);
217
      }
218
    };
219

	
220
    template <typename Graph>
221
    struct CountEdgesSelector<
222
      Graph,
223
      typename enable_if<typename Graph::EdgeNumTag, void>::type>
224
    {
225
      static int count(const Graph &g) {
226
        return g.edgeNum();
227
      }
228
    };
229
  }
230

	
231
  /// \brief Function to count the edges in the graph.
232
  ///
233
  /// This function counts the edges in the graph.
234
  /// The complexity of the function is O(m) but for some
235
  /// graph structures it is specialized to run in O(1).
236
  ///
237
  /// If the graph contains a \e edgeNum() member function and a
238
  /// \e EdgeNumTag tag then this function calls directly the member
239
  /// function to query the cardinality of the edge set.
240
  template <typename Graph>
241
  inline int countEdges(const Graph& g) {
242
    return _graph_utils_bits::CountEdgesSelector<Graph>::count(g);
243

	
244
  }
245

	
246

	
247
  template <typename Graph, typename DegIt>
248
  inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
249
    int num = 0;
250
    for (DegIt it(_g, _n); it != INVALID; ++it) {
251
      ++num;
252
    }
253
    return num;
254
  }
255

	
256
  /// \brief Function to count the number of the out-arcs from node \c n.
257
  ///
258
  /// This function counts the number of the out-arcs from node \c n
259
  /// in the graph.
260
  template <typename Graph>
261
  inline int countOutArcs(const Graph& _g,  const typename Graph::Node& _n) {
262
    return countNodeDegree<Graph, typename Graph::OutArcIt>(_g, _n);
263
  }
264

	
265
  /// \brief Function to count the number of the in-arcs to node \c n.
266
  ///
267
  /// This function counts the number of the in-arcs to node \c n
268
  /// in the graph.
269
  template <typename Graph>
270
  inline int countInArcs(const Graph& _g,  const typename Graph::Node& _n) {
271
    return countNodeDegree<Graph, typename Graph::InArcIt>(_g, _n);
272
  }
273

	
274
  /// \brief Function to count the number of the inc-edges to node \c n.
275
  ///
276
  /// This function counts the number of the inc-edges to node \c n
277
  /// in the graph.
278
  template <typename Graph>
279
  inline int countIncEdges(const Graph& _g,  const typename Graph::Node& _n) {
280
    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(_g, _n);
281
  }
282

	
283
  namespace _graph_utils_bits {
284

	
285
    template <typename Graph, typename Enable = void>
286
    struct FindArcSelector {
287
      typedef typename Graph::Node Node;
288
      typedef typename Graph::Arc Arc;
289
      static Arc find(const Graph &g, Node u, Node v, Arc e) {
290
        if (e == INVALID) {
291
          g.firstOut(e, u);
292
        } else {
293
          g.nextOut(e);
294
        }
295
        while (e != INVALID && g.target(e) != v) {
296
          g.nextOut(e);
297
        }
298
        return e;
299
      }
300
    };
301

	
302
    template <typename Graph>
303
    struct FindArcSelector<
304
      Graph,
305
      typename enable_if<typename Graph::FindEdgeTag, void>::type>
306
    {
307
      typedef typename Graph::Node Node;
308
      typedef typename Graph::Arc Arc;
309
      static Arc find(const Graph &g, Node u, Node v, Arc prev) {
310
        return g.findArc(u, v, prev);
311
      }
312
    };
313
  }
314

	
315
  /// \brief Finds an arc between two nodes of a graph.
316
  ///
317
  /// Finds an arc from node \c u to node \c v in graph \c g.
318
  ///
319
  /// If \c prev is \ref INVALID (this is the default value), then
320
  /// it finds the first arc from \c u to \c v. Otherwise it looks for
321
  /// the next arc from \c u to \c v after \c prev.
322
  /// \return The found arc or \ref INVALID if there is no such an arc.
323
  ///
324
  /// Thus you can iterate through each arc from \c u to \c v as it follows.
325
  ///\code
326
  /// for(Arc e=findArc(g,u,v);e!=INVALID;e=findArc(g,u,v,e)) {
327
  ///   ...
328
  /// }
329
  ///\endcode
330
  ///
331
  ///\sa ArcLookUp
332
  ///\sa AllArcLookUp
333
  ///\sa DynArcLookUp
334
  ///\sa ConArcIt
335
  template <typename Graph>
336
  inline typename Graph::Arc
337
  findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v,
338
           typename Graph::Arc prev = INVALID) {
339
    return _graph_utils_bits::FindArcSelector<Graph>::find(g, u, v, prev);
340
  }
341

	
342
  /// \brief Iterator for iterating on arcs connected the same nodes.
343
  ///
344
  /// Iterator for iterating on arcs connected the same nodes. It is
345
  /// higher level interface for the findArc() function. You can
346
  /// use it the following way:
347
  ///\code
348
  /// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) {
349
  ///   ...
350
  /// }
351
  ///\endcode
352
  ///
353
  ///\sa findArc()
354
  ///\sa ArcLookUp
355
  ///\sa AllArcLookUp
356
  ///\sa DynArcLookUp
357
  template <typename _Graph>
358
  class ConArcIt : public _Graph::Arc {
359
  public:
360

	
361
    typedef _Graph Graph;
362
    typedef typename Graph::Arc Parent;
363

	
364
    typedef typename Graph::Arc Arc;
365
    typedef typename Graph::Node Node;
366

	
367
    /// \brief Constructor.
368
    ///
369
    /// Construct a new ConArcIt iterating on the arcs which
370
    /// connects the \c u and \c v node.
371
    ConArcIt(const Graph& g, Node u, Node v) : _graph(g) {
372
      Parent::operator=(findArc(_graph, u, v));
373
    }
374

	
375
    /// \brief Constructor.
376
    ///
377
    /// Construct a new ConArcIt which continues the iterating from
378
    /// the \c e arc.
379
    ConArcIt(const Graph& g, Arc a) : Parent(a), _graph(g) {}
380

	
381
    /// \brief Increment operator.
382
    ///
383
    /// It increments the iterator and gives back the next arc.
384
    ConArcIt& operator++() {
385
      Parent::operator=(findArc(_graph, _graph.source(*this),
386
                                _graph.target(*this), *this));
387
      return *this;
388
    }
389
  private:
390
    const Graph& _graph;
391
  };
392

	
393
  namespace _graph_utils_bits {
394

	
395
    template <typename Graph, typename Enable = void>
396
    struct FindEdgeSelector {
397
      typedef typename Graph::Node Node;
398
      typedef typename Graph::Edge Edge;
399
      static Edge find(const Graph &g, Node u, Node v, Edge e) {
400
        bool b;
401
        if (u != v) {
402
          if (e == INVALID) {
403
            g.firstInc(e, b, u);
404
          } else {
405
            b = g.u(e) == u;
406
            g.nextInc(e, b);
407
          }
408
          while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) {
409
            g.nextInc(e, b);
410
          }
411
        } else {
412
          if (e == INVALID) {
413
            g.firstInc(e, b, u);
414
          } else {
415
            b = true;
416
            g.nextInc(e, b);
417
          }
418
          while (e != INVALID && (!b || g.v(e) != v)) {
419
            g.nextInc(e, b);
420
          }
421
        }
422
        return e;
423
      }
424
    };
425

	
426
    template <typename Graph>
427
    struct FindEdgeSelector<
428
      Graph,
429
      typename enable_if<typename Graph::FindEdgeTag, void>::type>
430
    {
431
      typedef typename Graph::Node Node;
432
      typedef typename Graph::Edge Edge;
433
      static Edge find(const Graph &g, Node u, Node v, Edge prev) {
434
        return g.findEdge(u, v, prev);
435
      }
436
    };
437
  }
438

	
439
  /// \brief Finds an edge between two nodes of a graph.
440
  ///
441
  /// Finds an edge from node \c u to node \c v in graph \c g.
442
  /// If the node \c u and node \c v is equal then each loop edge
443
  /// will be enumerated once.
444
  ///
445
  /// If \c prev is \ref INVALID (this is the default value), then
446
  /// it finds the first arc from \c u to \c v. Otherwise it looks for
447
  /// the next arc from \c u to \c v after \c prev.
448
  /// \return The found arc or \ref INVALID if there is no such an arc.
449
  ///
450
  /// Thus you can iterate through each arc from \c u to \c v as it follows.
451
  ///\code
452
  /// for(Edge e = findEdge(g,u,v); e != INVALID;
453
  ///     e = findEdge(g,u,v,e)) {
454
  ///   ...
455
  /// }
456
  ///\endcode
457
  ///
458
  ///\sa ConEdgeIt
459

	
460
  template <typename Graph>
461
  inline typename Graph::Edge
462
  findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v,
463
            typename Graph::Edge p = INVALID) {
464
    return _graph_utils_bits::FindEdgeSelector<Graph>::find(g, u, v, p);
465
  }
466

	
467
  /// \brief Iterator for iterating on edges connected the same nodes.
468
  ///
469
  /// Iterator for iterating on edges connected the same nodes. It is
470
  /// higher level interface for the findEdge() function. You can
471
  /// use it the following way:
472
  ///\code
473
  /// for (ConEdgeIt<Graph> it(g, src, trg); it != INVALID; ++it) {
474
  ///   ...
475
  /// }
476
  ///\endcode
477
  ///
478
  ///\sa findEdge()
479
  template <typename _Graph>
480
  class ConEdgeIt : public _Graph::Edge {
481
  public:
482

	
483
    typedef _Graph Graph;
484
    typedef typename Graph::Edge Parent;
485

	
486
    typedef typename Graph::Edge Edge;
487
    typedef typename Graph::Node Node;
488

	
489
    /// \brief Constructor.
490
    ///
491
    /// Construct a new ConEdgeIt iterating on the edges which
492
    /// connects the \c u and \c v node.
493
    ConEdgeIt(const Graph& g, Node u, Node v) : _graph(g) {
494
      Parent::operator=(findEdge(_graph, u, v));
495
    }
496

	
497
    /// \brief Constructor.
498
    ///
499
    /// Construct a new ConEdgeIt which continues the iterating from
500
    /// the \c e edge.
501
    ConEdgeIt(const Graph& g, Edge e) : Parent(e), _graph(g) {}
502

	
503
    /// \brief Increment operator.
504
    ///
505
    /// It increments the iterator and gives back the next edge.
506
    ConEdgeIt& operator++() {
507
      Parent::operator=(findEdge(_graph, _graph.u(*this),
508
                                 _graph.v(*this), *this));
509
      return *this;
510
    }
511
  private:
512
    const Graph& _graph;
513
  };
514

	
515
  namespace _graph_utils_bits {
516

	
517
    template <typename Digraph, typename Item, typename RefMap>
518
    class MapCopyBase {
519
    public:
520
      virtual void copy(const Digraph& from, const RefMap& refMap) = 0;
521

	
522
      virtual ~MapCopyBase() {}
523
    };
524

	
525
    template <typename Digraph, typename Item, typename RefMap,
526
              typename ToMap, typename FromMap>
527
    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
528
    public:
529

	
530
      MapCopy(ToMap& tmap, const FromMap& map)
531
        : _tmap(tmap), _map(map) {}
532

	
533
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
534
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
535
        for (ItemIt it(digraph); it != INVALID; ++it) {
536
          _tmap.set(refMap[it], _map[it]);
537
        }
538
      }
539

	
540
    private:
541
      ToMap& _tmap;
542
      const FromMap& _map;
543
    };
544

	
545
    template <typename Digraph, typename Item, typename RefMap, typename It>
546
    class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> {
547
    public:
548

	
549
      ItemCopy(It& it, const Item& item) : _it(it), _item(item) {}
550

	
551
      virtual void copy(const Digraph&, const RefMap& refMap) {
552
        _it = refMap[_item];
553
      }
554

	
555
    private:
556
      It& _it;
557
      Item _item;
558
    };
559

	
560
    template <typename Digraph, typename Item, typename RefMap, typename Ref>
561
    class RefCopy : public MapCopyBase<Digraph, Item, RefMap> {
562
    public:
563

	
564
      RefCopy(Ref& map) : _map(map) {}
565

	
566
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
567
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
568
        for (ItemIt it(digraph); it != INVALID; ++it) {
569
          _map.set(it, refMap[it]);
570
        }
571
      }
572

	
573
    private:
574
      Ref& _map;
575
    };
576

	
577
    template <typename Digraph, typename Item, typename RefMap,
578
              typename CrossRef>
579
    class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> {
580
    public:
581

	
582
      CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {}
583

	
584
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
585
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
586
        for (ItemIt it(digraph); it != INVALID; ++it) {
587
          _cmap.set(refMap[it], it);
588
        }
589
      }
590

	
591
    private:
592
      CrossRef& _cmap;
593
    };
594

	
595
    template <typename Digraph, typename Enable = void>
596
    struct DigraphCopySelector {
597
      template <typename From, typename NodeRefMap, typename ArcRefMap>
598
      static void copy(Digraph &to, const From& from,
599
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
600
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
601
          nodeRefMap[it] = to.addNode();
602
        }
603
        for (typename From::ArcIt it(from); it != INVALID; ++it) {
604
          arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)],
605
                                    nodeRefMap[from.target(it)]);
606
        }
607
      }
608
    };
609

	
610
    template <typename Digraph>
611
    struct DigraphCopySelector<
612
      Digraph,
613
      typename enable_if<typename Digraph::BuildTag, void>::type>
614
    {
615
      template <typename From, typename NodeRefMap, typename ArcRefMap>
616
      static void copy(Digraph &to, const From& from,
617
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
618
        to.build(from, nodeRefMap, arcRefMap);
619
      }
620
    };
621

	
622
    template <typename Graph, typename Enable = void>
623
    struct GraphCopySelector {
624
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
625
      static void copy(Graph &to, const From& from,
626
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
627
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
628
          nodeRefMap[it] = to.addNode();
629
        }
630
        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
631
          edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)],
632
                                      nodeRefMap[from.v(it)]);
633
        }
634
      }
635
    };
636

	
637
    template <typename Graph>
638
    struct GraphCopySelector<
639
      Graph,
640
      typename enable_if<typename Graph::BuildTag, void>::type>
641
    {
642
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
643
      static void copy(Graph &to, const From& from,
644
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
645
        to.build(from, nodeRefMap, edgeRefMap);
646
      }
647
    };
648

	
649
  }
650

	
651
  /// \brief Class to copy a digraph.
652
  ///
653
  /// Class to copy a digraph to another digraph (duplicate a digraph). The
654
  /// simplest way of using it is through the \c copyDigraph() function.
655
  ///
656
  /// This class not just make a copy of a graph, but it can create
657
  /// references and cross references between the nodes and arcs of
658
  /// the two graphs, it can copy maps for use with the newly created
659
  /// graph and copy nodes and arcs.
660
  ///
661
  /// To make a copy from a graph, first an instance of DigraphCopy
662
  /// should be created, then the data belongs to the graph should
663
  /// assigned to copy. In the end, the \c run() member should be
664
  /// called.
665
  ///
666
  /// The next code copies a graph with several data:
667
  ///\code
668
  ///  DigraphCopy<NewGraph, OrigGraph> dc(new_graph, orig_graph);
669
  ///  // create a reference for the nodes
670
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
671
  ///  dc.nodeRef(nr);
672
  ///  // create a cross reference (inverse) for the arcs
673
  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
674
  ///  dc.arcCrossRef(acr);
675
  ///  // copy an arc map
676
  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
677
  ///  NewGraph::ArcMap<double> namap(new_graph);
678
  ///  dc.arcMap(namap, oamap);
679
  ///  // copy a node
680
  ///  OrigGraph::Node on;
681
  ///  NewGraph::Node nn;
682
  ///  dc.node(nn, on);
683
  ///  // Executions of copy
684
  ///  dc.run();
685
  ///\endcode
686
  template <typename To, typename From>
687
  class DigraphCopy {
688
  private:
689

	
690
    typedef typename From::Node Node;
691
    typedef typename From::NodeIt NodeIt;
692
    typedef typename From::Arc Arc;
693
    typedef typename From::ArcIt ArcIt;
694

	
695
    typedef typename To::Node TNode;
696
    typedef typename To::Arc TArc;
697

	
698
    typedef typename From::template NodeMap<TNode> NodeRefMap;
699
    typedef typename From::template ArcMap<TArc> ArcRefMap;
700

	
701

	
702
  public:
703

	
704

	
705
    /// \brief Constructor for the DigraphCopy.
706
    ///
707
    /// It copies the content of the \c _from digraph into the
708
    /// \c _to digraph.
709
    DigraphCopy(To& to, const From& from)
710
      : _from(from), _to(to) {}
711

	
712
    /// \brief Destructor of the DigraphCopy
713
    ///
714
    /// Destructor of the DigraphCopy
715
    ~DigraphCopy() {
716
      for (int i = 0; i < int(_node_maps.size()); ++i) {
717
        delete _node_maps[i];
718
      }
719
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
720
        delete _arc_maps[i];
721
      }
722

	
723
    }
724

	
725
    /// \brief Copies the node references into the given map.
726
    ///
727
    /// Copies the node references into the given map. The parameter
728
    /// should be a map, which key type is the Node type of the source
729
    /// graph, while the value type is the Node type of the
730
    /// destination graph.
731
    template <typename NodeRef>
732
    DigraphCopy& nodeRef(NodeRef& map) {
733
      _node_maps.push_back(new _graph_utils_bits::RefCopy<From, Node,
734
                           NodeRefMap, NodeRef>(map));
735
      return *this;
736
    }
737

	
738
    /// \brief Copies the node cross references into the given map.
739
    ///
740
    ///  Copies the node cross references (reverse references) into
741
    ///  the given map. The parameter should be a map, which key type
742
    ///  is the Node type of the destination graph, while the value type is
743
    ///  the Node type of the source graph.
744
    template <typename NodeCrossRef>
745
    DigraphCopy& nodeCrossRef(NodeCrossRef& map) {
746
      _node_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Node,
747
                           NodeRefMap, NodeCrossRef>(map));
748
      return *this;
749
    }
750

	
751
    /// \brief Make copy of the given map.
752
    ///
753
    /// Makes copy of the given map for the newly created digraph.
754
    /// The new map's key type is the destination graph's node type,
755
    /// and the copied map's key type is the source graph's node type.
756
    template <typename ToMap, typename FromMap>
757
    DigraphCopy& nodeMap(ToMap& tmap, const FromMap& map) {
758
      _node_maps.push_back(new _graph_utils_bits::MapCopy<From, Node,
759
                           NodeRefMap, ToMap, FromMap>(tmap, map));
760
      return *this;
761
    }
762

	
763
    /// \brief Make a copy of the given node.
764
    ///
765
    /// Make a copy of the given node.
766
    DigraphCopy& node(TNode& tnode, const Node& snode) {
767
      _node_maps.push_back(new _graph_utils_bits::ItemCopy<From, Node,
768
                           NodeRefMap, TNode>(tnode, snode));
769
      return *this;
770
    }
771

	
772
    /// \brief Copies the arc references into the given map.
773
    ///
774
    /// Copies the arc references into the given map.
775
    template <typename ArcRef>
776
    DigraphCopy& arcRef(ArcRef& map) {
777
      _arc_maps.push_back(new _graph_utils_bits::RefCopy<From, Arc,
778
                          ArcRefMap, ArcRef>(map));
779
      return *this;
780
    }
781

	
782
    /// \brief Copies the arc cross references into the given map.
783
    ///
784
    ///  Copies the arc cross references (reverse references) into
785
    ///  the given map.
786
    template <typename ArcCrossRef>
787
    DigraphCopy& arcCrossRef(ArcCrossRef& map) {
788
      _arc_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Arc,
789
                          ArcRefMap, ArcCrossRef>(map));
790
      return *this;
791
    }
792

	
793
    /// \brief Make copy of the given map.
794
    ///
795
    /// Makes copy of the given map for the newly created digraph.
796
    /// The new map's key type is the to digraph's arc type,
797
    /// and the copied map's key type is the from digraph's arc
798
    /// type.
799
    template <typename ToMap, typename FromMap>
800
    DigraphCopy& arcMap(ToMap& tmap, const FromMap& map) {
801
      _arc_maps.push_back(new _graph_utils_bits::MapCopy<From, Arc,
802
                          ArcRefMap, ToMap, FromMap>(tmap, map));
803
      return *this;
804
    }
805

	
806
    /// \brief Make a copy of the given arc.
807
    ///
808
    /// Make a copy of the given arc.
809
    DigraphCopy& arc(TArc& tarc, const Arc& sarc) {
810
      _arc_maps.push_back(new _graph_utils_bits::ItemCopy<From, Arc,
811
                          ArcRefMap, TArc>(tarc, sarc));
812
      return *this;
813
    }
814

	
815
    /// \brief Executes the copies.
816
    ///
817
    /// Executes the copies.
818
    void run() {
819
      NodeRefMap nodeRefMap(_from);
820
      ArcRefMap arcRefMap(_from);
821
      _graph_utils_bits::DigraphCopySelector<To>::
822
        copy(_to, _from, nodeRefMap, arcRefMap);
823
      for (int i = 0; i < int(_node_maps.size()); ++i) {
824
        _node_maps[i]->copy(_from, nodeRefMap);
825
      }
826
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
827
        _arc_maps[i]->copy(_from, arcRefMap);
828
      }
829
    }
830

	
831
  protected:
832

	
833

	
834
    const From& _from;
835
    To& _to;
836

	
837
    std::vector<_graph_utils_bits::MapCopyBase<From, Node, NodeRefMap>* >
838
    _node_maps;
839

	
840
    std::vector<_graph_utils_bits::MapCopyBase<From, Arc, ArcRefMap>* >
841
    _arc_maps;
842

	
843
  };
844

	
845
  /// \brief Copy a digraph to another digraph.
846
  ///
847
  /// Copy a digraph to another digraph. The complete usage of the
848
  /// function is detailed in the DigraphCopy class, but a short
849
  /// example shows a basic work:
850
  ///\code
851
  /// copyDigraph(trg, src).nodeRef(nr).arcCrossRef(ecr).run();
852
  ///\endcode
853
  ///
854
  /// After the copy the \c nr map will contain the mapping from the
855
  /// nodes of the \c from digraph to the nodes of the \c to digraph and
856
  /// \c ecr will contain the mapping from the arcs of the \c to digraph
857
  /// to the arcs of the \c from digraph.
858
  ///
859
  /// \see DigraphCopy
860
  template <typename To, typename From>
861
  DigraphCopy<To, From> copyDigraph(To& to, const From& from) {
862
    return DigraphCopy<To, From>(to, from);
863
  }
864

	
865
  /// \brief Class to copy a graph.
866
  ///
867
  /// Class to copy a graph to another graph (duplicate a graph). The
868
  /// simplest way of using it is through the \c copyGraph() function.
869
  ///
870
  /// This class not just make a copy of a graph, but it can create
871
  /// references and cross references between the nodes, edges and arcs of
872
  /// the two graphs, it can copy maps for use with the newly created
873
  /// graph and copy nodes, edges and arcs.
874
  ///
875
  /// To make a copy from a graph, first an instance of GraphCopy
876
  /// should be created, then the data belongs to the graph should
877
  /// assigned to copy. In the end, the \c run() member should be
878
  /// called.
879
  ///
880
  /// The next code copies a graph with several data:
881
  ///\code
882
  ///  GraphCopy<NewGraph, OrigGraph> dc(new_graph, orig_graph);
883
  ///  // create a reference for the nodes
884
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
885
  ///  dc.nodeRef(nr);
886
  ///  // create a cross reference (inverse) for the edges
887
  ///  NewGraph::EdgeMap<OrigGraph::Arc> ecr(new_graph);
888
  ///  dc.edgeCrossRef(ecr);
889
  ///  // copy an arc map
890
  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
891
  ///  NewGraph::ArcMap<double> namap(new_graph);
892
  ///  dc.arcMap(namap, oamap);
893
  ///  // copy a node
894
  ///  OrigGraph::Node on;
895
  ///  NewGraph::Node nn;
896
  ///  dc.node(nn, on);
897
  ///  // Executions of copy
898
  ///  dc.run();
899
  ///\endcode
900
  template <typename To, typename From>
901
  class GraphCopy {
902
  private:
903

	
904
    typedef typename From::Node Node;
905
    typedef typename From::NodeIt NodeIt;
906
    typedef typename From::Arc Arc;
907
    typedef typename From::ArcIt ArcIt;
908
    typedef typename From::Edge Edge;
909
    typedef typename From::EdgeIt EdgeIt;
910

	
911
    typedef typename To::Node TNode;
912
    typedef typename To::Arc TArc;
913
    typedef typename To::Edge TEdge;
914

	
915
    typedef typename From::template NodeMap<TNode> NodeRefMap;
916
    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
917

	
918
    struct ArcRefMap {
919
      ArcRefMap(const To& to, const From& from,
920
                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
921
        : _to(to), _from(from),
922
          _edge_ref(edge_ref), _node_ref(node_ref) {}
923

	
924
      typedef typename From::Arc Key;
925
      typedef typename To::Arc Value;
926

	
927
      Value operator[](const Key& key) const {
928
        bool forward = _from.u(key) != _from.v(key) ?
929
          _node_ref[_from.source(key)] ==
930
          _to.source(_to.direct(_edge_ref[key], true)) :
931
          _from.direction(key);
932
        return _to.direct(_edge_ref[key], forward);
933
      }
934

	
935
      const To& _to;
936
      const From& _from;
937
      const EdgeRefMap& _edge_ref;
938
      const NodeRefMap& _node_ref;
939
    };
940

	
941

	
942
  public:
943

	
944

	
945
    /// \brief Constructor for the GraphCopy.
946
    ///
947
    /// It copies the content of the \c _from graph into the
948
    /// \c _to graph.
949
    GraphCopy(To& to, const From& from)
950
      : _from(from), _to(to) {}
951

	
952
    /// \brief Destructor of the GraphCopy
953
    ///
954
    /// Destructor of the GraphCopy
955
    ~GraphCopy() {
956
      for (int i = 0; i < int(_node_maps.size()); ++i) {
957
        delete _node_maps[i];
958
      }
959
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
960
        delete _arc_maps[i];
961
      }
962
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
963
        delete _edge_maps[i];
964
      }
965

	
966
    }
967

	
968
    /// \brief Copies the node references into the given map.
969
    ///
970
    /// Copies the node references into the given map.
971
    template <typename NodeRef>
972
    GraphCopy& nodeRef(NodeRef& map) {
973
      _node_maps.push_back(new _graph_utils_bits::RefCopy<From, Node,
974
                           NodeRefMap, NodeRef>(map));
975
      return *this;
976
    }
977

	
978
    /// \brief Copies the node cross references into the given map.
979
    ///
980
    ///  Copies the node cross references (reverse references) into
981
    ///  the given map.
982
    template <typename NodeCrossRef>
983
    GraphCopy& nodeCrossRef(NodeCrossRef& map) {
984
      _node_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Node,
985
                           NodeRefMap, NodeCrossRef>(map));
986
      return *this;
987
    }
988

	
989
    /// \brief Make copy of the given map.
990
    ///
991
    /// Makes copy of the given map for the newly created graph.
992
    /// The new map's key type is the to graph's node type,
993
    /// and the copied map's key type is the from graph's node
994
    /// type.
995
    template <typename ToMap, typename FromMap>
996
    GraphCopy& nodeMap(ToMap& tmap, const FromMap& map) {
997
      _node_maps.push_back(new _graph_utils_bits::MapCopy<From, Node,
998
                           NodeRefMap, ToMap, FromMap>(tmap, map));
999
      return *this;
1000
    }
1001

	
1002
    /// \brief Make a copy of the given node.
1003
    ///
1004
    /// Make a copy of the given node.
1005
    GraphCopy& node(TNode& tnode, const Node& snode) {
1006
      _node_maps.push_back(new _graph_utils_bits::ItemCopy<From, Node,
1007
                           NodeRefMap, TNode>(tnode, snode));
1008
      return *this;
1009
    }
1010

	
1011
    /// \brief Copies the arc references into the given map.
1012
    ///
1013
    /// Copies the arc references into the given map.
1014
    template <typename ArcRef>
1015
    GraphCopy& arcRef(ArcRef& map) {
1016
      _arc_maps.push_back(new _graph_utils_bits::RefCopy<From, Arc,
1017
                          ArcRefMap, ArcRef>(map));
1018
      return *this;
1019
    }
1020

	
1021
    /// \brief Copies the arc cross references into the given map.
1022
    ///
1023
    ///  Copies the arc cross references (reverse references) into
1024
    ///  the given map.
1025
    template <typename ArcCrossRef>
1026
    GraphCopy& arcCrossRef(ArcCrossRef& map) {
1027
      _arc_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Arc,
1028
                          ArcRefMap, ArcCrossRef>(map));
1029
      return *this;
1030
    }
1031

	
1032
    /// \brief Make copy of the given map.
1033
    ///
1034
    /// Makes copy of the given map for the newly created graph.
1035
    /// The new map's key type is the to graph's arc type,
1036
    /// and the copied map's key type is the from graph's arc
1037
    /// type.
1038
    template <typename ToMap, typename FromMap>
1039
    GraphCopy& arcMap(ToMap& tmap, const FromMap& map) {
1040
      _arc_maps.push_back(new _graph_utils_bits::MapCopy<From, Arc,
1041
                          ArcRefMap, ToMap, FromMap>(tmap, map));
1042
      return *this;
1043
    }
1044

	
1045
    /// \brief Make a copy of the given arc.
1046
    ///
1047
    /// Make a copy of the given arc.
1048
    GraphCopy& arc(TArc& tarc, const Arc& sarc) {
1049
      _arc_maps.push_back(new _graph_utils_bits::ItemCopy<From, Arc,
1050
                          ArcRefMap, TArc>(tarc, sarc));
1051
      return *this;
1052
    }
1053

	
1054
    /// \brief Copies the edge references into the given map.
1055
    ///
1056
    /// Copies the edge references into the given map.
1057
    template <typename EdgeRef>
1058
    GraphCopy& edgeRef(EdgeRef& map) {
1059
      _edge_maps.push_back(new _graph_utils_bits::RefCopy<From, Edge,
1060
                           EdgeRefMap, EdgeRef>(map));
1061
      return *this;
1062
    }
1063

	
1064
    /// \brief Copies the edge cross references into the given map.
1065
    ///
1066
    /// Copies the edge cross references (reverse
1067
    /// references) into the given map.
1068
    template <typename EdgeCrossRef>
1069
    GraphCopy& edgeCrossRef(EdgeCrossRef& map) {
1070
      _edge_maps.push_back(new _graph_utils_bits::CrossRefCopy<From,
1071
                           Edge, EdgeRefMap, EdgeCrossRef>(map));
1072
      return *this;
1073
    }
1074

	
1075
    /// \brief Make copy of the given map.
1076
    ///
1077
    /// Makes copy of the given map for the newly created graph.
1078
    /// The new map's key type is the to graph's edge type,
1079
    /// and the copied map's key type is the from graph's edge
1080
    /// type.
1081
    template <typename ToMap, typename FromMap>
1082
    GraphCopy& edgeMap(ToMap& tmap, const FromMap& map) {
1083
      _edge_maps.push_back(new _graph_utils_bits::MapCopy<From, Edge,
1084
                           EdgeRefMap, ToMap, FromMap>(tmap, map));
1085
      return *this;
1086
    }
1087

	
1088
    /// \brief Make a copy of the given edge.
1089
    ///
1090
    /// Make a copy of the given edge.
1091
    GraphCopy& edge(TEdge& tedge, const Edge& sedge) {
1092
      _edge_maps.push_back(new _graph_utils_bits::ItemCopy<From, Edge,
1093
                           EdgeRefMap, TEdge>(tedge, sedge));
1094
      return *this;
1095
    }
1096

	
1097
    /// \brief Executes the copies.
1098
    ///
1099
    /// Executes the copies.
1100
    void run() {
1101
      NodeRefMap nodeRefMap(_from);
1102
      EdgeRefMap edgeRefMap(_from);
1103
      ArcRefMap arcRefMap(_to, _from, edgeRefMap, nodeRefMap);
1104
      _graph_utils_bits::GraphCopySelector<To>::
1105
        copy(_to, _from, nodeRefMap, edgeRefMap);
1106
      for (int i = 0; i < int(_node_maps.size()); ++i) {
1107
        _node_maps[i]->copy(_from, nodeRefMap);
1108
      }
1109
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
1110
        _edge_maps[i]->copy(_from, edgeRefMap);
1111
      }
1112
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
1113
        _arc_maps[i]->copy(_from, arcRefMap);
1114
      }
1115
    }
1116

	
1117
  private:
1118

	
1119
    const From& _from;
1120
    To& _to;
1121

	
1122
    std::vector<_graph_utils_bits::MapCopyBase<From, Node, NodeRefMap>* >
1123
    _node_maps;
1124

	
1125
    std::vector<_graph_utils_bits::MapCopyBase<From, Arc, ArcRefMap>* >
1126
    _arc_maps;
1127

	
1128
    std::vector<_graph_utils_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
1129
    _edge_maps;
1130

	
1131
  };
1132

	
1133
  /// \brief Copy a graph to another graph.
1134
  ///
1135
  /// Copy a graph to another graph. The complete usage of the
1136
  /// function is detailed in the GraphCopy class, but a short
1137
  /// example shows a basic work:
1138
  ///\code
1139
  /// copyGraph(trg, src).nodeRef(nr).arcCrossRef(ecr).run();
1140
  ///\endcode
1141
  ///
1142
  /// After the copy the \c nr map will contain the mapping from the
1143
  /// nodes of the \c from graph to the nodes of the \c to graph and
1144
  /// \c ecr will contain the mapping from the arcs of the \c to graph
1145
  /// to the arcs of the \c from graph.
1146
  ///
1147
  /// \see GraphCopy
1148
  template <typename To, typename From>
1149
  GraphCopy<To, From>
1150
  copyGraph(To& to, const From& from) {
1151
    return GraphCopy<To, From>(to, from);
1152
  }
1153

	
1154
  /// @}
1155

	
1156
  /// \addtogroup graph_maps
1157
  /// @{
1158

	
1159
  /// Provides an immutable and unique id for each item in the graph.
1160

	
1161
  /// The IdMap class provides a unique and immutable id for each item of the
1162
  /// same type (e.g. node) in the graph. This id is <ul><li>\b unique:
1163
  /// different items (nodes) get different ids <li>\b immutable: the id of an
1164
  /// item (node) does not change (even if you delete other nodes).  </ul>
1165
  /// Through this map you get access (i.e. can read) the inner id values of
1166
  /// the items stored in the graph. This map can be inverted with its member
1167
  /// class \c InverseMap or with the \c operator() member.
1168
  ///
1169
  template <typename _Graph, typename _Item>
1170
  class IdMap {
1171
  public:
1172
    typedef _Graph Graph;
1173
    typedef int Value;
1174
    typedef _Item Item;
1175
    typedef _Item Key;
1176

	
1177
    /// \brief Constructor.
1178
    ///
1179
    /// Constructor of the map.
1180
    explicit IdMap(const Graph& graph) : _graph(&graph) {}
1181

	
1182
    /// \brief Gives back the \e id of the item.
1183
    ///
1184
    /// Gives back the immutable and unique \e id of the item.
1185
    int operator[](const Item& item) const { return _graph->id(item);}
1186

	
1187
    /// \brief Gives back the item by its id.
1188
    ///
1189
    /// Gives back the item by its id.
1190
    Item operator()(int id) { return _graph->fromId(id, Item()); }
1191

	
1192
  private:
1193
    const Graph* _graph;
1194

	
1195
  public:
1196

	
1197
    /// \brief The class represents the inverse of its owner (IdMap).
1198
    ///
1199
    /// The class represents the inverse of its owner (IdMap).
1200
    /// \see inverse()
1201
    class InverseMap {
1202
    public:
1203

	
1204
      /// \brief Constructor.
1205
      ///
1206
      /// Constructor for creating an id-to-item map.
1207
      explicit InverseMap(const Graph& graph) : _graph(&graph) {}
1208

	
1209
      /// \brief Constructor.
1210
      ///
1211
      /// Constructor for creating an id-to-item map.
1212
      explicit InverseMap(const IdMap& map) : _graph(map._graph) {}
1213

	
1214
      /// \brief Gives back the given item from its id.
1215
      ///
1216
      /// Gives back the given item from its id.
1217
      ///
1218
      Item operator[](int id) const { return _graph->fromId(id, Item());}
1219

	
1220
    private:
1221
      const Graph* _graph;
1222
    };
1223

	
1224
    /// \brief Gives back the inverse of the map.
1225
    ///
1226
    /// Gives back the inverse of the IdMap.
1227
    InverseMap inverse() const { return InverseMap(*_graph);}
1228

	
1229
  };
1230

	
1231

	
1232
  /// \brief General invertable graph-map type.
1233

	
1234
  /// This type provides simple invertable graph-maps.
1235
  /// The InvertableMap wraps an arbitrary ReadWriteMap
1236
  /// and if a key is set to a new value then store it
1237
  /// in the inverse map.
1238
  ///
1239
  /// The values of the map can be accessed
1240
  /// with stl compatible forward iterator.
1241
  ///
1242
  /// \tparam _Graph The graph type.
1243
  /// \tparam _Item The item type of the graph.
1244
  /// \tparam _Value The value type of the map.
1245
  ///
1246
  /// \see IterableValueMap
1247
  template <typename _Graph, typename _Item, typename _Value>
1248
  class InvertableMap : protected DefaultMap<_Graph, _Item, _Value> {
1249
  private:
1250

	
1251
    typedef DefaultMap<_Graph, _Item, _Value> Map;
1252
    typedef _Graph Graph;
1253

	
1254
    typedef std::map<_Value, _Item> Container;
1255
    Container _inv_map;
1256

	
1257
  public:
1258

	
1259
    /// The key type of InvertableMap (Node, Arc, Edge).
1260
    typedef typename Map::Key Key;
1261
    /// The value type of the InvertableMap.
1262
    typedef typename Map::Value Value;
1263

	
1264

	
1265

	
1266
    /// \brief Constructor.
1267
    ///
1268
    /// Construct a new InvertableMap for the graph.
1269
    ///
1270
    explicit InvertableMap(const Graph& graph) : Map(graph) {}
1271

	
1272
    /// \brief Forward iterator for values.
1273
    ///
1274
    /// This iterator is an stl compatible forward
1275
    /// iterator on the values of the map. The values can
1276
    /// be accessed in the [beginValue, endValue) range.
1277
    ///
1278
    class ValueIterator
1279
      : public std::iterator<std::forward_iterator_tag, Value> {
1280
      friend class InvertableMap;
1281
    private:
1282
      ValueIterator(typename Container::const_iterator _it)
1283
        : it(_it) {}
1284
    public:
1285

	
1286
      ValueIterator() {}
1287

	
1288
      ValueIterator& operator++() { ++it; return *this; }
1289
      ValueIterator operator++(int) {
1290
        ValueIterator tmp(*this);
1291
        operator++();
1292
        return tmp;
1293
      }
1294

	
1295
      const Value& operator*() const { return it->first; }
1296
      const Value* operator->() const { return &(it->first); }
1297

	
1298
      bool operator==(ValueIterator jt) const { return it == jt.it; }
1299
      bool operator!=(ValueIterator jt) const { return it != jt.it; }
1300

	
1301
    private:
1302
      typename Container::const_iterator it;
1303
    };
1304

	
1305
    /// \brief Returns an iterator to the first value.
1306
    ///
1307
    /// Returns an stl compatible iterator to the
1308
    /// first value of the map. The values of the
1309
    /// map can be accessed in the [beginValue, endValue)
1310
    /// range.
1311
    ValueIterator beginValue() const {
1312
      return ValueIterator(_inv_map.begin());
1313
    }
1314

	
1315
    /// \brief Returns an iterator after the last value.
1316
    ///
1317
    /// Returns an stl compatible iterator after the
1318
    /// last value of the map. The values of the
1319
    /// map can be accessed in the [beginValue, endValue)
1320
    /// range.
1321
    ValueIterator endValue() const {
1322
      return ValueIterator(_inv_map.end());
1323
    }
1324

	
1325
    /// \brief The setter function of the map.
1326
    ///
1327
    /// Sets the mapped value.
1328
    void set(const Key& key, const Value& val) {
1329
      Value oldval = Map::operator[](key);
1330
      typename Container::iterator it = _inv_map.find(oldval);
1331
      if (it != _inv_map.end() && it->second == key) {
1332
        _inv_map.erase(it);
1333
      }
1334
      _inv_map.insert(make_pair(val, key));
1335
      Map::set(key, val);
1336
    }
1337

	
1338
    /// \brief The getter function of the map.
1339
    ///
1340
    /// It gives back the value associated with the key.
1341
    typename MapTraits<Map>::ConstReturnValue
1342
    operator[](const Key& key) const {
1343
      return Map::operator[](key);
1344
    }
1345

	
1346
    /// \brief Gives back the item by its value.
1347
    ///
1348
    /// Gives back the item by its value.
1349
    Key operator()(const Value& key) const {
1350
      typename Container::const_iterator it = _inv_map.find(key);
1351
      return it != _inv_map.end() ? it->second : INVALID;
1352
    }
1353

	
1354
  protected:
1355

	
1356
    /// \brief Erase the key from the map.
1357
    ///
1358
    /// Erase the key to the map. It is called by the
1359
    /// \c AlterationNotifier.
1360
    virtual void erase(const Key& key) {
1361
      Value val = Map::operator[](key);
1362
      typename Container::iterator it = _inv_map.find(val);
1363
      if (it != _inv_map.end() && it->second == key) {
1364
        _inv_map.erase(it);
1365
      }
1366
      Map::erase(key);
1367
    }
1368

	
1369
    /// \brief Erase more keys from the map.
1370
    ///
1371
    /// Erase more keys from the map. It is called by the
1372
    /// \c AlterationNotifier.
1373
    virtual void erase(const std::vector<Key>& keys) {
1374
      for (int i = 0; i < int(keys.size()); ++i) {
1375
        Value val = Map::operator[](keys[i]);
1376
        typename Container::iterator it = _inv_map.find(val);
1377
        if (it != _inv_map.end() && it->second == keys[i]) {
1378
          _inv_map.erase(it);
1379
        }
1380
      }
1381
      Map::erase(keys);
1382
    }
1383

	
1384
    /// \brief Clear the keys from the map and inverse map.
1385
    ///
1386
    /// Clear the keys from the map and inverse map. It is called by the
1387
    /// \c AlterationNotifier.
1388
    virtual void clear() {
1389
      _inv_map.clear();
1390
      Map::clear();
1391
    }
1392

	
1393
  public:
1394

	
1395
    /// \brief The inverse map type.
1396
    ///
1397
    /// The inverse of this map. The subscript operator of the map
1398
    /// gives back always the item what was last assigned to the value.
1399
    class InverseMap {
1400
    public:
1401
      /// \brief Constructor of the InverseMap.
1402
      ///
1403
      /// Constructor of the InverseMap.
1404
      explicit InverseMap(const InvertableMap& inverted)
1405
        : _inverted(inverted) {}
1406

	
1407
      /// The value type of the InverseMap.
1408
      typedef typename InvertableMap::Key Value;
1409
      /// The key type of the InverseMap.
1410
      typedef typename InvertableMap::Value Key;
1411

	
1412
      /// \brief Subscript operator.
1413
      ///
1414
      /// Subscript operator. It gives back always the item
1415
      /// what was last assigned to the value.
1416
      Value operator[](const Key& key) const {
1417
        return _inverted(key);
1418
      }
1419

	
1420
    private:
1421
      const InvertableMap& _inverted;
1422
    };
1423

	
1424
    /// \brief It gives back the just readable inverse map.
1425
    ///
1426
    /// It gives back the just readable inverse map.
1427
    InverseMap inverse() const {
1428
      return InverseMap(*this);
1429
    }
1430

	
1431

	
1432

	
1433
  };
1434

	
1435
  /// \brief Provides a mutable, continuous and unique descriptor for each
1436
  /// item in the graph.
1437
  ///
1438
  /// The DescriptorMap class provides a unique and continuous (but mutable)
1439
  /// descriptor (id) for each item of the same type (e.g. node) in the
1440
  /// graph. This id is <ul><li>\b unique: different items (nodes) get
1441
  /// different ids <li>\b continuous: the range of the ids is the set of
1442
  /// integers between 0 and \c n-1, where \c n is the number of the items of
1443
  /// this type (e.g. nodes) (so the id of a node can change if you delete an
1444
  /// other node, i.e. this id is mutable).  </ul> This map can be inverted
1445
  /// with its member class \c InverseMap, or with the \c operator() member.
1446
  ///
1447
  /// \tparam _Graph The graph class the \c DescriptorMap belongs to.
1448
  /// \tparam _Item The Item is the Key of the Map. It may be Node, Arc or
1449
  /// Edge.
1450
  template <typename _Graph, typename _Item>
1451
  class DescriptorMap : protected DefaultMap<_Graph, _Item, int> {
1452

	
1453
    typedef _Item Item;
1454
    typedef DefaultMap<_Graph, _Item, int> Map;
1455

	
1456
  public:
1457
    /// The graph class of DescriptorMap.
1458
    typedef _Graph Graph;
1459

	
1460
    /// The key type of DescriptorMap (Node, Arc, Edge).
1461
    typedef typename Map::Key Key;
1462
    /// The value type of DescriptorMap.
1463
    typedef typename Map::Value Value;
1464

	
1465
    /// \brief Constructor.
1466
    ///
1467
    /// Constructor for descriptor map.
1468
    explicit DescriptorMap(const Graph& _graph) : Map(_graph) {
1469
      Item it;
1470
      const typename Map::Notifier* nf = Map::notifier();
1471
      for (nf->first(it); it != INVALID; nf->next(it)) {
1472
        Map::set(it, _inv_map.size());
1473
        _inv_map.push_back(it);
1474
      }
1475
    }
1476

	
1477
  protected:
1478

	
1479
    /// \brief Add a new key to the map.
1480
    ///
1481
    /// Add a new key to the map. It is called by the
1482
    /// \c AlterationNotifier.
1483
    virtual void add(const Item& item) {
1484
      Map::add(item);
1485
      Map::set(item, _inv_map.size());
1486
      _inv_map.push_back(item);
1487
    }
1488

	
1489
    /// \brief Add more new keys to the map.
1490
    ///
1491
    /// Add more new keys to the map. It is called by the
1492
    /// \c AlterationNotifier.
1493
    virtual void add(const std::vector<Item>& items) {
1494
      Map::add(items);
1495
      for (int i = 0; i < int(items.size()); ++i) {
1496
        Map::set(items[i], _inv_map.size());
1497
        _inv_map.push_back(items[i]);
1498
      }
1499
    }
1500

	
1501
    /// \brief Erase the key from the map.
1502
    ///
1503
    /// Erase the key from the map. It is called by the
1504
    /// \c AlterationNotifier.
1505
    virtual void erase(const Item& item) {
1506
      Map::set(_inv_map.back(), Map::operator[](item));
1507
      _inv_map[Map::operator[](item)] = _inv_map.back();
1508
      _inv_map.pop_back();
1509
      Map::erase(item);
1510
    }
1511

	
1512
    /// \brief Erase more keys from the map.
1513
    ///
1514
    /// Erase more keys from the map. It is called by the
1515
    /// \c AlterationNotifier.
1516
    virtual void erase(const std::vector<Item>& items) {
1517
      for (int i = 0; i < int(items.size()); ++i) {
1518
        Map::set(_inv_map.back(), Map::operator[](items[i]));
1519
        _inv_map[Map::operator[](items[i])] = _inv_map.back();
1520
        _inv_map.pop_back();
1521
      }
1522
      Map::erase(items);
1523
    }
1524

	
1525
    /// \brief Build the unique map.
1526
    ///
1527
    /// Build the unique map. It is called by the
1528
    /// \c AlterationNotifier.
1529
    virtual void build() {
1530
      Map::build();
1531
      Item it;
1532
      const typename Map::Notifier* nf = Map::notifier();
1533
      for (nf->first(it); it != INVALID; nf->next(it)) {
1534
        Map::set(it, _inv_map.size());
1535
        _inv_map.push_back(it);
1536
      }
1537
    }
1538

	
1539
    /// \brief Clear the keys from the map.
1540
    ///
1541
    /// Clear the keys from the map. It is called by the
1542
    /// \c AlterationNotifier.
1543
    virtual void clear() {
1544
      _inv_map.clear();
1545
      Map::clear();
1546
    }
1547

	
1548
  public:
1549

	
1550
    /// \brief Returns the maximal value plus one.
1551
    ///
1552
    /// Returns the maximal value plus one in the map.
1553
    unsigned int size() const {
1554
      return _inv_map.size();
1555
    }
1556

	
1557
    /// \brief Swaps the position of the two items in the map.
1558
    ///
1559
    /// Swaps the position of the two items in the map.
1560
    void swap(const Item& p, const Item& q) {
1561
      int pi = Map::operator[](p);
1562
      int qi = Map::operator[](q);
1563
      Map::set(p, qi);
1564
      _inv_map[qi] = p;
1565
      Map::set(q, pi);
1566
      _inv_map[pi] = q;
1567
    }
1568

	
1569
    /// \brief Gives back the \e descriptor of the item.
1570
    ///
1571
    /// Gives back the mutable and unique \e descriptor of the map.
1572
    int operator[](const Item& item) const {
1573
      return Map::operator[](item);
1574
    }
1575

	
1576
    /// \brief Gives back the item by its descriptor.
1577
    ///
1578
    /// Gives back th item by its descriptor.
1579
    Item operator()(int id) const {
1580
      return _inv_map[id];
1581
    }
1582

	
1583
  private:
1584

	
1585
    typedef std::vector<Item> Container;
1586
    Container _inv_map;
1587

	
1588
  public:
1589
    /// \brief The inverse map type of DescriptorMap.
1590
    ///
1591
    /// The inverse map type of DescriptorMap.
1592
    class InverseMap {
1593
    public:
1594
      /// \brief Constructor of the InverseMap.
1595
      ///
1596
      /// Constructor of the InverseMap.
1597
      explicit InverseMap(const DescriptorMap& inverted)
1598
        : _inverted(inverted) {}
1599

	
1600

	
1601
      /// The value type of the InverseMap.
1602
      typedef typename DescriptorMap::Key Value;
1603
      /// The key type of the InverseMap.
1604
      typedef typename DescriptorMap::Value Key;
1605

	
1606
      /// \brief Subscript operator.
1607
      ///
1608
      /// Subscript operator. It gives back the item
1609
      /// that the descriptor belongs to currently.
1610
      Value operator[](const Key& key) const {
1611
        return _inverted(key);
1612
      }
1613

	
1614
      /// \brief Size of the map.
1615
      ///
1616
      /// Returns the size of the map.
1617
      unsigned int size() const {
1618
        return _inverted.size();
1619
      }
1620

	
1621
    private:
1622
      const DescriptorMap& _inverted;
1623
    };
1624

	
1625
    /// \brief Gives back the inverse of the map.
1626
    ///
1627
    /// Gives back the inverse of the map.
1628
    const InverseMap inverse() const {
1629
      return InverseMap(*this);
1630
    }
1631
  };
1632

	
1633
  /// \brief Returns the source of the given arc.
1634
  ///
1635
  /// The SourceMap gives back the source Node of the given arc.
1636
  /// \see TargetMap
1637
  template <typename Digraph>
1638
  class SourceMap {
1639
  public:
1640

	
1641
    typedef typename Digraph::Node Value;
1642
    typedef typename Digraph::Arc Key;
1643

	
1644
    /// \brief Constructor
1645
    ///
1646
    /// Constructor
1647
    /// \param _digraph The digraph that the map belongs to.
1648
    explicit SourceMap(const Digraph& digraph) : _digraph(digraph) {}
1649

	
1650
    /// \brief The subscript operator.
1651
    ///
1652
    /// The subscript operator.
1653
    /// \param arc The arc
1654
    /// \return The source of the arc
1655
    Value operator[](const Key& arc) const {
1656
      return _digraph.source(arc);
1657
    }
1658

	
1659
  private:
1660
    const Digraph& _digraph;
1661
  };
1662

	
1663
  /// \brief Returns a \ref SourceMap class.
1664
  ///
1665
  /// This function just returns an \ref SourceMap class.
1666
  /// \relates SourceMap
1667
  template <typename Digraph>
1668
  inline SourceMap<Digraph> sourceMap(const Digraph& digraph) {
1669
    return SourceMap<Digraph>(digraph);
1670
  }
1671

	
1672
  /// \brief Returns the target of the given arc.
1673
  ///
1674
  /// The TargetMap gives back the target Node of the given arc.
1675
  /// \see SourceMap
1676
  template <typename Digraph>
1677
  class TargetMap {
1678
  public:
1679

	
1680
    typedef typename Digraph::Node Value;
1681
    typedef typename Digraph::Arc Key;
1682

	
1683
    /// \brief Constructor
1684
    ///
1685
    /// Constructor
1686
    /// \param _digraph The digraph that the map belongs to.
1687
    explicit TargetMap(const Digraph& digraph) : _digraph(digraph) {}
1688

	
1689
    /// \brief The subscript operator.
1690
    ///
1691
    /// The subscript operator.
1692
    /// \param e The arc
1693
    /// \return The target of the arc
1694
    Value operator[](const Key& e) const {
1695
      return _digraph.target(e);
1696
    }
1697

	
1698
  private:
1699
    const Digraph& _digraph;
1700
  };
1701

	
1702
  /// \brief Returns a \ref TargetMap class.
1703
  ///
1704
  /// This function just returns a \ref TargetMap class.
1705
  /// \relates TargetMap
1706
  template <typename Digraph>
1707
  inline TargetMap<Digraph> targetMap(const Digraph& digraph) {
1708
    return TargetMap<Digraph>(digraph);
1709
  }
1710

	
1711
  /// \brief Returns the "forward" directed arc view of an edge.
1712
  ///
1713
  /// Returns the "forward" directed arc view of an edge.
1714
  /// \see BackwardMap
1715
  template <typename Graph>
1716
  class ForwardMap {
1717
  public:
1718

	
1719
    typedef typename Graph::Arc Value;
1720
    typedef typename Graph::Edge Key;
1721

	
1722
    /// \brief Constructor
1723
    ///
1724
    /// Constructor
1725
    /// \param _graph The graph that the map belongs to.
1726
    explicit ForwardMap(const Graph& graph) : _graph(graph) {}
1727

	
1728
    /// \brief The subscript operator.
1729
    ///
1730
    /// The subscript operator.
1731
    /// \param key An edge
1732
    /// \return The "forward" directed arc view of edge
1733
    Value operator[](const Key& key) const {
1734
      return _graph.direct(key, true);
1735
    }
1736

	
1737
  private:
1738
    const Graph& _graph;
1739
  };
1740

	
1741
  /// \brief Returns a \ref ForwardMap class.
1742
  ///
1743
  /// This function just returns an \ref ForwardMap class.
1744
  /// \relates ForwardMap
1745
  template <typename Graph>
1746
  inline ForwardMap<Graph> forwardMap(const Graph& graph) {
1747
    return ForwardMap<Graph>(graph);
1748
  }
1749

	
1750
  /// \brief Returns the "backward" directed arc view of an edge.
1751
  ///
1752
  /// Returns the "backward" directed arc view of an edge.
1753
  /// \see ForwardMap
1754
  template <typename Graph>
1755
  class BackwardMap {
1756
  public:
1757

	
1758
    typedef typename Graph::Arc Value;
1759
    typedef typename Graph::Edge Key;
1760

	
1761
    /// \brief Constructor
1762
    ///
1763
    /// Constructor
1764
    /// \param _graph The graph that the map belongs to.
1765
    explicit BackwardMap(const Graph& graph) : _graph(graph) {}
1766

	
1767
    /// \brief The subscript operator.
1768
    ///
1769
    /// The subscript operator.
1770
    /// \param key An edge
1771
    /// \return The "backward" directed arc view of edge
1772
    Value operator[](const Key& key) const {
1773
      return _graph.direct(key, false);
1774
    }
1775

	
1776
  private:
1777
    const Graph& _graph;
1778
  };
1779

	
1780
  /// \brief Returns a \ref BackwardMap class
1781

	
1782
  /// This function just returns a \ref BackwardMap class.
1783
  /// \relates BackwardMap
1784
  template <typename Graph>
1785
  inline BackwardMap<Graph> backwardMap(const Graph& graph) {
1786
    return BackwardMap<Graph>(graph);
1787
  }
1788

	
1789
  /// \brief Potential difference map
1790
  ///
1791
  /// If there is an potential map on the nodes then we
1792
  /// can get an arc map as we get the substraction of the
1793
  /// values of the target and source.
1794
  template <typename Digraph, typename NodeMap>
1795
  class PotentialDifferenceMap {
1796
  public:
1797
    typedef typename Digraph::Arc Key;
1798
    typedef typename NodeMap::Value Value;
1799

	
1800
    /// \brief Constructor
1801
    ///
1802
    /// Contructor of the map
1803
    explicit PotentialDifferenceMap(const Digraph& digraph,
1804
                                    const NodeMap& potential)
1805
      : _digraph(digraph), _potential(potential) {}
1806

	
1807
    /// \brief Const subscription operator
1808
    ///
1809
    /// Const subscription operator
1810
    Value operator[](const Key& arc) const {
1811
      return _potential[_digraph.target(arc)] -
1812
        _potential[_digraph.source(arc)];
1813
    }
1814

	
1815
  private:
1816
    const Digraph& _digraph;
1817
    const NodeMap& _potential;
1818
  };
1819

	
1820
  /// \brief Returns a PotentialDifferenceMap.
1821
  ///
1822
  /// This function just returns a PotentialDifferenceMap.
1823
  /// \relates PotentialDifferenceMap
1824
  template <typename Digraph, typename NodeMap>
1825
  PotentialDifferenceMap<Digraph, NodeMap>
1826
  potentialDifferenceMap(const Digraph& digraph, const NodeMap& potential) {
1827
    return PotentialDifferenceMap<Digraph, NodeMap>(digraph, potential);
1828
  }
1829

	
1830
  /// \brief Map of the node in-degrees.
1831
  ///
1832
  /// This map returns the in-degree of a node. Once it is constructed,
1833
  /// the degrees are stored in a standard NodeMap, so each query is done
1834
  /// in constant time. On the other hand, the values are updated automatically
1835
  /// whenever the digraph changes.
1836
  ///
1837
  /// \warning Besides addNode() and addArc(), a digraph structure may provide
1838
  /// alternative ways to modify the digraph. The correct behavior of InDegMap
1839
  /// is not guarantied if these additional features are used. For example
1840
  /// the functions \ref ListDigraph::changeSource() "changeSource()",
1841
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
1842
  /// \ref ListDigraph::reverseArc() "reverseArc()"
1843
  /// of \ref ListDigraph will \e not update the degree values correctly.
1844
  ///
1845
  /// \sa OutDegMap
1846

	
1847
  template <typename _Digraph>
1848
  class InDegMap
1849
    : protected ItemSetTraits<_Digraph, typename _Digraph::Arc>
1850
      ::ItemNotifier::ObserverBase {
1851

	
1852
  public:
1853

	
1854
    typedef _Digraph Digraph;
1855
    typedef int Value;
1856
    typedef typename Digraph::Node Key;
1857

	
1858
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
1859
    ::ItemNotifier::ObserverBase Parent;
1860

	
1861
  private:
1862

	
1863
    class AutoNodeMap : public DefaultMap<Digraph, Key, int> {
1864
    public:
1865

	
1866
      typedef DefaultMap<Digraph, Key, int> Parent;
1867

	
1868
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
1869

	
1870
      virtual void add(const Key& key) {
1871
        Parent::add(key);
1872
        Parent::set(key, 0);
1873
      }
1874

	
1875
      virtual void add(const std::vector<Key>& keys) {
1876
        Parent::add(keys);
1877
        for (int i = 0; i < int(keys.size()); ++i) {
1878
          Parent::set(keys[i], 0);
1879
        }
1880
      }
1881

	
1882
      virtual void build() {
1883
        Parent::build();
1884
        Key it;
1885
        typename Parent::Notifier* nf = Parent::notifier();
1886
        for (nf->first(it); it != INVALID; nf->next(it)) {
1887
          Parent::set(it, 0);
1888
        }
1889
      }
1890
    };
1891

	
1892
  public:
1893

	
1894
    /// \brief Constructor.
1895
    ///
1896
    /// Constructor for creating in-degree map.
1897
    explicit InDegMap(const Digraph& digraph)
1898
      : _digraph(digraph), _deg(digraph) {
1899
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
1900

	
1901
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
1902
        _deg[it] = countInArcs(_digraph, it);
1903
      }
1904
    }
1905

	
1906
    /// Gives back the in-degree of a Node.
1907
    int operator[](const Key& key) const {
1908
      return _deg[key];
1909
    }
1910

	
1911
  protected:
1912

	
1913
    typedef typename Digraph::Arc Arc;
1914

	
1915
    virtual void add(const Arc& arc) {
1916
      ++_deg[_digraph.target(arc)];
1917
    }
1918

	
1919
    virtual void add(const std::vector<Arc>& arcs) {
1920
      for (int i = 0; i < int(arcs.size()); ++i) {
1921
        ++_deg[_digraph.target(arcs[i])];
1922
      }
1923
    }
1924

	
1925
    virtual void erase(const Arc& arc) {
1926
      --_deg[_digraph.target(arc)];
1927
    }
1928

	
1929
    virtual void erase(const std::vector<Arc>& arcs) {
1930
      for (int i = 0; i < int(arcs.size()); ++i) {
1931
        --_deg[_digraph.target(arcs[i])];
1932
      }
1933
    }
1934

	
1935
    virtual void build() {
1936
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
1937
        _deg[it] = countInArcs(_digraph, it);
1938
      }
1939
    }
1940

	
1941
    virtual void clear() {
1942
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
1943
        _deg[it] = 0;
1944
      }
1945
    }
1946
  private:
1947

	
1948
    const Digraph& _digraph;
1949
    AutoNodeMap _deg;
1950
  };
1951

	
1952
  /// \brief Map of the node out-degrees.
1953
  ///
1954
  /// This map returns the out-degree of a node. Once it is constructed,
1955
  /// the degrees are stored in a standard NodeMap, so each query is done
1956
  /// in constant time. On the other hand, the values are updated automatically
1957
  /// whenever the digraph changes.
1958
  ///
1959
  /// \warning Besides addNode() and addArc(), a digraph structure may provide
1960
  /// alternative ways to modify the digraph. The correct behavior of OutDegMap
1961
  /// is not guarantied if these additional features are used. For example
1962
  /// the functions \ref ListDigraph::changeSource() "changeSource()",
1963
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
1964
  /// \ref ListDigraph::reverseArc() "reverseArc()"
1965
  /// of \ref ListDigraph will \e not update the degree values correctly.
1966
  ///
1967
  /// \sa InDegMap
1968

	
1969
  template <typename _Digraph>
1970
  class OutDegMap
1971
    : protected ItemSetTraits<_Digraph, typename _Digraph::Arc>
1972
      ::ItemNotifier::ObserverBase {
1973

	
1974
  public:
1975

	
1976
    typedef _Digraph Digraph;
1977
    typedef int Value;
1978
    typedef typename Digraph::Node Key;
1979

	
1980
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
1981
    ::ItemNotifier::ObserverBase Parent;
1982

	
1983
  private:
1984

	
1985
    class AutoNodeMap : public DefaultMap<Digraph, Key, int> {
1986
    public:
1987

	
1988
      typedef DefaultMap<Digraph, Key, int> Parent;
1989

	
1990
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
1991

	
1992
      virtual void add(const Key& key) {
1993
        Parent::add(key);
1994
        Parent::set(key, 0);
1995
      }
1996
      virtual void add(const std::vector<Key>& keys) {
1997
        Parent::add(keys);
1998
        for (int i = 0; i < int(keys.size()); ++i) {
1999
          Parent::set(keys[i], 0);
2000
        }
2001
      }
2002
      virtual void build() {
2003
        Parent::build();
2004
        Key it;
2005
        typename Parent::Notifier* nf = Parent::notifier();
2006
        for (nf->first(it); it != INVALID; nf->next(it)) {
2007
          Parent::set(it, 0);
2008
        }
2009
      }
2010
    };
2011

	
2012
  public:
2013

	
2014
    /// \brief Constructor.
2015
    ///
2016
    /// Constructor for creating out-degree map.
2017
    explicit OutDegMap(const Digraph& digraph)
2018
      : _digraph(digraph), _deg(digraph) {
2019
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2020

	
2021
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2022
        _deg[it] = countOutArcs(_digraph, it);
2023
      }
2024
    }
2025

	
2026
    /// Gives back the out-degree of a Node.
2027
    int operator[](const Key& key) const {
2028
      return _deg[key];
2029
    }
2030

	
2031
  protected:
2032

	
2033
    typedef typename Digraph::Arc Arc;
2034

	
2035
    virtual void add(const Arc& arc) {
2036
      ++_deg[_digraph.source(arc)];
2037
    }
2038

	
2039
    virtual void add(const std::vector<Arc>& arcs) {
2040
      for (int i = 0; i < int(arcs.size()); ++i) {
2041
        ++_deg[_digraph.source(arcs[i])];
2042
      }
2043
    }
2044

	
2045
    virtual void erase(const Arc& arc) {
2046
      --_deg[_digraph.source(arc)];
2047
    }
2048

	
2049
    virtual void erase(const std::vector<Arc>& arcs) {
2050
      for (int i = 0; i < int(arcs.size()); ++i) {
2051
        --_deg[_digraph.source(arcs[i])];
2052
      }
2053
    }
2054

	
2055
    virtual void build() {
2056
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2057
        _deg[it] = countOutArcs(_digraph, it);
2058
      }
2059
    }
2060

	
2061
    virtual void clear() {
2062
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2063
        _deg[it] = 0;
2064
      }
2065
    }
2066
  private:
2067

	
2068
    const Digraph& _digraph;
2069
    AutoNodeMap _deg;
2070
  };
2071

	
2072

	
2073
  ///Dynamic arc look up between given endpoints.
2074

	
2075
  ///\ingroup gutils
2076
  ///Using this class, you can find an arc in a digraph from a given
2077
  ///source to a given target in amortized time <em>O(log d)</em>,
2078
  ///where <em>d</em> is the out-degree of the source node.
2079
  ///
2080
  ///It is possible to find \e all parallel arcs between two nodes with
2081
  ///the \c findFirst() and \c findNext() members.
2082
  ///
2083
  ///See the \ref ArcLookUp and \ref AllArcLookUp classes if your
2084
  ///digraph is not changed so frequently.
2085
  ///
2086
  ///This class uses a self-adjusting binary search tree, Sleator's
2087
  ///and Tarjan's Splay tree for guarantee the logarithmic amortized
2088
  ///time bound for arc lookups. This class also guarantees the
2089
  ///optimal time bound in a constant factor for any distribution of
2090
  ///queries.
2091
  ///
2092
  ///\tparam G The type of the underlying digraph.
2093
  ///
2094
  ///\sa ArcLookUp
2095
  ///\sa AllArcLookUp
2096
  template<class G>
2097
  class DynArcLookUp
2098
    : protected ItemSetTraits<G, typename G::Arc>::ItemNotifier::ObserverBase
2099
  {
2100
  public:
2101
    typedef typename ItemSetTraits<G, typename G::Arc>
2102
    ::ItemNotifier::ObserverBase Parent;
2103

	
2104
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
2105
    typedef G Digraph;
2106

	
2107
  protected:
2108

	
2109
    class AutoNodeMap : public DefaultMap<G, Node, Arc> {
2110
    public:
2111

	
2112
      typedef DefaultMap<G, Node, Arc> Parent;
2113

	
2114
      AutoNodeMap(const G& digraph) : Parent(digraph, INVALID) {}
2115

	
2116
      virtual void add(const Node& node) {
2117
        Parent::add(node);
2118
        Parent::set(node, INVALID);
2119
      }
2120

	
2121
      virtual void add(const std::vector<Node>& nodes) {
2122
        Parent::add(nodes);
2123
        for (int i = 0; i < int(nodes.size()); ++i) {
2124
          Parent::set(nodes[i], INVALID);
2125
        }
2126
      }
2127

	
2128
      virtual void build() {
2129
        Parent::build();
2130
        Node it;
2131
        typename Parent::Notifier* nf = Parent::notifier();
2132
        for (nf->first(it); it != INVALID; nf->next(it)) {
2133
          Parent::set(it, INVALID);
2134
        }
2135
      }
2136
    };
2137

	
2138
    const Digraph &_g;
2139
    AutoNodeMap _head;
2140
    typename Digraph::template ArcMap<Arc> _parent;
2141
    typename Digraph::template ArcMap<Arc> _left;
2142
    typename Digraph::template ArcMap<Arc> _right;
2143

	
2144
    class ArcLess {
2145
      const Digraph &g;
2146
    public:
2147
      ArcLess(const Digraph &_g) : g(_g) {}
2148
      bool operator()(Arc a,Arc b) const
2149
      {
2150
        return g.target(a)<g.target(b);
2151
      }
2152
    };
2153

	
2154
  public:
2155

	
2156
    ///Constructor
2157

	
2158
    ///Constructor.
2159
    ///
2160
    ///It builds up the search database.
2161
    DynArcLookUp(const Digraph &g)
2162
      : _g(g),_head(g),_parent(g),_left(g),_right(g)
2163
    {
2164
      Parent::attach(_g.notifier(typename Digraph::Arc()));
2165
      refresh();
2166
    }
2167

	
2168
  protected:
2169

	
2170
    virtual void add(const Arc& arc) {
2171
      insert(arc);
2172
    }
2173

	
2174
    virtual void add(const std::vector<Arc>& arcs) {
2175
      for (int i = 0; i < int(arcs.size()); ++i) {
2176
        insert(arcs[i]);
2177
      }
2178
    }
2179

	
2180
    virtual void erase(const Arc& arc) {
2181
      remove(arc);
2182
    }
2183

	
2184
    virtual void erase(const std::vector<Arc>& arcs) {
2185
      for (int i = 0; i < int(arcs.size()); ++i) {
2186
        remove(arcs[i]);
2187
      }
2188
    }
2189

	
2190
    virtual void build() {
2191
      refresh();
2192
    }
2193

	
2194
    virtual void clear() {
2195
      for(NodeIt n(_g);n!=INVALID;++n) {
2196
        _head.set(n, INVALID);
2197
      }
2198
    }
2199

	
2200
    void insert(Arc arc) {
2201
      Node s = _g.source(arc);
2202
      Node t = _g.target(arc);
2203
      _left.set(arc, INVALID);
2204
      _right.set(arc, INVALID);
2205

	
2206
      Arc e = _head[s];
2207
      if (e == INVALID) {
2208
        _head.set(s, arc);
2209
        _parent.set(arc, INVALID);
2210
        return;
2211
      }
2212
      while (true) {
2213
        if (t < _g.target(e)) {
2214
          if (_left[e] == INVALID) {
2215
            _left.set(e, arc);
2216
            _parent.set(arc, e);
2217
            splay(arc);
2218
            return;
2219
          } else {
2220
            e = _left[e];
2221
          }
2222
        } else {
2223
          if (_right[e] == INVALID) {
2224
            _right.set(e, arc);
2225
            _parent.set(arc, e);
2226
            splay(arc);
2227
            return;
2228
          } else {
2229
            e = _right[e];
2230
          }
2231
        }
2232
      }
2233
    }
2234

	
2235
    void remove(Arc arc) {
2236
      if (_left[arc] == INVALID) {
2237
        if (_right[arc] != INVALID) {
2238
          _parent.set(_right[arc], _parent[arc]);
2239
        }
2240
        if (_parent[arc] != INVALID) {
2241
          if (_left[_parent[arc]] == arc) {
2242
            _left.set(_parent[arc], _right[arc]);
2243
          } else {
2244
            _right.set(_parent[arc], _right[arc]);
2245
          }
2246
        } else {
2247
          _head.set(_g.source(arc), _right[arc]);
2248
        }
2249
      } else if (_right[arc] == INVALID) {
2250
        _parent.set(_left[arc], _parent[arc]);
2251
        if (_parent[arc] != INVALID) {
2252
          if (_left[_parent[arc]] == arc) {
2253
            _left.set(_parent[arc], _left[arc]);
2254
          } else {
2255
            _right.set(_parent[arc], _left[arc]);
2256
          }
2257
        } else {
2258
          _head.set(_g.source(arc), _left[arc]);
2259
        }
2260
      } else {
2261
        Arc e = _left[arc];
2262
        if (_right[e] != INVALID) {
2263
          e = _right[e];
2264
          while (_right[e] != INVALID) {
2265
            e = _right[e];
2266
          }
2267
          Arc s = _parent[e];
2268
          _right.set(_parent[e], _left[e]);
2269
          if (_left[e] != INVALID) {
2270
            _parent.set(_left[e], _parent[e]);
2271
          }
2272

	
2273
          _left.set(e, _left[arc]);
2274
          _parent.set(_left[arc], e);
2275
          _right.set(e, _right[arc]);
2276
          _parent.set(_right[arc], e);
2277

	
2278
          _parent.set(e, _parent[arc]);
2279
          if (_parent[arc] != INVALID) {
2280
            if (_left[_parent[arc]] == arc) {
2281
              _left.set(_parent[arc], e);
2282
            } else {
2283
              _right.set(_parent[arc], e);
2284
            }
2285
          }
2286
          splay(s);
2287
        } else {
2288
          _right.set(e, _right[arc]);
2289
          _parent.set(_right[arc], e);
2290

	
2291
          if (_parent[arc] != INVALID) {
2292
            if (_left[_parent[arc]] == arc) {
2293
              _left.set(_parent[arc], e);
2294
            } else {
2295
              _right.set(_parent[arc], e);
2296
            }
2297
          } else {
2298
            _head.set(_g.source(arc), e);
2299
          }
2300
        }
2301
      }
2302
    }
2303

	
2304
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
2305
    {
2306
      int m=(a+b)/2;
2307
      Arc me=v[m];
2308
      if (a < m) {
2309
        Arc left = refreshRec(v,a,m-1);
2310
        _left.set(me, left);
2311
        _parent.set(left, me);
2312
      } else {
2313
        _left.set(me, INVALID);
2314
      }
2315
      if (m < b) {
2316
        Arc right = refreshRec(v,m+1,b);
2317
        _right.set(me, right);
2318
        _parent.set(right, me);
2319
      } else {
2320
        _right.set(me, INVALID);
2321
      }
2322
      return me;
2323
    }
2324

	
2325
    void refresh() {
2326
      for(NodeIt n(_g);n!=INVALID;++n) {
2327
        std::vector<Arc> v;
2328
        for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
2329
        if(v.size()) {
2330
          std::sort(v.begin(),v.end(),ArcLess(_g));
2331
          Arc head = refreshRec(v,0,v.size()-1);
2332
          _head.set(n, head);
2333
          _parent.set(head, INVALID);
2334
        }
2335
        else _head.set(n, INVALID);
2336
      }
2337
    }
2338

	
2339
    void zig(Arc v) {
2340
      Arc w = _parent[v];
2341
      _parent.set(v, _parent[w]);
2342
      _parent.set(w, v);
2343
      _left.set(w, _right[v]);
2344
      _right.set(v, w);
2345
      if (_parent[v] != INVALID) {
2346
        if (_right[_parent[v]] == w) {
2347
          _right.set(_parent[v], v);
2348
        } else {
2349
          _left.set(_parent[v], v);
2350
        }
2351
      }
2352
      if (_left[w] != INVALID){
2353
        _parent.set(_left[w], w);
2354
      }
2355
    }
2356

	
2357
    void zag(Arc v) {
2358
      Arc w = _parent[v];
2359
      _parent.set(v, _parent[w]);
2360
      _parent.set(w, v);
2361
      _right.set(w, _left[v]);
2362
      _left.set(v, w);
2363
      if (_parent[v] != INVALID){
2364
        if (_left[_parent[v]] == w) {
2365
          _left.set(_parent[v], v);
2366
        } else {
2367
          _right.set(_parent[v], v);
2368
        }
2369
      }
2370
      if (_right[w] != INVALID){
2371
        _parent.set(_right[w], w);
2372
      }
2373
    }
2374

	
2375
    void splay(Arc v) {
2376
      while (_parent[v] != INVALID) {
2377
        if (v == _left[_parent[v]]) {
2378
          if (_parent[_parent[v]] == INVALID) {
2379
            zig(v);
2380
          } else {
2381
            if (_parent[v] == _left[_parent[_parent[v]]]) {
2382
              zig(_parent[v]);
2383
              zig(v);
2384
            } else {
2385
              zig(v);
2386
              zag(v);
2387
            }
2388
          }
2389
        } else {
2390
          if (_parent[_parent[v]] == INVALID) {
2391
            zag(v);
2392
          } else {
2393
            if (_parent[v] == _left[_parent[_parent[v]]]) {
2394
              zag(v);
2395
              zig(v);
2396
            } else {
2397
              zag(_parent[v]);
2398
              zag(v);
2399
            }
2400
          }
2401
        }
2402
      }
2403
      _head[_g.source(v)] = v;
2404
    }
2405

	
2406

	
2407
  public:
2408

	
2409
    ///Find an arc between two nodes.
2410

	
2411
    ///Find an arc between two nodes in time <em>O(</em>log<em>d)</em>, where
2412
    /// <em>d</em> is the number of outgoing arcs of \c s.
2413
    ///\param s The source node
2414
    ///\param t The target node
2415
    ///\return An arc from \c s to \c t if there exists,
2416
    ///\ref INVALID otherwise.
2417
    Arc operator()(Node s, Node t) const
2418
    {
2419
      Arc a = _head[s];
2420
      while (true) {
2421
        if (_g.target(a) == t) {
2422
          const_cast<DynArcLookUp&>(*this).splay(a);
2423
          return a;
2424
        } else if (t < _g.target(a)) {
2425
          if (_left[a] == INVALID) {
2426
            const_cast<DynArcLookUp&>(*this).splay(a);
2427
            return INVALID;
2428
          } else {
2429
            a = _left[a];
2430
          }
2431
        } else  {
2432
          if (_right[a] == INVALID) {
2433
            const_cast<DynArcLookUp&>(*this).splay(a);
2434
            return INVALID;
2435
          } else {
2436
            a = _right[a];
2437
          }
2438
        }
2439
      }
2440
    }
2441

	
2442
    ///Find the first arc between two nodes.
2443

	
2444
    ///Find the first arc between two nodes in time
2445
    /// <em>O(</em>log<em>d)</em>, where <em>d</em> is the number of
2446
    /// outgoing arcs of \c s.
2447
    ///\param s The source node
2448
    ///\param t The target node
2449
    ///\return An arc from \c s to \c t if there exists, \ref INVALID
2450
    /// otherwise.
2451
    Arc findFirst(Node s, Node t) const
2452
    {
2453
      Arc a = _head[s];
2454
      Arc r = INVALID;
2455
      while (true) {
2456
        if (_g.target(a) < t) {
2457
          if (_right[a] == INVALID) {
2458
            const_cast<DynArcLookUp&>(*this).splay(a);
2459
            return r;
2460
          } else {
2461
            a = _right[a];
2462
          }
2463
        } else {
2464
          if (_g.target(a) == t) {
2465
            r = a;
2466
          }
2467
          if (_left[a] == INVALID) {
2468
            const_cast<DynArcLookUp&>(*this).splay(a);
2469
            return r;
2470
          } else {
2471
            a = _left[a];
2472
          }
2473
        }
2474
      }
2475
    }
2476

	
2477
    ///Find the next arc between two nodes.
2478

	
2479
    ///Find the next arc between two nodes in time
2480
    /// <em>O(</em>log<em>d)</em>, where <em>d</em> is the number of
2481
    /// outgoing arcs of \c s.
2482
    ///\param s The source node
2483
    ///\param t The target node
2484
    ///\return An arc from \c s to \c t if there exists, \ref INVALID
2485
    /// otherwise.
2486

	
2487
    ///\note If \c e is not the result of the previous \c findFirst()
2488
    ///operation then the amorized time bound can not be guaranteed.
2489
#ifdef DOXYGEN
2490
    Arc findNext(Node s, Node t, Arc a) const
2491
#else
2492
    Arc findNext(Node, Node t, Arc a) const
2493
#endif
2494
    {
2495
      if (_right[a] != INVALID) {
2496
        a = _right[a];
2497
        while (_left[a] != INVALID) {
2498
          a = _left[a];
2499
        }
2500
        const_cast<DynArcLookUp&>(*this).splay(a);
2501
      } else {
2502
        while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
2503
          a = _parent[a];
2504
        }
2505
        if (_parent[a] == INVALID) {
2506
          return INVALID;
2507
        } else {
2508
          a = _parent[a];
2509
          const_cast<DynArcLookUp&>(*this).splay(a);
2510
        }
2511
      }
2512
      if (_g.target(a) == t) return a;
2513
      else return INVALID;
2514
    }
2515

	
2516
  };
2517

	
2518
  ///Fast arc look up between given endpoints.
2519

	
2520
  ///\ingroup gutils
2521
  ///Using this class, you can find an arc in a digraph from a given
2522
  ///source to a given target in time <em>O(log d)</em>,
2523
  ///where <em>d</em> is the out-degree of the source node.
2524
  ///
2525
  ///It is not possible to find \e all parallel arcs between two nodes.
2526
  ///Use \ref AllArcLookUp for this purpose.
2527
  ///
2528
  ///\warning This class is static, so you should refresh() (or at least
2529
  ///refresh(Node)) this data structure
2530
  ///whenever the digraph changes. This is a time consuming (superlinearly
2531
  ///proportional (<em>O(m</em>log<em>m)</em>) to the number of arcs).
2532
  ///
2533
  ///\tparam G The type of the underlying digraph.
2534
  ///
2535
  ///\sa DynArcLookUp
2536
  ///\sa AllArcLookUp
2537
  template<class G>
2538
  class ArcLookUp
2539
  {
2540
  public:
2541
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
2542
    typedef G Digraph;
2543

	
2544
  protected:
2545
    const Digraph &_g;
2546
    typename Digraph::template NodeMap<Arc> _head;
2547
    typename Digraph::template ArcMap<Arc> _left;
2548
    typename Digraph::template ArcMap<Arc> _right;
2549

	
2550
    class ArcLess {
2551
      const Digraph &g;
2552
    public:
2553
      ArcLess(const Digraph &_g) : g(_g) {}
2554
      bool operator()(Arc a,Arc b) const
2555
      {
2556
        return g.target(a)<g.target(b);
2557
      }
2558
    };
2559

	
2560
  public:
2561

	
2562
    ///Constructor
2563

	
2564
    ///Constructor.
2565
    ///
2566
    ///It builds up the search database, which remains valid until the digraph
2567
    ///changes.
2568
    ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();}
2569

	
2570
  private:
2571
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
2572
    {
2573
      int m=(a+b)/2;
2574
      Arc me=v[m];
2575
      _left[me] = a<m?refreshRec(v,a,m-1):INVALID;
2576
      _right[me] = m<b?refreshRec(v,m+1,b):INVALID;
2577
      return me;
2578
    }
2579
  public:
2580
    ///Refresh the data structure at a node.
2581

	
2582
    ///Build up the search database of node \c n.
2583
    ///
2584
    ///It runs in time <em>O(d</em>log<em>d)</em>, where <em>d</em> is
2585
    ///the number of the outgoing arcs of \c n.
2586
    void refresh(Node n)
2587
    {
2588
      std::vector<Arc> v;
2589
      for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
2590
      if(v.size()) {
2591
        std::sort(v.begin(),v.end(),ArcLess(_g));
2592
        _head[n]=refreshRec(v,0,v.size()-1);
2593
      }
2594
      else _head[n]=INVALID;
2595
    }
2596
    ///Refresh the full data structure.
2597

	
2598
    ///Build up the full search database. In fact, it simply calls
2599
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
2600
    ///
2601
    ///It runs in time <em>O(m</em>log<em>D)</em>, where <em>m</em> is
2602
    ///the number of the arcs of \c n and <em>D</em> is the maximum
2603
    ///out-degree of the digraph.
2604

	
2605
    void refresh()
2606
    {
2607
      for(NodeIt n(_g);n!=INVALID;++n) refresh(n);
2608
    }
2609

	
2610
    ///Find an arc between two nodes.
2611

	
2612
    ///Find an arc between two nodes in time <em>O(</em>log<em>d)</em>, where
2613
    /// <em>d</em> is the number of outgoing arcs of \c s.
2614
    ///\param s The source node
2615
    ///\param t The target node
2616
    ///\return An arc from \c s to \c t if there exists,
2617
    ///\ref INVALID otherwise.
2618
    ///
2619
    ///\warning If you change the digraph, refresh() must be called before using
2620
    ///this operator. If you change the outgoing arcs of
2621
    ///a single node \c n, then
2622
    ///\ref refresh(Node) "refresh(n)" is enough.
2623
    ///
2624
    Arc operator()(Node s, Node t) const
2625
    {
2626
      Arc e;
2627
      for(e=_head[s];
2628
          e!=INVALID&&_g.target(e)!=t;
2629
          e = t < _g.target(e)?_left[e]:_right[e]) ;
2630
      return e;
2631
    }
2632

	
2633
  };
2634

	
2635
  ///Fast look up of all arcs between given endpoints.
2636

	
2637
  ///\ingroup gutils
2638
  ///This class is the same as \ref ArcLookUp, with the addition
2639
  ///that it makes it possible to find all arcs between given endpoints.
2640
  ///
2641
  ///\warning This class is static, so you should refresh() (or at least
2642
  ///refresh(Node)) this data structure
2643
  ///whenever the digraph changes. This is a time consuming (superlinearly
2644
  ///proportional (<em>O(m</em>log<em>m)</em>) to the number of arcs).
2645
  ///
2646
  ///\tparam G The type of the underlying digraph.
2647
  ///
2648
  ///\sa DynArcLookUp
2649
  ///\sa ArcLookUp
2650
  template<class G>
2651
  class AllArcLookUp : public ArcLookUp<G>
2652
  {
2653
    using ArcLookUp<G>::_g;
2654
    using ArcLookUp<G>::_right;
2655
    using ArcLookUp<G>::_left;
2656
    using ArcLookUp<G>::_head;
2657

	
2658
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
2659
    typedef G Digraph;
2660

	
2661
    typename Digraph::template ArcMap<Arc> _next;
2662

	
2663
    Arc refreshNext(Arc head,Arc next=INVALID)
2664
    {
2665
      if(head==INVALID) return next;
2666
      else {
2667
        next=refreshNext(_right[head],next);
2668
//         _next[head]=next;
2669
        _next[head]=( next!=INVALID && _g.target(next)==_g.target(head))
2670
          ? next : INVALID;
2671
        return refreshNext(_left[head],head);
2672
      }
2673
    }
2674

	
2675
    void refreshNext()
2676
    {
2677
      for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]);
2678
    }
2679

	
2680
  public:
2681
    ///Constructor
2682

	
2683
    ///Constructor.
2684
    ///
2685
    ///It builds up the search database, which remains valid until the digraph
2686
    ///changes.
2687
    AllArcLookUp(const Digraph &g) : ArcLookUp<G>(g), _next(g) {refreshNext();}
2688

	
2689
    ///Refresh the data structure at a node.
2690

	
2691
    ///Build up the search database of node \c n.
2692
    ///
2693
    ///It runs in time <em>O(d</em>log<em>d)</em>, where <em>d</em> is
2694
    ///the number of the outgoing arcs of \c n.
2695

	
2696
    void refresh(Node n)
2697
    {
2698
      ArcLookUp<G>::refresh(n);
2699
      refreshNext(_head[n]);
2700
    }
2701

	
2702
    ///Refresh the full data structure.
2703

	
2704
    ///Build up the full search database. In fact, it simply calls
2705
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
2706
    ///
2707
    ///It runs in time <em>O(m</em>log<em>D)</em>, where <em>m</em> is
2708
    ///the number of the arcs of \c n and <em>D</em> is the maximum
2709
    ///out-degree of the digraph.
2710

	
2711
    void refresh()
2712
    {
2713
      for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]);
2714
    }
2715

	
2716
    ///Find an arc between two nodes.
2717

	
2718
    ///Find an arc between two nodes.
2719
    ///\param s The source node
2720
    ///\param t The target node
2721
    ///\param prev The previous arc between \c s and \c t. It it is INVALID or
2722
    ///not given, the operator finds the first appropriate arc.
2723
    ///\return An arc from \c s to \c t after \c prev or
2724
    ///\ref INVALID if there is no more.
2725
    ///
2726
    ///For example, you can count the number of arcs from \c u to \c v in the
2727
    ///following way.
2728
    ///\code
2729
    ///AllArcLookUp<ListDigraph> ae(g);
2730
    ///...
2731
    ///int n=0;
2732
    ///for(Arc e=ae(u,v);e!=INVALID;e=ae(u,v,e)) n++;
2733
    ///\endcode
2734
    ///
2735
    ///Finding the first arc take <em>O(</em>log<em>d)</em> time, where
2736
    /// <em>d</em> is the number of outgoing arcs of \c s. Then, the
2737
    ///consecutive arcs are found in constant time.
2738
    ///
2739
    ///\warning If you change the digraph, refresh() must be called before using
2740
    ///this operator. If you change the outgoing arcs of
2741
    ///a single node \c n, then
2742
    ///\ref refresh(Node) "refresh(n)" is enough.
2743
    ///
2744
#ifdef DOXYGEN
2745
    Arc operator()(Node s, Node t, Arc prev=INVALID) const {}
2746
#else
2747
    using ArcLookUp<G>::operator() ;
2748
    Arc operator()(Node s, Node t, Arc prev) const
2749
    {
2750
      return prev==INVALID?(*this)(s,t):_next[prev];
2751
    }
2752
#endif
2753

	
2754
  };
2755

	
2756
  /// @}
2757

	
2758
} //END OF NAMESPACE LEMON
2759

	
2760
#endif
0 comments (0 inline)