COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/core.h @ 976:736436e516d3

1.2
Last change on this file since 976:736436e516d3 was 976:736436e516d3, checked in by Alpar Juttner <alpar@…>, 6 years ago

Merge fix #470 to branch 1.2

File size: 59.2 KB
RevLine 
[220]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library.
4 *
[877]5 * Copyright (C) 2003-2010
[220]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
[501]25#include <lemon/config.h>
[220]26#include <lemon/bits/enable_if.h>
27#include <lemon/bits/traits.h>
[319]28#include <lemon/assert.h>
[220]29
[671]30// Disable the following warnings when compiling with MSVC:
31// C4250: 'class1' : inherits 'class2::member' via dominance
32// C4355: 'this' : used in base member initializer list
33// C4503: 'function' : decorated name length exceeded, name was truncated
34// C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
35// C4996: 'function': was declared deprecated
36#ifdef _MSC_VER
37#pragma warning( disable : 4250 4355 4503 4800 4996 )
38#endif
39
[975]40#ifdef __GNUC__
41// Needed by the [DI]GRAPH_TYPEDEFS marcos for gcc 4.8
42#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
43#endif
44
[220]45///\file
46///\brief LEMON core utilities.
[229]47///
48///This header file contains core utilities for LEMON.
[233]49///It is automatically included by all graph types, therefore it usually
[229]50///do not have to be included directly.
[220]51
52namespace lemon {
53
54  /// \brief Dummy type to make it easier to create invalid iterators.
55  ///
56  /// Dummy type to make it easier to create invalid iterators.
57  /// See \ref INVALID for the usage.
58  struct Invalid {
59  public:
60    bool operator==(Invalid) { return true;  }
61    bool operator!=(Invalid) { return false; }
62    bool operator< (Invalid) { return false; }
63  };
64
65  /// \brief Invalid iterators.
66  ///
67  /// \ref Invalid is a global type that converts to each iterator
68  /// in such a way that the value of the target iterator will be invalid.
69#ifdef LEMON_ONLY_TEMPLATES
70  const Invalid INVALID = Invalid();
71#else
72  extern const Invalid INVALID;
73#endif
74
75  /// \addtogroup gutils
76  /// @{
77
[300]78  ///Create convenience typedefs for the digraph types and iterators
[220]79
[282]80  ///This \c \#define creates convenient type definitions for the following
81  ///types of \c Digraph: \c Node,  \c NodeIt, \c Arc, \c ArcIt, \c InArcIt,
[220]82  ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap,
83  ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap.
84  ///
85  ///\note If the graph type is a dependent type, ie. the graph type depend
86  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
87  ///macro.
88#define DIGRAPH_TYPEDEFS(Digraph)                                       \
89  typedef Digraph::Node Node;                                           \
90  typedef Digraph::NodeIt NodeIt;                                       \
91  typedef Digraph::Arc Arc;                                             \
92  typedef Digraph::ArcIt ArcIt;                                         \
93  typedef Digraph::InArcIt InArcIt;                                     \
94  typedef Digraph::OutArcIt OutArcIt;                                   \
95  typedef Digraph::NodeMap<bool> BoolNodeMap;                           \
96  typedef Digraph::NodeMap<int> IntNodeMap;                             \
97  typedef Digraph::NodeMap<double> DoubleNodeMap;                       \
98  typedef Digraph::ArcMap<bool> BoolArcMap;                             \
99  typedef Digraph::ArcMap<int> IntArcMap;                               \
[300]100  typedef Digraph::ArcMap<double> DoubleArcMap
[220]101
[300]102  ///Create convenience typedefs for the digraph types and iterators
[220]103
104  ///\see DIGRAPH_TYPEDEFS
105  ///
106  ///\note Use this macro, if the graph type is a dependent type,
107  ///ie. the graph type depend on a template parameter.
108#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph)                              \
109  typedef typename Digraph::Node Node;                                  \
110  typedef typename Digraph::NodeIt NodeIt;                              \
111  typedef typename Digraph::Arc Arc;                                    \
112  typedef typename Digraph::ArcIt ArcIt;                                \
113  typedef typename Digraph::InArcIt InArcIt;                            \
114  typedef typename Digraph::OutArcIt OutArcIt;                          \
115  typedef typename Digraph::template NodeMap<bool> BoolNodeMap;         \
116  typedef typename Digraph::template NodeMap<int> IntNodeMap;           \
117  typedef typename Digraph::template NodeMap<double> DoubleNodeMap;     \
118  typedef typename Digraph::template ArcMap<bool> BoolArcMap;           \
119  typedef typename Digraph::template ArcMap<int> IntArcMap;             \
[300]120  typedef typename Digraph::template ArcMap<double> DoubleArcMap
[220]121
[300]122  ///Create convenience typedefs for the graph types and iterators
[220]123
[282]124  ///This \c \#define creates the same convenient type definitions as defined
[220]125  ///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates
126  ///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap,
127  ///\c DoubleEdgeMap.
128  ///
129  ///\note If the graph type is a dependent type, ie. the graph type depend
[282]130  ///on a template parameter, then use \c TEMPLATE_GRAPH_TYPEDEFS()
[220]131  ///macro.
132#define GRAPH_TYPEDEFS(Graph)                                           \
133  DIGRAPH_TYPEDEFS(Graph);                                              \
134  typedef Graph::Edge Edge;                                             \
135  typedef Graph::EdgeIt EdgeIt;                                         \
136  typedef Graph::IncEdgeIt IncEdgeIt;                                   \
137  typedef Graph::EdgeMap<bool> BoolEdgeMap;                             \
138  typedef Graph::EdgeMap<int> IntEdgeMap;                               \
[300]139  typedef Graph::EdgeMap<double> DoubleEdgeMap
[220]140
[300]141  ///Create convenience typedefs for the graph types and iterators
[220]142
143  ///\see GRAPH_TYPEDEFS
144  ///
145  ///\note Use this macro, if the graph type is a dependent type,
146  ///ie. the graph type depend on a template parameter.
147#define TEMPLATE_GRAPH_TYPEDEFS(Graph)                                  \
148  TEMPLATE_DIGRAPH_TYPEDEFS(Graph);                                     \
149  typedef typename Graph::Edge Edge;                                    \
150  typedef typename Graph::EdgeIt EdgeIt;                                \
151  typedef typename Graph::IncEdgeIt IncEdgeIt;                          \
152  typedef typename Graph::template EdgeMap<bool> BoolEdgeMap;           \
153  typedef typename Graph::template EdgeMap<int> IntEdgeMap;             \
[300]154  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
[220]155
[282]156  /// \brief Function to count the items in a graph.
[220]157  ///
[282]158  /// This function counts the items (nodes, arcs etc.) in a graph.
159  /// The complexity of the function is linear because
[220]160  /// it iterates on all of the items.
161  template <typename Graph, typename Item>
162  inline int countItems(const Graph& g) {
163    typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt;
164    int num = 0;
165    for (ItemIt it(g); it != INVALID; ++it) {
166      ++num;
167    }
168    return num;
169  }
170
171  // Node counting:
172
173  namespace _core_bits {
174
175    template <typename Graph, typename Enable = void>
176    struct CountNodesSelector {
177      static int count(const Graph &g) {
178        return countItems<Graph, typename Graph::Node>(g);
179      }
180    };
181
182    template <typename Graph>
183    struct CountNodesSelector<
184      Graph, typename
185      enable_if<typename Graph::NodeNumTag, void>::type>
186    {
187      static int count(const Graph &g) {
188        return g.nodeNum();
189      }
190    };
191  }
192
193  /// \brief Function to count the nodes in the graph.
194  ///
195  /// This function counts the nodes in the graph.
[282]196  /// The complexity of the function is <em>O</em>(<em>n</em>), but for some
197  /// graph structures it is specialized to run in <em>O</em>(1).
[220]198  ///
[282]199  /// \note If the graph contains a \c nodeNum() member function and a
200  /// \c NodeNumTag tag then this function calls directly the member
[220]201  /// function to query the cardinality of the node set.
202  template <typename Graph>
203  inline int countNodes(const Graph& g) {
204    return _core_bits::CountNodesSelector<Graph>::count(g);
205  }
206
207  // Arc counting:
208
209  namespace _core_bits {
210
211    template <typename Graph, typename Enable = void>
212    struct CountArcsSelector {
213      static int count(const Graph &g) {
214        return countItems<Graph, typename Graph::Arc>(g);
215      }
216    };
217
218    template <typename Graph>
219    struct CountArcsSelector<
220      Graph,
221      typename enable_if<typename Graph::ArcNumTag, void>::type>
222    {
223      static int count(const Graph &g) {
224        return g.arcNum();
225      }
226    };
227  }
228
229  /// \brief Function to count the arcs in the graph.
230  ///
231  /// This function counts the arcs in the graph.
[282]232  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
233  /// graph structures it is specialized to run in <em>O</em>(1).
[220]234  ///
[282]235  /// \note If the graph contains a \c arcNum() member function and a
236  /// \c ArcNumTag tag then this function calls directly the member
[220]237  /// function to query the cardinality of the arc set.
238  template <typename Graph>
239  inline int countArcs(const Graph& g) {
240    return _core_bits::CountArcsSelector<Graph>::count(g);
241  }
242
243  // Edge counting:
[282]244
[220]245  namespace _core_bits {
246
247    template <typename Graph, typename Enable = void>
248    struct CountEdgesSelector {
249      static int count(const Graph &g) {
250        return countItems<Graph, typename Graph::Edge>(g);
251      }
252    };
253
254    template <typename Graph>
255    struct CountEdgesSelector<
256      Graph,
257      typename enable_if<typename Graph::EdgeNumTag, void>::type>
258    {
259      static int count(const Graph &g) {
260        return g.edgeNum();
261      }
262    };
263  }
264
265  /// \brief Function to count the edges in the graph.
266  ///
267  /// This function counts the edges in the graph.
[282]268  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
269  /// graph structures it is specialized to run in <em>O</em>(1).
[220]270  ///
[282]271  /// \note If the graph contains a \c edgeNum() member function and a
272  /// \c EdgeNumTag tag then this function calls directly the member
[220]273  /// function to query the cardinality of the edge set.
274  template <typename Graph>
275  inline int countEdges(const Graph& g) {
276    return _core_bits::CountEdgesSelector<Graph>::count(g);
277
278  }
279
280
281  template <typename Graph, typename DegIt>
282  inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
283    int num = 0;
284    for (DegIt it(_g, _n); it != INVALID; ++it) {
285      ++num;
286    }
287    return num;
288  }
289
290  /// \brief Function to count the number of the out-arcs from node \c n.
291  ///
292  /// This function counts the number of the out-arcs from node \c n
[282]293  /// in the graph \c g.
[220]294  template <typename Graph>
[282]295  inline int countOutArcs(const Graph& g,  const typename Graph::Node& n) {
296    return countNodeDegree<Graph, typename Graph::OutArcIt>(g, n);
[220]297  }
298
299  /// \brief Function to count the number of the in-arcs to node \c n.
300  ///
301  /// This function counts the number of the in-arcs to node \c n
[282]302  /// in the graph \c g.
[220]303  template <typename Graph>
[282]304  inline int countInArcs(const Graph& g,  const typename Graph::Node& n) {
305    return countNodeDegree<Graph, typename Graph::InArcIt>(g, n);
[220]306  }
307
308  /// \brief Function to count the number of the inc-edges to node \c n.
309  ///
310  /// This function counts the number of the inc-edges to node \c n
[282]311  /// in the undirected graph \c g.
[220]312  template <typename Graph>
[282]313  inline int countIncEdges(const Graph& g,  const typename Graph::Node& n) {
314    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(g, n);
[220]315  }
316
317  namespace _core_bits {
318
319    template <typename Digraph, typename Item, typename RefMap>
320    class MapCopyBase {
321    public:
322      virtual void copy(const Digraph& from, const RefMap& refMap) = 0;
323
324      virtual ~MapCopyBase() {}
325    };
326
327    template <typename Digraph, typename Item, typename RefMap,
[282]328              typename FromMap, typename ToMap>
[220]329    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
330    public:
331
[282]332      MapCopy(const FromMap& map, ToMap& tmap)
333        : _map(map), _tmap(tmap) {}
[220]334
335      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
336        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
337        for (ItemIt it(digraph); it != INVALID; ++it) {
338          _tmap.set(refMap[it], _map[it]);
339        }
340      }
341
342    private:
[282]343      const FromMap& _map;
[220]344      ToMap& _tmap;
345    };
346
347    template <typename Digraph, typename Item, typename RefMap, typename It>
348    class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> {
349    public:
350
[282]351      ItemCopy(const Item& item, It& it) : _item(item), _it(it) {}
[220]352
353      virtual void copy(const Digraph&, const RefMap& refMap) {
354        _it = refMap[_item];
355      }
356
357    private:
[282]358      Item _item;
[220]359      It& _it;
360    };
361
362    template <typename Digraph, typename Item, typename RefMap, typename Ref>
363    class RefCopy : public MapCopyBase<Digraph, Item, RefMap> {
364    public:
365
366      RefCopy(Ref& map) : _map(map) {}
367
368      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
369        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
370        for (ItemIt it(digraph); it != INVALID; ++it) {
371          _map.set(it, refMap[it]);
372        }
373      }
374
375    private:
376      Ref& _map;
377    };
378
379    template <typename Digraph, typename Item, typename RefMap,
380              typename CrossRef>
381    class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> {
382    public:
383
384      CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {}
385
386      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
387        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
388        for (ItemIt it(digraph); it != INVALID; ++it) {
389          _cmap.set(refMap[it], it);
390        }
391      }
392
393    private:
394      CrossRef& _cmap;
395    };
396
397    template <typename Digraph, typename Enable = void>
398    struct DigraphCopySelector {
399      template <typename From, typename NodeRefMap, typename ArcRefMap>
[282]400      static void copy(const From& from, Digraph &to,
[220]401                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
[893]402        to.clear();
[220]403        for (typename From::NodeIt it(from); it != INVALID; ++it) {
404          nodeRefMap[it] = to.addNode();
405        }
406        for (typename From::ArcIt it(from); it != INVALID; ++it) {
407          arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)],
408                                    nodeRefMap[from.target(it)]);
409        }
410      }
411    };
412
413    template <typename Digraph>
414    struct DigraphCopySelector<
415      Digraph,
416      typename enable_if<typename Digraph::BuildTag, void>::type>
417    {
418      template <typename From, typename NodeRefMap, typename ArcRefMap>
[282]419      static void copy(const From& from, Digraph &to,
[220]420                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
421        to.build(from, nodeRefMap, arcRefMap);
422      }
423    };
424
425    template <typename Graph, typename Enable = void>
426    struct GraphCopySelector {
427      template <typename From, typename NodeRefMap, typename EdgeRefMap>
[282]428      static void copy(const From& from, Graph &to,
[220]429                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
[893]430        to.clear();
[220]431        for (typename From::NodeIt it(from); it != INVALID; ++it) {
432          nodeRefMap[it] = to.addNode();
433        }
434        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
435          edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)],
436                                      nodeRefMap[from.v(it)]);
437        }
438      }
439    };
440
441    template <typename Graph>
442    struct GraphCopySelector<
443      Graph,
444      typename enable_if<typename Graph::BuildTag, void>::type>
445    {
446      template <typename From, typename NodeRefMap, typename EdgeRefMap>
[282]447      static void copy(const From& from, Graph &to,
[220]448                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
449        to.build(from, nodeRefMap, edgeRefMap);
450      }
451    };
452
453  }
454
455  /// \brief Class to copy a digraph.
456  ///
457  /// Class to copy a digraph to another digraph (duplicate a digraph). The
[282]458  /// simplest way of using it is through the \c digraphCopy() function.
[220]459  ///
[282]460  /// This class not only make a copy of a digraph, but it can create
[220]461  /// references and cross references between the nodes and arcs of
[282]462  /// the two digraphs, and it can copy maps to use with the newly created
463  /// digraph.
[220]464  ///
[282]465  /// To make a copy from a digraph, first an instance of DigraphCopy
466  /// should be created, then the data belongs to the digraph should
[220]467  /// assigned to copy. In the end, the \c run() member should be
468  /// called.
469  ///
[282]470  /// The next code copies a digraph with several data:
[220]471  ///\code
[282]472  ///  DigraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
473  ///  // Create references for the nodes
[220]474  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
[282]475  ///  cg.nodeRef(nr);
476  ///  // Create cross references (inverse) for the arcs
[220]477  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
[282]478  ///  cg.arcCrossRef(acr);
479  ///  // Copy an arc map
[220]480  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
481  ///  NewGraph::ArcMap<double> namap(new_graph);
[282]482  ///  cg.arcMap(oamap, namap);
483  ///  // Copy a node
[220]484  ///  OrigGraph::Node on;
485  ///  NewGraph::Node nn;
[282]486  ///  cg.node(on, nn);
487  ///  // Execute copying
488  ///  cg.run();
[220]489  ///\endcode
[282]490  template <typename From, typename To>
[220]491  class DigraphCopy {
492  private:
493
494    typedef typename From::Node Node;
495    typedef typename From::NodeIt NodeIt;
496    typedef typename From::Arc Arc;
497    typedef typename From::ArcIt ArcIt;
498
499    typedef typename To::Node TNode;
500    typedef typename To::Arc TArc;
501
502    typedef typename From::template NodeMap<TNode> NodeRefMap;
503    typedef typename From::template ArcMap<TArc> ArcRefMap;
504
505  public:
506
[282]507    /// \brief Constructor of DigraphCopy.
[220]508    ///
[282]509    /// Constructor of DigraphCopy for copying the content of the
510    /// \c from digraph into the \c to digraph.
511    DigraphCopy(const From& from, To& to)
[220]512      : _from(from), _to(to) {}
513
[282]514    /// \brief Destructor of DigraphCopy
[220]515    ///
[282]516    /// Destructor of DigraphCopy.
[220]517    ~DigraphCopy() {
518      for (int i = 0; i < int(_node_maps.size()); ++i) {
519        delete _node_maps[i];
520      }
521      for (int i = 0; i < int(_arc_maps.size()); ++i) {
522        delete _arc_maps[i];
523      }
524
525    }
526
[282]527    /// \brief Copy the node references into the given map.
[220]528    ///
[282]529    /// This function copies the node references into the given map.
530    /// The parameter should be a map, whose key type is the Node type of
531    /// the source digraph, while the value type is the Node type of the
532    /// destination digraph.
[220]533    template <typename NodeRef>
534    DigraphCopy& nodeRef(NodeRef& map) {
535      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
536                           NodeRefMap, NodeRef>(map));
537      return *this;
538    }
539
[282]540    /// \brief Copy the node cross references into the given map.
[220]541    ///
[282]542    /// This function copies the node cross references (reverse references)
543    /// into the given map. The parameter should be a map, whose key type
544    /// is the Node type of the destination digraph, while the value type is
545    /// the Node type of the source digraph.
[220]546    template <typename NodeCrossRef>
547    DigraphCopy& nodeCrossRef(NodeCrossRef& map) {
548      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
549                           NodeRefMap, NodeCrossRef>(map));
550      return *this;
551    }
552
[282]553    /// \brief Make a copy of the given node map.
[220]554    ///
[282]555    /// This function makes a copy of the given node map for the newly
556    /// created digraph.
557    /// The key type of the new map \c tmap should be the Node type of the
558    /// destination digraph, and the key type of the original map \c map
559    /// should be the Node type of the source digraph.
560    template <typename FromMap, typename ToMap>
561    DigraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
[220]562      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
[282]563                           NodeRefMap, FromMap, ToMap>(map, tmap));
[220]564      return *this;
565    }
566
567    /// \brief Make a copy of the given node.
568    ///
[282]569    /// This function makes a copy of the given node.
570    DigraphCopy& node(const Node& node, TNode& tnode) {
[220]571      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
[282]572                           NodeRefMap, TNode>(node, tnode));
[220]573      return *this;
574    }
575
[282]576    /// \brief Copy the arc references into the given map.
[220]577    ///
[282]578    /// This function copies the arc references into the given map.
579    /// The parameter should be a map, whose key type is the Arc type of
580    /// the source digraph, while the value type is the Arc type of the
581    /// destination digraph.
[220]582    template <typename ArcRef>
583    DigraphCopy& arcRef(ArcRef& map) {
584      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
585                          ArcRefMap, ArcRef>(map));
586      return *this;
587    }
588
[282]589    /// \brief Copy the arc cross references into the given map.
[220]590    ///
[282]591    /// This function copies the arc cross references (reverse references)
592    /// into the given map. The parameter should be a map, whose key type
593    /// is the Arc type of the destination digraph, while the value type is
594    /// the Arc type of the source digraph.
[220]595    template <typename ArcCrossRef>
596    DigraphCopy& arcCrossRef(ArcCrossRef& map) {
597      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
598                          ArcRefMap, ArcCrossRef>(map));
599      return *this;
600    }
601
[282]602    /// \brief Make a copy of the given arc map.
[220]603    ///
[282]604    /// This function makes a copy of the given arc map for the newly
605    /// created digraph.
606    /// The key type of the new map \c tmap should be the Arc type of the
607    /// destination digraph, and the key type of the original map \c map
608    /// should be the Arc type of the source digraph.
609    template <typename FromMap, typename ToMap>
610    DigraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
[220]611      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
[282]612                          ArcRefMap, FromMap, ToMap>(map, tmap));
[220]613      return *this;
614    }
615
616    /// \brief Make a copy of the given arc.
617    ///
[282]618    /// This function makes a copy of the given arc.
619    DigraphCopy& arc(const Arc& arc, TArc& tarc) {
[220]620      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
[282]621                          ArcRefMap, TArc>(arc, tarc));
[220]622      return *this;
623    }
624
[282]625    /// \brief Execute copying.
[220]626    ///
[282]627    /// This function executes the copying of the digraph along with the
628    /// copying of the assigned data.
[220]629    void run() {
630      NodeRefMap nodeRefMap(_from);
631      ArcRefMap arcRefMap(_from);
632      _core_bits::DigraphCopySelector<To>::
[282]633        copy(_from, _to, nodeRefMap, arcRefMap);
[220]634      for (int i = 0; i < int(_node_maps.size()); ++i) {
635        _node_maps[i]->copy(_from, nodeRefMap);
636      }
637      for (int i = 0; i < int(_arc_maps.size()); ++i) {
638        _arc_maps[i]->copy(_from, arcRefMap);
639      }
640    }
641
642  protected:
643
644    const From& _from;
645    To& _to;
646
647    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
[282]648      _node_maps;
[220]649
650    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
[282]651      _arc_maps;
[220]652
653  };
654
655  /// \brief Copy a digraph to another digraph.
656  ///
[282]657  /// This function copies a digraph to another digraph.
658  /// The complete usage of it is detailed in the DigraphCopy class, but
659  /// a short example shows a basic work:
[220]660  ///\code
[282]661  /// digraphCopy(src, trg).nodeRef(nr).arcCrossRef(acr).run();
[220]662  ///\endcode
663  ///
664  /// After the copy the \c nr map will contain the mapping from the
665  /// nodes of the \c from digraph to the nodes of the \c to digraph and
[282]666  /// \c acr will contain the mapping from the arcs of the \c to digraph
[220]667  /// to the arcs of the \c from digraph.
668  ///
669  /// \see DigraphCopy
[282]670  template <typename From, typename To>
671  DigraphCopy<From, To> digraphCopy(const From& from, To& to) {
672    return DigraphCopy<From, To>(from, to);
[220]673  }
674
675  /// \brief Class to copy a graph.
676  ///
677  /// Class to copy a graph to another graph (duplicate a graph). The
[282]678  /// simplest way of using it is through the \c graphCopy() function.
[220]679  ///
[282]680  /// This class not only make a copy of a graph, but it can create
[220]681  /// references and cross references between the nodes, edges and arcs of
[282]682  /// the two graphs, and it can copy maps for using with the newly created
683  /// graph.
[220]684  ///
685  /// To make a copy from a graph, first an instance of GraphCopy
686  /// should be created, then the data belongs to the graph should
687  /// assigned to copy. In the end, the \c run() member should be
688  /// called.
689  ///
690  /// The next code copies a graph with several data:
691  ///\code
[282]692  ///  GraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
693  ///  // Create references for the nodes
[220]694  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
[282]695  ///  cg.nodeRef(nr);
696  ///  // Create cross references (inverse) for the edges
697  ///  NewGraph::EdgeMap<OrigGraph::Edge> ecr(new_graph);
698  ///  cg.edgeCrossRef(ecr);
699  ///  // Copy an edge map
700  ///  OrigGraph::EdgeMap<double> oemap(orig_graph);
701  ///  NewGraph::EdgeMap<double> nemap(new_graph);
702  ///  cg.edgeMap(oemap, nemap);
703  ///  // Copy a node
[220]704  ///  OrigGraph::Node on;
705  ///  NewGraph::Node nn;
[282]706  ///  cg.node(on, nn);
707  ///  // Execute copying
708  ///  cg.run();
[220]709  ///\endcode
[282]710  template <typename From, typename To>
[220]711  class GraphCopy {
712  private:
713
714    typedef typename From::Node Node;
715    typedef typename From::NodeIt NodeIt;
716    typedef typename From::Arc Arc;
717    typedef typename From::ArcIt ArcIt;
718    typedef typename From::Edge Edge;
719    typedef typename From::EdgeIt EdgeIt;
720
721    typedef typename To::Node TNode;
722    typedef typename To::Arc TArc;
723    typedef typename To::Edge TEdge;
724
725    typedef typename From::template NodeMap<TNode> NodeRefMap;
726    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
727
728    struct ArcRefMap {
[282]729      ArcRefMap(const From& from, const To& to,
[220]730                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
[282]731        : _from(from), _to(to),
[220]732          _edge_ref(edge_ref), _node_ref(node_ref) {}
733
734      typedef typename From::Arc Key;
735      typedef typename To::Arc Value;
736
737      Value operator[](const Key& key) const {
738        bool forward = _from.u(key) != _from.v(key) ?
739          _node_ref[_from.source(key)] ==
740          _to.source(_to.direct(_edge_ref[key], true)) :
741          _from.direction(key);
742        return _to.direct(_edge_ref[key], forward);
743      }
744
[282]745      const From& _from;
[220]746      const To& _to;
747      const EdgeRefMap& _edge_ref;
748      const NodeRefMap& _node_ref;
749    };
750
751  public:
752
[282]753    /// \brief Constructor of GraphCopy.
[220]754    ///
[282]755    /// Constructor of GraphCopy for copying the content of the
756    /// \c from graph into the \c to graph.
757    GraphCopy(const From& from, To& to)
[220]758      : _from(from), _to(to) {}
759
[282]760    /// \brief Destructor of GraphCopy
[220]761    ///
[282]762    /// Destructor of GraphCopy.
[220]763    ~GraphCopy() {
764      for (int i = 0; i < int(_node_maps.size()); ++i) {
765        delete _node_maps[i];
766      }
767      for (int i = 0; i < int(_arc_maps.size()); ++i) {
768        delete _arc_maps[i];
769      }
770      for (int i = 0; i < int(_edge_maps.size()); ++i) {
771        delete _edge_maps[i];
772      }
773    }
774
[282]775    /// \brief Copy the node references into the given map.
[220]776    ///
[282]777    /// This function copies the node references into the given map.
778    /// The parameter should be a map, whose key type is the Node type of
779    /// the source graph, while the value type is the Node type of the
780    /// destination graph.
[220]781    template <typename NodeRef>
782    GraphCopy& nodeRef(NodeRef& map) {
783      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
784                           NodeRefMap, NodeRef>(map));
785      return *this;
786    }
787
[282]788    /// \brief Copy the node cross references into the given map.
[220]789    ///
[282]790    /// This function copies the node cross references (reverse references)
791    /// into the given map. The parameter should be a map, whose key type
792    /// is the Node type of the destination graph, while the value type is
793    /// the Node type of the source graph.
[220]794    template <typename NodeCrossRef>
795    GraphCopy& nodeCrossRef(NodeCrossRef& map) {
796      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
797                           NodeRefMap, NodeCrossRef>(map));
798      return *this;
799    }
800
[282]801    /// \brief Make a copy of the given node map.
[220]802    ///
[282]803    /// This function makes a copy of the given node map for the newly
804    /// created graph.
805    /// The key type of the new map \c tmap should be the Node type of the
806    /// destination graph, and the key type of the original map \c map
807    /// should be the Node type of the source graph.
808    template <typename FromMap, typename ToMap>
809    GraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
[220]810      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
[282]811                           NodeRefMap, FromMap, ToMap>(map, tmap));
[220]812      return *this;
813    }
814
815    /// \brief Make a copy of the given node.
816    ///
[282]817    /// This function makes a copy of the given node.
818    GraphCopy& node(const Node& node, TNode& tnode) {
[220]819      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
[282]820                           NodeRefMap, TNode>(node, tnode));
[220]821      return *this;
822    }
823
[282]824    /// \brief Copy the arc references into the given map.
[220]825    ///
[282]826    /// This function copies the arc references into the given map.
827    /// The parameter should be a map, whose key type is the Arc type of
828    /// the source graph, while the value type is the Arc type of the
829    /// destination graph.
[220]830    template <typename ArcRef>
831    GraphCopy& arcRef(ArcRef& map) {
832      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
833                          ArcRefMap, ArcRef>(map));
834      return *this;
835    }
836
[282]837    /// \brief Copy the arc cross references into the given map.
[220]838    ///
[282]839    /// This function copies the arc cross references (reverse references)
840    /// into the given map. The parameter should be a map, whose key type
841    /// is the Arc type of the destination graph, while the value type is
842    /// the Arc type of the source graph.
[220]843    template <typename ArcCrossRef>
844    GraphCopy& arcCrossRef(ArcCrossRef& map) {
845      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
846                          ArcRefMap, ArcCrossRef>(map));
847      return *this;
848    }
849
[282]850    /// \brief Make a copy of the given arc map.
[220]851    ///
[282]852    /// This function makes a copy of the given arc map for the newly
853    /// created graph.
854    /// The key type of the new map \c tmap should be the Arc type of the
855    /// destination graph, and the key type of the original map \c map
856    /// should be the Arc type of the source graph.
857    template <typename FromMap, typename ToMap>
858    GraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
[220]859      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
[282]860                          ArcRefMap, FromMap, ToMap>(map, tmap));
[220]861      return *this;
862    }
863
864    /// \brief Make a copy of the given arc.
865    ///
[282]866    /// This function makes a copy of the given arc.
867    GraphCopy& arc(const Arc& arc, TArc& tarc) {
[220]868      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
[282]869                          ArcRefMap, TArc>(arc, tarc));
[220]870      return *this;
871    }
872
[282]873    /// \brief Copy the edge references into the given map.
[220]874    ///
[282]875    /// This function copies the edge references into the given map.
876    /// The parameter should be a map, whose key type is the Edge type of
877    /// the source graph, while the value type is the Edge type of the
878    /// destination graph.
[220]879    template <typename EdgeRef>
880    GraphCopy& edgeRef(EdgeRef& map) {
881      _edge_maps.push_back(new _core_bits::RefCopy<From, Edge,
882                           EdgeRefMap, EdgeRef>(map));
883      return *this;
884    }
885
[282]886    /// \brief Copy the edge cross references into the given map.
[220]887    ///
[282]888    /// This function copies the edge cross references (reverse references)
889    /// into the given map. The parameter should be a map, whose key type
890    /// is the Edge type of the destination graph, while the value type is
891    /// the Edge type of the source graph.
[220]892    template <typename EdgeCrossRef>
893    GraphCopy& edgeCrossRef(EdgeCrossRef& map) {
894      _edge_maps.push_back(new _core_bits::CrossRefCopy<From,
895                           Edge, EdgeRefMap, EdgeCrossRef>(map));
896      return *this;
897    }
898
[282]899    /// \brief Make a copy of the given edge map.
[220]900    ///
[282]901    /// This function makes a copy of the given edge map for the newly
902    /// created graph.
903    /// The key type of the new map \c tmap should be the Edge type of the
904    /// destination graph, and the key type of the original map \c map
905    /// should be the Edge type of the source graph.
906    template <typename FromMap, typename ToMap>
907    GraphCopy& edgeMap(const FromMap& map, ToMap& tmap) {
[220]908      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
[282]909                           EdgeRefMap, FromMap, ToMap>(map, tmap));
[220]910      return *this;
911    }
912
913    /// \brief Make a copy of the given edge.
914    ///
[282]915    /// This function makes a copy of the given edge.
916    GraphCopy& edge(const Edge& edge, TEdge& tedge) {
[220]917      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
[282]918                           EdgeRefMap, TEdge>(edge, tedge));
[220]919      return *this;
920    }
921
[282]922    /// \brief Execute copying.
[220]923    ///
[282]924    /// This function executes the copying of the graph along with the
925    /// copying of the assigned data.
[220]926    void run() {
927      NodeRefMap nodeRefMap(_from);
928      EdgeRefMap edgeRefMap(_from);
[282]929      ArcRefMap arcRefMap(_from, _to, edgeRefMap, nodeRefMap);
[220]930      _core_bits::GraphCopySelector<To>::
[282]931        copy(_from, _to, nodeRefMap, edgeRefMap);
[220]932      for (int i = 0; i < int(_node_maps.size()); ++i) {
933        _node_maps[i]->copy(_from, nodeRefMap);
934      }
935      for (int i = 0; i < int(_edge_maps.size()); ++i) {
936        _edge_maps[i]->copy(_from, edgeRefMap);
937      }
938      for (int i = 0; i < int(_arc_maps.size()); ++i) {
939        _arc_maps[i]->copy(_from, arcRefMap);
940      }
941    }
942
943  private:
944
945    const From& _from;
946    To& _to;
947
948    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
[282]949      _node_maps;
[220]950
951    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
[282]952      _arc_maps;
[220]953
954    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
[282]955      _edge_maps;
[220]956
957  };
958
959  /// \brief Copy a graph to another graph.
960  ///
[282]961  /// This function copies a graph to another graph.
962  /// The complete usage of it is detailed in the GraphCopy class,
963  /// but a short example shows a basic work:
[220]964  ///\code
[282]965  /// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run();
[220]966  ///\endcode
967  ///
968  /// After the copy the \c nr map will contain the mapping from the
969  /// nodes of the \c from graph to the nodes of the \c to graph and
[282]970  /// \c ecr will contain the mapping from the edges of the \c to graph
971  /// to the edges of the \c from graph.
[220]972  ///
973  /// \see GraphCopy
[282]974  template <typename From, typename To>
975  GraphCopy<From, To>
976  graphCopy(const From& from, To& to) {
977    return GraphCopy<From, To>(from, to);
[220]978  }
979
980  namespace _core_bits {
981
982    template <typename Graph, typename Enable = void>
983    struct FindArcSelector {
984      typedef typename Graph::Node Node;
985      typedef typename Graph::Arc Arc;
986      static Arc find(const Graph &g, Node u, Node v, Arc e) {
987        if (e == INVALID) {
988          g.firstOut(e, u);
989        } else {
990          g.nextOut(e);
991        }
992        while (e != INVALID && g.target(e) != v) {
993          g.nextOut(e);
994        }
995        return e;
996      }
997    };
998
999    template <typename Graph>
1000    struct FindArcSelector<
1001      Graph,
[282]1002      typename enable_if<typename Graph::FindArcTag, void>::type>
[220]1003    {
1004      typedef typename Graph::Node Node;
1005      typedef typename Graph::Arc Arc;
1006      static Arc find(const Graph &g, Node u, Node v, Arc prev) {
1007        return g.findArc(u, v, prev);
1008      }
1009    };
1010  }
1011
[282]1012  /// \brief Find an arc between two nodes of a digraph.
[220]1013  ///
[282]1014  /// This function finds an arc from node \c u to node \c v in the
1015  /// digraph \c g.
[220]1016  ///
1017  /// If \c prev is \ref INVALID (this is the default value), then
1018  /// it finds the first arc from \c u to \c v. Otherwise it looks for
1019  /// the next arc from \c u to \c v after \c prev.
1020  /// \return The found arc or \ref INVALID if there is no such an arc.
1021  ///
1022  /// Thus you can iterate through each arc from \c u to \c v as it follows.
1023  ///\code
[282]1024  /// for(Arc e = findArc(g,u,v); e != INVALID; e = findArc(g,u,v,e)) {
[220]1025  ///   ...
1026  /// }
1027  ///\endcode
1028  ///
[282]1029  /// \note \ref ConArcIt provides iterator interface for the same
1030  /// functionality.
1031  ///
[220]1032  ///\sa ConArcIt
[282]1033  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
[220]1034  template <typename Graph>
1035  inline typename Graph::Arc
1036  findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1037          typename Graph::Arc prev = INVALID) {
1038    return _core_bits::FindArcSelector<Graph>::find(g, u, v, prev);
1039  }
1040
[282]1041  /// \brief Iterator for iterating on parallel arcs connecting the same nodes.
[220]1042  ///
[282]1043  /// Iterator for iterating on parallel arcs connecting the same nodes. It is
1044  /// a higher level interface for the \ref findArc() function. You can
[220]1045  /// use it the following way:
1046  ///\code
1047  /// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) {
1048  ///   ...
1049  /// }
1050  ///\endcode
1051  ///
1052  ///\sa findArc()
[282]1053  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
[559]1054  template <typename GR>
1055  class ConArcIt : public GR::Arc {
[617]1056    typedef typename GR::Arc Parent;
1057
[220]1058  public:
1059
[617]1060    typedef typename GR::Arc Arc;
1061    typedef typename GR::Node Node;
[220]1062
1063    /// \brief Constructor.
1064    ///
[282]1065    /// Construct a new ConArcIt iterating on the arcs that
1066    /// connects nodes \c u and \c v.
[617]1067    ConArcIt(const GR& g, Node u, Node v) : _graph(g) {
[220]1068      Parent::operator=(findArc(_graph, u, v));
1069    }
1070
1071    /// \brief Constructor.
1072    ///
[282]1073    /// Construct a new ConArcIt that continues the iterating from arc \c a.
[617]1074    ConArcIt(const GR& g, Arc a) : Parent(a), _graph(g) {}
[220]1075
1076    /// \brief Increment operator.
1077    ///
1078    /// It increments the iterator and gives back the next arc.
1079    ConArcIt& operator++() {
1080      Parent::operator=(findArc(_graph, _graph.source(*this),
1081                                _graph.target(*this), *this));
1082      return *this;
1083    }
1084  private:
[617]1085    const GR& _graph;
[220]1086  };
1087
1088  namespace _core_bits {
1089
1090    template <typename Graph, typename Enable = void>
1091    struct FindEdgeSelector {
1092      typedef typename Graph::Node Node;
1093      typedef typename Graph::Edge Edge;
1094      static Edge find(const Graph &g, Node u, Node v, Edge e) {
1095        bool b;
1096        if (u != v) {
1097          if (e == INVALID) {
1098            g.firstInc(e, b, u);
1099          } else {
1100            b = g.u(e) == u;
1101            g.nextInc(e, b);
1102          }
1103          while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) {
1104            g.nextInc(e, b);
1105          }
1106        } else {
1107          if (e == INVALID) {
1108            g.firstInc(e, b, u);
1109          } else {
1110            b = true;
1111            g.nextInc(e, b);
1112          }
1113          while (e != INVALID && (!b || g.v(e) != v)) {
1114            g.nextInc(e, b);
1115          }
1116        }
1117        return e;
1118      }
1119    };
1120
1121    template <typename Graph>
1122    struct FindEdgeSelector<
1123      Graph,
1124      typename enable_if<typename Graph::FindEdgeTag, void>::type>
1125    {
1126      typedef typename Graph::Node Node;
1127      typedef typename Graph::Edge Edge;
1128      static Edge find(const Graph &g, Node u, Node v, Edge prev) {
1129        return g.findEdge(u, v, prev);
1130      }
1131    };
1132  }
1133
[282]1134  /// \brief Find an edge between two nodes of a graph.
[220]1135  ///
[282]1136  /// This function finds an edge from node \c u to node \c v in graph \c g.
1137  /// If node \c u and node \c v is equal then each loop edge
[220]1138  /// will be enumerated once.
1139  ///
1140  /// If \c prev is \ref INVALID (this is the default value), then
[282]1141  /// it finds the first edge from \c u to \c v. Otherwise it looks for
1142  /// the next edge from \c u to \c v after \c prev.
1143  /// \return The found edge or \ref INVALID if there is no such an edge.
[220]1144  ///
[282]1145  /// Thus you can iterate through each edge between \c u and \c v
1146  /// as it follows.
[220]1147  ///\code
[282]1148  /// for(Edge e = findEdge(g,u,v); e != INVALID; e = findEdge(g,u,v,e)) {
[220]1149  ///   ...
1150  /// }
1151  ///\endcode
1152  ///
[282]1153  /// \note \ref ConEdgeIt provides iterator interface for the same
1154  /// functionality.
1155  ///
[220]1156  ///\sa ConEdgeIt
1157  template <typename Graph>
1158  inline typename Graph::Edge
1159  findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1160            typename Graph::Edge p = INVALID) {
1161    return _core_bits::FindEdgeSelector<Graph>::find(g, u, v, p);
1162  }
1163
[282]1164  /// \brief Iterator for iterating on parallel edges connecting the same nodes.
[220]1165  ///
[282]1166  /// Iterator for iterating on parallel edges connecting the same nodes.
1167  /// It is a higher level interface for the findEdge() function. You can
[220]1168  /// use it the following way:
1169  ///\code
[282]1170  /// for (ConEdgeIt<Graph> it(g, u, v); it != INVALID; ++it) {
[220]1171  ///   ...
1172  /// }
1173  ///\endcode
1174  ///
1175  ///\sa findEdge()
[559]1176  template <typename GR>
1177  class ConEdgeIt : public GR::Edge {
[617]1178    typedef typename GR::Edge Parent;
1179
[220]1180  public:
1181
[617]1182    typedef typename GR::Edge Edge;
1183    typedef typename GR::Node Node;
[220]1184
1185    /// \brief Constructor.
1186    ///
[282]1187    /// Construct a new ConEdgeIt iterating on the edges that
1188    /// connects nodes \c u and \c v.
[617]1189    ConEdgeIt(const GR& g, Node u, Node v) : _graph(g), _u(u), _v(v) {
[429]1190      Parent::operator=(findEdge(_graph, _u, _v));
[220]1191    }
1192
1193    /// \brief Constructor.
1194    ///
[282]1195    /// Construct a new ConEdgeIt that continues iterating from edge \c e.
[617]1196    ConEdgeIt(const GR& g, Edge e) : Parent(e), _graph(g) {}
[220]1197
1198    /// \brief Increment operator.
1199    ///
1200    /// It increments the iterator and gives back the next edge.
1201    ConEdgeIt& operator++() {
[429]1202      Parent::operator=(findEdge(_graph, _u, _v, *this));
[220]1203      return *this;
1204    }
1205  private:
[617]1206    const GR& _graph;
[429]1207    Node _u, _v;
[220]1208  };
1209
1210
[282]1211  ///Dynamic arc look-up between given endpoints.
[220]1212
1213  ///Using this class, you can find an arc in a digraph from a given
[282]1214  ///source to a given target in amortized time <em>O</em>(log<em>d</em>),
[220]1215  ///where <em>d</em> is the out-degree of the source node.
1216  ///
1217  ///It is possible to find \e all parallel arcs between two nodes with
[233]1218  ///the \c operator() member.
[220]1219  ///
[282]1220  ///This is a dynamic data structure. Consider to use \ref ArcLookUp or
1221  ///\ref AllArcLookUp if your digraph is not changed so frequently.
[220]1222  ///
[282]1223  ///This class uses a self-adjusting binary search tree, the Splay tree
1224  ///of Sleator and Tarjan to guarantee the logarithmic amortized
1225  ///time bound for arc look-ups. This class also guarantees the
[220]1226  ///optimal time bound in a constant factor for any distribution of
1227  ///queries.
1228  ///
[559]1229  ///\tparam GR The type of the underlying digraph.
[220]1230  ///
1231  ///\sa ArcLookUp
1232  ///\sa AllArcLookUp
[559]1233  template <typename GR>
[220]1234  class DynArcLookUp
[559]1235    : protected ItemSetTraits<GR, typename GR::Arc>::ItemNotifier::ObserverBase
[220]1236  {
[559]1237    typedef typename ItemSetTraits<GR, typename GR::Arc>
[220]1238    ::ItemNotifier::ObserverBase Parent;
1239
[559]1240    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
[617]1241
1242  public:
1243
1244    /// The Digraph type
[559]1245    typedef GR Digraph;
[220]1246
1247  protected:
1248
[877]1249    class AutoNodeMap : public ItemSetTraits<GR, Node>::template Map<Arc>::Type
1250    {
[617]1251      typedef typename ItemSetTraits<GR, Node>::template Map<Arc>::Type Parent;
1252
[220]1253    public:
1254
[559]1255      AutoNodeMap(const GR& digraph) : Parent(digraph, INVALID) {}
[220]1256
1257      virtual void add(const Node& node) {
1258        Parent::add(node);
1259        Parent::set(node, INVALID);
1260      }
1261
1262      virtual void add(const std::vector<Node>& nodes) {
1263        Parent::add(nodes);
1264        for (int i = 0; i < int(nodes.size()); ++i) {
1265          Parent::set(nodes[i], INVALID);
1266        }
1267      }
1268
1269      virtual void build() {
1270        Parent::build();
1271        Node it;
1272        typename Parent::Notifier* nf = Parent::notifier();
1273        for (nf->first(it); it != INVALID; nf->next(it)) {
1274          Parent::set(it, INVALID);
1275        }
1276      }
1277    };
1278
1279    class ArcLess {
1280      const Digraph &g;
1281    public:
1282      ArcLess(const Digraph &_g) : g(_g) {}
1283      bool operator()(Arc a,Arc b) const
1284      {
1285        return g.target(a)<g.target(b);
1286      }
1287    };
1288
[877]1289  protected:
[617]1290
1291    const Digraph &_g;
1292    AutoNodeMap _head;
1293    typename Digraph::template ArcMap<Arc> _parent;
1294    typename Digraph::template ArcMap<Arc> _left;
1295    typename Digraph::template ArcMap<Arc> _right;
1296
[220]1297  public:
1298
1299    ///Constructor
1300
1301    ///Constructor.
1302    ///
1303    ///It builds up the search database.
1304    DynArcLookUp(const Digraph &g)
1305      : _g(g),_head(g),_parent(g),_left(g),_right(g)
1306    {
1307      Parent::attach(_g.notifier(typename Digraph::Arc()));
1308      refresh();
1309    }
1310
1311  protected:
1312
1313    virtual void add(const Arc& arc) {
1314      insert(arc);
1315    }
1316
1317    virtual void add(const std::vector<Arc>& arcs) {
1318      for (int i = 0; i < int(arcs.size()); ++i) {
1319        insert(arcs[i]);
1320      }
1321    }
1322
1323    virtual void erase(const Arc& arc) {
1324      remove(arc);
1325    }
1326
1327    virtual void erase(const std::vector<Arc>& arcs) {
1328      for (int i = 0; i < int(arcs.size()); ++i) {
1329        remove(arcs[i]);
1330      }
1331    }
1332
1333    virtual void build() {
1334      refresh();
1335    }
1336
1337    virtual void clear() {
1338      for(NodeIt n(_g);n!=INVALID;++n) {
[581]1339        _head[n] = INVALID;
[220]1340      }
1341    }
1342
1343    void insert(Arc arc) {
1344      Node s = _g.source(arc);
1345      Node t = _g.target(arc);
[581]1346      _left[arc] = INVALID;
1347      _right[arc] = INVALID;
[220]1348
1349      Arc e = _head[s];
1350      if (e == INVALID) {
[581]1351        _head[s] = arc;
1352        _parent[arc] = INVALID;
[220]1353        return;
1354      }
1355      while (true) {
1356        if (t < _g.target(e)) {
1357          if (_left[e] == INVALID) {
[581]1358            _left[e] = arc;
1359            _parent[arc] = e;
[220]1360            splay(arc);
1361            return;
1362          } else {
1363            e = _left[e];
1364          }
1365        } else {
1366          if (_right[e] == INVALID) {
[581]1367            _right[e] = arc;
1368            _parent[arc] = e;
[220]1369            splay(arc);
1370            return;
1371          } else {
1372            e = _right[e];
1373          }
1374        }
1375      }
1376    }
1377
1378    void remove(Arc arc) {
1379      if (_left[arc] == INVALID) {
1380        if (_right[arc] != INVALID) {
[581]1381          _parent[_right[arc]] = _parent[arc];
[220]1382        }
1383        if (_parent[arc] != INVALID) {
1384          if (_left[_parent[arc]] == arc) {
[581]1385            _left[_parent[arc]] = _right[arc];
[220]1386          } else {
[581]1387            _right[_parent[arc]] = _right[arc];
[220]1388          }
1389        } else {
[581]1390          _head[_g.source(arc)] = _right[arc];
[220]1391        }
1392      } else if (_right[arc] == INVALID) {
[581]1393        _parent[_left[arc]] = _parent[arc];
[220]1394        if (_parent[arc] != INVALID) {
1395          if (_left[_parent[arc]] == arc) {
[581]1396            _left[_parent[arc]] = _left[arc];
[220]1397          } else {
[581]1398            _right[_parent[arc]] = _left[arc];
[220]1399          }
1400        } else {
[581]1401          _head[_g.source(arc)] = _left[arc];
[220]1402        }
1403      } else {
1404        Arc e = _left[arc];
1405        if (_right[e] != INVALID) {
1406          e = _right[e];
1407          while (_right[e] != INVALID) {
1408            e = _right[e];
1409          }
1410          Arc s = _parent[e];
[581]1411          _right[_parent[e]] = _left[e];
[220]1412          if (_left[e] != INVALID) {
[581]1413            _parent[_left[e]] = _parent[e];
[220]1414          }
1415
[581]1416          _left[e] = _left[arc];
1417          _parent[_left[arc]] = e;
1418          _right[e] = _right[arc];
1419          _parent[_right[arc]] = e;
[220]1420
[581]1421          _parent[e] = _parent[arc];
[220]1422          if (_parent[arc] != INVALID) {
1423            if (_left[_parent[arc]] == arc) {
[581]1424              _left[_parent[arc]] = e;
[220]1425            } else {
[581]1426              _right[_parent[arc]] = e;
[220]1427            }
1428          }
1429          splay(s);
1430        } else {
[581]1431          _right[e] = _right[arc];
1432          _parent[_right[arc]] = e;
1433          _parent[e] = _parent[arc];
[220]1434
1435          if (_parent[arc] != INVALID) {
1436            if (_left[_parent[arc]] == arc) {
[581]1437              _left[_parent[arc]] = e;
[220]1438            } else {
[581]1439              _right[_parent[arc]] = e;
[220]1440            }
1441          } else {
[581]1442            _head[_g.source(arc)] = e;
[220]1443          }
1444        }
1445      }
1446    }
1447
1448    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1449    {
1450      int m=(a+b)/2;
1451      Arc me=v[m];
1452      if (a < m) {
1453        Arc left = refreshRec(v,a,m-1);
[581]1454        _left[me] = left;
1455        _parent[left] = me;
[220]1456      } else {
[581]1457        _left[me] = INVALID;
[220]1458      }
1459      if (m < b) {
1460        Arc right = refreshRec(v,m+1,b);
[581]1461        _right[me] = right;
1462        _parent[right] = me;
[220]1463      } else {
[581]1464        _right[me] = INVALID;
[220]1465      }
1466      return me;
1467    }
1468
1469    void refresh() {
1470      for(NodeIt n(_g);n!=INVALID;++n) {
1471        std::vector<Arc> v;
[233]1472        for(OutArcIt a(_g,n);a!=INVALID;++a) v.push_back(a);
1473        if (!v.empty()) {
[220]1474          std::sort(v.begin(),v.end(),ArcLess(_g));
1475          Arc head = refreshRec(v,0,v.size()-1);
[581]1476          _head[n] = head;
1477          _parent[head] = INVALID;
[220]1478        }
[581]1479        else _head[n] = INVALID;
[220]1480      }
1481    }
1482
1483    void zig(Arc v) {
1484      Arc w = _parent[v];
[581]1485      _parent[v] = _parent[w];
1486      _parent[w] = v;
1487      _left[w] = _right[v];
1488      _right[v] = w;
[220]1489      if (_parent[v] != INVALID) {
1490        if (_right[_parent[v]] == w) {
[581]1491          _right[_parent[v]] = v;
[220]1492        } else {
[581]1493          _left[_parent[v]] = v;
[220]1494        }
1495      }
1496      if (_left[w] != INVALID){
[581]1497        _parent[_left[w]] = w;
[220]1498      }
1499    }
1500
1501    void zag(Arc v) {
1502      Arc w = _parent[v];
[581]1503      _parent[v] = _parent[w];
1504      _parent[w] = v;
1505      _right[w] = _left[v];
1506      _left[v] = w;
[220]1507      if (_parent[v] != INVALID){
1508        if (_left[_parent[v]] == w) {
[581]1509          _left[_parent[v]] = v;
[220]1510        } else {
[581]1511          _right[_parent[v]] = v;
[220]1512        }
1513      }
1514      if (_right[w] != INVALID){
[581]1515        _parent[_right[w]] = w;
[220]1516      }
1517    }
1518
1519    void splay(Arc v) {
1520      while (_parent[v] != INVALID) {
1521        if (v == _left[_parent[v]]) {
1522          if (_parent[_parent[v]] == INVALID) {
1523            zig(v);
1524          } else {
1525            if (_parent[v] == _left[_parent[_parent[v]]]) {
1526              zig(_parent[v]);
1527              zig(v);
1528            } else {
1529              zig(v);
1530              zag(v);
1531            }
1532          }
1533        } else {
1534          if (_parent[_parent[v]] == INVALID) {
1535            zag(v);
1536          } else {
1537            if (_parent[v] == _left[_parent[_parent[v]]]) {
1538              zag(v);
1539              zig(v);
1540            } else {
1541              zag(_parent[v]);
1542              zag(v);
1543            }
1544          }
1545        }
1546      }
1547      _head[_g.source(v)] = v;
1548    }
1549
1550
1551  public:
1552
1553    ///Find an arc between two nodes.
1554
[233]1555    ///Find an arc between two nodes.
[282]1556    ///\param s The source node.
1557    ///\param t The target node.
[233]1558    ///\param p The previous arc between \c s and \c t. It it is INVALID or
1559    ///not given, the operator finds the first appropriate arc.
1560    ///\return An arc from \c s to \c t after \c p or
1561    ///\ref INVALID if there is no more.
1562    ///
1563    ///For example, you can count the number of arcs from \c u to \c v in the
1564    ///following way.
1565    ///\code
1566    ///DynArcLookUp<ListDigraph> ae(g);
1567    ///...
[282]1568    ///int n = 0;
1569    ///for(Arc a = ae(u,v); a != INVALID; a = ae(u,v,a)) n++;
[233]1570    ///\endcode
1571    ///
[282]1572    ///Finding the arcs take at most <em>O</em>(log<em>d</em>)
[233]1573    ///amortized time, specifically, the time complexity of the lookups
1574    ///is equal to the optimal search tree implementation for the
1575    ///current query distribution in a constant factor.
1576    ///
1577    ///\note This is a dynamic data structure, therefore the data
[282]1578    ///structure is updated after each graph alteration. Thus although
1579    ///this data structure is theoretically faster than \ref ArcLookUp
[313]1580    ///and \ref AllArcLookUp, it often provides worse performance than
[233]1581    ///them.
1582    Arc operator()(Node s, Node t, Arc p = INVALID) const  {
1583      if (p == INVALID) {
1584        Arc a = _head[s];
1585        if (a == INVALID) return INVALID;
1586        Arc r = INVALID;
1587        while (true) {
1588          if (_g.target(a) < t) {
1589            if (_right[a] == INVALID) {
1590              const_cast<DynArcLookUp&>(*this).splay(a);
1591              return r;
1592            } else {
1593              a = _right[a];
1594            }
1595          } else {
1596            if (_g.target(a) == t) {
1597              r = a;
1598            }
1599            if (_left[a] == INVALID) {
1600              const_cast<DynArcLookUp&>(*this).splay(a);
1601              return r;
1602            } else {
1603              a = _left[a];
1604            }
1605          }
1606        }
1607      } else {
1608        Arc a = p;
1609        if (_right[a] != INVALID) {
1610          a = _right[a];
1611          while (_left[a] != INVALID) {
1612            a = _left[a];
1613          }
[220]1614          const_cast<DynArcLookUp&>(*this).splay(a);
[233]1615        } else {
1616          while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
1617            a = _parent[a];
1618          }
1619          if (_parent[a] == INVALID) {
[220]1620            return INVALID;
1621          } else {
[233]1622            a = _parent[a];
[220]1623            const_cast<DynArcLookUp&>(*this).splay(a);
1624          }
1625        }
[233]1626        if (_g.target(a) == t) return a;
1627        else return INVALID;
[220]1628      }
1629    }
1630
1631  };
1632
[282]1633  ///Fast arc look-up between given endpoints.
[220]1634
1635  ///Using this class, you can find an arc in a digraph from a given
[282]1636  ///source to a given target in time <em>O</em>(log<em>d</em>),
[220]1637  ///where <em>d</em> is the out-degree of the source node.
1638  ///
1639  ///It is not possible to find \e all parallel arcs between two nodes.
1640  ///Use \ref AllArcLookUp for this purpose.
1641  ///
[282]1642  ///\warning This class is static, so you should call refresh() (or at
1643  ///least refresh(Node)) to refresh this data structure whenever the
1644  ///digraph changes. This is a time consuming (superlinearly proportional
1645  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
[220]1646  ///
[559]1647  ///\tparam GR The type of the underlying digraph.
[220]1648  ///
1649  ///\sa DynArcLookUp
1650  ///\sa AllArcLookUp
[559]1651  template<class GR>
[220]1652  class ArcLookUp
1653  {
[617]1654    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1655
[220]1656  public:
[617]1657
1658    /// The Digraph type
[559]1659    typedef GR Digraph;
[220]1660
1661  protected:
1662    const Digraph &_g;
1663    typename Digraph::template NodeMap<Arc> _head;
1664    typename Digraph::template ArcMap<Arc> _left;
1665    typename Digraph::template ArcMap<Arc> _right;
1666
1667    class ArcLess {
1668      const Digraph &g;
1669    public:
1670      ArcLess(const Digraph &_g) : g(_g) {}
1671      bool operator()(Arc a,Arc b) const
1672      {
1673        return g.target(a)<g.target(b);
1674      }
1675    };
1676
1677  public:
1678
1679    ///Constructor
1680
1681    ///Constructor.
1682    ///
1683    ///It builds up the search database, which remains valid until the digraph
1684    ///changes.
1685    ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();}
1686
1687  private:
1688    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1689    {
1690      int m=(a+b)/2;
1691      Arc me=v[m];
1692      _left[me] = a<m?refreshRec(v,a,m-1):INVALID;
1693      _right[me] = m<b?refreshRec(v,m+1,b):INVALID;
1694      return me;
1695    }
1696  public:
[282]1697    ///Refresh the search data structure at a node.
[220]1698
1699    ///Build up the search database of node \c n.
1700    ///
[282]1701    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em>
1702    ///is the number of the outgoing arcs of \c n.
[220]1703    void refresh(Node n)
1704    {
1705      std::vector<Arc> v;
1706      for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
1707      if(v.size()) {
1708        std::sort(v.begin(),v.end(),ArcLess(_g));
1709        _head[n]=refreshRec(v,0,v.size()-1);
1710      }
1711      else _head[n]=INVALID;
1712    }
1713    ///Refresh the full data structure.
1714
1715    ///Build up the full search database. In fact, it simply calls
1716    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1717    ///
[282]1718    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
1719    ///the number of the arcs in the digraph and <em>D</em> is the maximum
[220]1720    ///out-degree of the digraph.
1721    void refresh()
1722    {
1723      for(NodeIt n(_g);n!=INVALID;++n) refresh(n);
1724    }
1725
1726    ///Find an arc between two nodes.
1727
[313]1728    ///Find an arc between two nodes in time <em>O</em>(log<em>d</em>),
1729    ///where <em>d</em> is the number of outgoing arcs of \c s.
[282]1730    ///\param s The source node.
1731    ///\param t The target node.
[220]1732    ///\return An arc from \c s to \c t if there exists,
1733    ///\ref INVALID otherwise.
1734    ///
1735    ///\warning If you change the digraph, refresh() must be called before using
1736    ///this operator. If you change the outgoing arcs of
[282]1737    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
[220]1738    Arc operator()(Node s, Node t) const
1739    {
1740      Arc e;
1741      for(e=_head[s];
1742          e!=INVALID&&_g.target(e)!=t;
1743          e = t < _g.target(e)?_left[e]:_right[e]) ;
1744      return e;
1745    }
1746
1747  };
1748
[282]1749  ///Fast look-up of all arcs between given endpoints.
[220]1750
1751  ///This class is the same as \ref ArcLookUp, with the addition
[282]1752  ///that it makes it possible to find all parallel arcs between given
1753  ///endpoints.
[220]1754  ///
[282]1755  ///\warning This class is static, so you should call refresh() (or at
1756  ///least refresh(Node)) to refresh this data structure whenever the
1757  ///digraph changes. This is a time consuming (superlinearly proportional
1758  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
[220]1759  ///
[559]1760  ///\tparam GR The type of the underlying digraph.
[220]1761  ///
1762  ///\sa DynArcLookUp
1763  ///\sa ArcLookUp
[559]1764  template<class GR>
1765  class AllArcLookUp : public ArcLookUp<GR>
[220]1766  {
[559]1767    using ArcLookUp<GR>::_g;
1768    using ArcLookUp<GR>::_right;
1769    using ArcLookUp<GR>::_left;
1770    using ArcLookUp<GR>::_head;
[220]1771
[559]1772    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
[220]1773
[617]1774    typename GR::template ArcMap<Arc> _next;
[220]1775
1776    Arc refreshNext(Arc head,Arc next=INVALID)
1777    {
1778      if(head==INVALID) return next;
1779      else {
1780        next=refreshNext(_right[head],next);
1781        _next[head]=( next!=INVALID && _g.target(next)==_g.target(head))
1782          ? next : INVALID;
1783        return refreshNext(_left[head],head);
1784      }
1785    }
1786
1787    void refreshNext()
1788    {
1789      for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]);
1790    }
1791
1792  public:
[617]1793
1794    /// The Digraph type
1795    typedef GR Digraph;
1796
[220]1797    ///Constructor
1798
1799    ///Constructor.
1800    ///
1801    ///It builds up the search database, which remains valid until the digraph
1802    ///changes.
[559]1803    AllArcLookUp(const Digraph &g) : ArcLookUp<GR>(g), _next(g) {refreshNext();}
[220]1804
1805    ///Refresh the data structure at a node.
1806
1807    ///Build up the search database of node \c n.
1808    ///
[282]1809    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em> is
[220]1810    ///the number of the outgoing arcs of \c n.
1811    void refresh(Node n)
1812    {
[559]1813      ArcLookUp<GR>::refresh(n);
[220]1814      refreshNext(_head[n]);
1815    }
1816
1817    ///Refresh the full data structure.
1818
1819    ///Build up the full search database. In fact, it simply calls
1820    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1821    ///
[282]1822    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
1823    ///the number of the arcs in the digraph and <em>D</em> is the maximum
[220]1824    ///out-degree of the digraph.
1825    void refresh()
1826    {
1827      for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]);
1828    }
1829
1830    ///Find an arc between two nodes.
1831
1832    ///Find an arc between two nodes.
[282]1833    ///\param s The source node.
1834    ///\param t The target node.
[220]1835    ///\param prev The previous arc between \c s and \c t. It it is INVALID or
1836    ///not given, the operator finds the first appropriate arc.
1837    ///\return An arc from \c s to \c t after \c prev or
1838    ///\ref INVALID if there is no more.
1839    ///
1840    ///For example, you can count the number of arcs from \c u to \c v in the
1841    ///following way.
1842    ///\code
1843    ///AllArcLookUp<ListDigraph> ae(g);
1844    ///...
[282]1845    ///int n = 0;
1846    ///for(Arc a = ae(u,v); a != INVALID; a=ae(u,v,a)) n++;
[220]1847    ///\endcode
1848    ///
[313]1849    ///Finding the first arc take <em>O</em>(log<em>d</em>) time,
1850    ///where <em>d</em> is the number of outgoing arcs of \c s. Then the
[220]1851    ///consecutive arcs are found in constant time.
1852    ///
1853    ///\warning If you change the digraph, refresh() must be called before using
1854    ///this operator. If you change the outgoing arcs of
[282]1855    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
[220]1856    ///
[959]1857    Arc operator()(Node s, Node t, Arc prev=INVALID) const
[220]1858    {
[959]1859      if(prev==INVALID)
1860        {
1861          Arc f=INVALID;
1862          Arc e;
1863          for(e=_head[s];
1864              e!=INVALID&&_g.target(e)!=t;
1865              e = t < _g.target(e)?_left[e]:_right[e]) ;
1866          while(e!=INVALID)
1867            if(_g.target(e)==t)
1868              {
1869                f = e;
1870                e = _left[e];
1871              }
1872            else e = _right[e];
1873          return f;
1874        }
1875      else return _next[prev];
[220]1876    }
1877
1878  };
1879
1880  /// @}
1881
1882} //namespace lemon
1883
1884#endif
Note: See TracBrowser for help on using the repository browser.