COIN-OR::LEMON - Graph Library

source: lemon/lemon/core.h @ 1243:79f149ee0230

1.1
Last change on this file since 1243:79f149ee0230 was 1237:deaf433636ca, checked in by Alpar Juttner <alpar@…>, 11 years ago

Merge fix #470 to branch 1.1

File size: 59.2 KB
Line 
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-2011
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/config.h>
26#include <lemon/bits/enable_if.h>
27#include <lemon/bits/traits.h>
28#include <lemon/assert.h>
29
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
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
45///\file
46///\brief LEMON core utilities.
47///
48///This header file contains core utilities for LEMON.
49///It is automatically included by all graph types, therefore it usually
50///do not have to be included directly.
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
78  ///Create convenience typedefs for the digraph types and iterators
79
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,
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;                               \
100  typedef Digraph::ArcMap<double> DoubleArcMap
101
102  ///Create convenience typedefs for the digraph types and iterators
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;             \
120  typedef typename Digraph::template ArcMap<double> DoubleArcMap
121
122  ///Create convenience typedefs for the graph types and iterators
123
124  ///This \c \#define creates the same convenient type definitions as defined
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
130  ///on a template parameter, then use \c TEMPLATE_GRAPH_TYPEDEFS()
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;                               \
139  typedef Graph::EdgeMap<double> DoubleEdgeMap
140
141  ///Create convenience typedefs for the graph types and iterators
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;             \
154  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
155
156  /// \brief Function to count the items in a graph.
157  ///
158  /// This function counts the items (nodes, arcs etc.) in a graph.
159  /// The complexity of the function is linear because
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.
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).
198  ///
199  /// \note If the graph contains a \c nodeNum() member function and a
200  /// \c NodeNumTag tag then this function calls directly the member
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.
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).
234  ///
235  /// \note If the graph contains a \c arcNum() member function and a
236  /// \c ArcNumTag tag then this function calls directly the member
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:
244
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.
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).
270  ///
271  /// \note If the graph contains a \c edgeNum() member function and a
272  /// \c EdgeNumTag tag then this function calls directly the member
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
293  /// in the graph \c g.
294  template <typename Graph>
295  inline int countOutArcs(const Graph& g,  const typename Graph::Node& n) {
296    return countNodeDegree<Graph, typename Graph::OutArcIt>(g, n);
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
302  /// in the graph \c g.
303  template <typename Graph>
304  inline int countInArcs(const Graph& g,  const typename Graph::Node& n) {
305    return countNodeDegree<Graph, typename Graph::InArcIt>(g, n);
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
311  /// in the undirected graph \c g.
312  template <typename Graph>
313  inline int countIncEdges(const Graph& g,  const typename Graph::Node& n) {
314    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(g, n);
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,
328              typename FromMap, typename ToMap>
329    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
330    public:
331
332      MapCopy(const FromMap& map, ToMap& tmap)
333        : _map(map), _tmap(tmap) {}
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:
343      const FromMap& _map;
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
351      ItemCopy(const Item& item, It& it) : _item(item), _it(it) {}
352
353      virtual void copy(const Digraph&, const RefMap& refMap) {
354        _it = refMap[_item];
355      }
356
357    private:
358      Item _item;
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>
400      static void copy(const From& from, Digraph &to,
401                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
402        to.clear();
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>
419      static void copy(const From& from, Digraph &to,
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>
428      static void copy(const From& from, Graph &to,
429                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
430        to.clear();
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>
447      static void copy(const From& from, Graph &to,
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
458  /// simplest way of using it is through the \c digraphCopy() function.
459  ///
460  /// This class not only make a copy of a digraph, but it can create
461  /// references and cross references between the nodes and arcs of
462  /// the two digraphs, and it can copy maps to use with the newly created
463  /// digraph.
464  ///
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
467  /// assigned to copy. In the end, the \c run() member should be
468  /// called.
469  ///
470  /// The next code copies a digraph with several data:
471  ///\code
472  ///  DigraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
473  ///  // Create references for the nodes
474  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
475  ///  cg.nodeRef(nr);
476  ///  // Create cross references (inverse) for the arcs
477  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
478  ///  cg.arcCrossRef(acr);
479  ///  // Copy an arc map
480  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
481  ///  NewGraph::ArcMap<double> namap(new_graph);
482  ///  cg.arcMap(oamap, namap);
483  ///  // Copy a node
484  ///  OrigGraph::Node on;
485  ///  NewGraph::Node nn;
486  ///  cg.node(on, nn);
487  ///  // Execute copying
488  ///  cg.run();
489  ///\endcode
490  template <typename From, typename To>
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
507    /// \brief Constructor of DigraphCopy.
508    ///
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)
512      : _from(from), _to(to) {}
513
514    /// \brief Destructor of DigraphCopy
515    ///
516    /// Destructor of DigraphCopy.
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
527    /// \brief Copy the node references into the given map.
528    ///
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.
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
540    /// \brief Copy the node cross references into the given map.
541    ///
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.
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
553    /// \brief Make a copy of the given node map.
554    ///
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) {
562      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
563                           NodeRefMap, FromMap, ToMap>(map, tmap));
564      return *this;
565    }
566
567    /// \brief Make a copy of the given node.
568    ///
569    /// This function makes a copy of the given node.
570    DigraphCopy& node(const Node& node, TNode& tnode) {
571      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
572                           NodeRefMap, TNode>(node, tnode));
573      return *this;
574    }
575
576    /// \brief Copy the arc references into the given map.
577    ///
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.
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
589    /// \brief Copy the arc cross references into the given map.
590    ///
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.
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
602    /// \brief Make a copy of the given arc map.
603    ///
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) {
611      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
612                          ArcRefMap, FromMap, ToMap>(map, tmap));
613      return *this;
614    }
615
616    /// \brief Make a copy of the given arc.
617    ///
618    /// This function makes a copy of the given arc.
619    DigraphCopy& arc(const Arc& arc, TArc& tarc) {
620      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
621                          ArcRefMap, TArc>(arc, tarc));
622      return *this;
623    }
624
625    /// \brief Execute copying.
626    ///
627    /// This function executes the copying of the digraph along with the
628    /// copying of the assigned data.
629    void run() {
630      NodeRefMap nodeRefMap(_from);
631      ArcRefMap arcRefMap(_from);
632      _core_bits::DigraphCopySelector<To>::
633        copy(_from, _to, nodeRefMap, arcRefMap);
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>* >
648      _node_maps;
649
650    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
651      _arc_maps;
652
653  };
654
655  /// \brief Copy a digraph to another digraph.
656  ///
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:
660  ///\code
661  /// digraphCopy(src, trg).nodeRef(nr).arcCrossRef(acr).run();
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
666  /// \c acr will contain the mapping from the arcs of the \c to digraph
667  /// to the arcs of the \c from digraph.
668  ///
669  /// \see DigraphCopy
670  template <typename From, typename To>
671  DigraphCopy<From, To> digraphCopy(const From& from, To& to) {
672    return DigraphCopy<From, To>(from, to);
673  }
674
675  /// \brief Class to copy a graph.
676  ///
677  /// Class to copy a graph to another graph (duplicate a graph). The
678  /// simplest way of using it is through the \c graphCopy() function.
679  ///
680  /// This class not only make a copy of a graph, but it can create
681  /// references and cross references between the nodes, edges and arcs of
682  /// the two graphs, and it can copy maps for using with the newly created
683  /// graph.
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
692  ///  GraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
693  ///  // Create references for the nodes
694  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
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
704  ///  OrigGraph::Node on;
705  ///  NewGraph::Node nn;
706  ///  cg.node(on, nn);
707  ///  // Execute copying
708  ///  cg.run();
709  ///\endcode
710  template <typename From, typename To>
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 {
729      ArcRefMap(const From& from, const To& to,
730                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
731        : _from(from), _to(to),
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
745      const From& _from;
746      const To& _to;
747      const EdgeRefMap& _edge_ref;
748      const NodeRefMap& _node_ref;
749    };
750
751  public:
752
753    /// \brief Constructor of GraphCopy.
754    ///
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)
758      : _from(from), _to(to) {}
759
760    /// \brief Destructor of GraphCopy
761    ///
762    /// Destructor of GraphCopy.
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
775    /// \brief Copy the node references into the given map.
776    ///
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.
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
788    /// \brief Copy the node cross references into the given map.
789    ///
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.
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
801    /// \brief Make a copy of the given node map.
802    ///
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) {
810      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
811                           NodeRefMap, FromMap, ToMap>(map, tmap));
812      return *this;
813    }
814
815    /// \brief Make a copy of the given node.
816    ///
817    /// This function makes a copy of the given node.
818    GraphCopy& node(const Node& node, TNode& tnode) {
819      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
820                           NodeRefMap, TNode>(node, tnode));
821      return *this;
822    }
823
824    /// \brief Copy the arc references into the given map.
825    ///
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.
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
837    /// \brief Copy the arc cross references into the given map.
838    ///
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.
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
850    /// \brief Make a copy of the given arc map.
851    ///
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) {
859      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
860                          ArcRefMap, FromMap, ToMap>(map, tmap));
861      return *this;
862    }
863
864    /// \brief Make a copy of the given arc.
865    ///
866    /// This function makes a copy of the given arc.
867    GraphCopy& arc(const Arc& arc, TArc& tarc) {
868      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
869                          ArcRefMap, TArc>(arc, tarc));
870      return *this;
871    }
872
873    /// \brief Copy the edge references into the given map.
874    ///
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.
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
886    /// \brief Copy the edge cross references into the given map.
887    ///
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.
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
899    /// \brief Make a copy of the given edge map.
900    ///
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) {
908      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
909                           EdgeRefMap, FromMap, ToMap>(map, tmap));
910      return *this;
911    }
912
913    /// \brief Make a copy of the given edge.
914    ///
915    /// This function makes a copy of the given edge.
916    GraphCopy& edge(const Edge& edge, TEdge& tedge) {
917      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
918                           EdgeRefMap, TEdge>(edge, tedge));
919      return *this;
920    }
921
922    /// \brief Execute copying.
923    ///
924    /// This function executes the copying of the graph along with the
925    /// copying of the assigned data.
926    void run() {
927      NodeRefMap nodeRefMap(_from);
928      EdgeRefMap edgeRefMap(_from);
929      ArcRefMap arcRefMap(_from, _to, edgeRefMap, nodeRefMap);
930      _core_bits::GraphCopySelector<To>::
931        copy(_from, _to, nodeRefMap, edgeRefMap);
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>* >
949      _node_maps;
950
951    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
952      _arc_maps;
953
954    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
955      _edge_maps;
956
957  };
958
959  /// \brief Copy a graph to another graph.
960  ///
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:
964  ///\code
965  /// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run();
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
970  /// \c ecr will contain the mapping from the edges of the \c to graph
971  /// to the edges of the \c from graph.
972  ///
973  /// \see GraphCopy
974  template <typename From, typename To>
975  GraphCopy<From, To>
976  graphCopy(const From& from, To& to) {
977    return GraphCopy<From, To>(from, to);
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,
1002      typename enable_if<typename Graph::FindArcTag, void>::type>
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
1012  /// \brief Find an arc between two nodes of a digraph.
1013  ///
1014  /// This function finds an arc from node \c u to node \c v in the
1015  /// digraph \c g.
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
1024  /// for(Arc e = findArc(g,u,v); e != INVALID; e = findArc(g,u,v,e)) {
1025  ///   ...
1026  /// }
1027  ///\endcode
1028  ///
1029  /// \note \ref ConArcIt provides iterator interface for the same
1030  /// functionality.
1031  ///
1032  ///\sa ConArcIt
1033  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
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
1041  /// \brief Iterator for iterating on parallel arcs connecting the same nodes.
1042  ///
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
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()
1053  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1054  template <typename GR>
1055  class ConArcIt : public GR::Arc {
1056    typedef typename GR::Arc Parent;
1057
1058  public:
1059
1060    typedef typename GR::Arc Arc;
1061    typedef typename GR::Node Node;
1062
1063    /// \brief Constructor.
1064    ///
1065    /// Construct a new ConArcIt iterating on the arcs that
1066    /// connects nodes \c u and \c v.
1067    ConArcIt(const GR& g, Node u, Node v) : _graph(g) {
1068      Parent::operator=(findArc(_graph, u, v));
1069    }
1070
1071    /// \brief Constructor.
1072    ///
1073    /// Construct a new ConArcIt that continues the iterating from arc \c a.
1074    ConArcIt(const GR& g, Arc a) : Parent(a), _graph(g) {}
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:
1085    const GR& _graph;
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
1134  /// \brief Find an edge between two nodes of a graph.
1135  ///
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
1138  /// will be enumerated once.
1139  ///
1140  /// If \c prev is \ref INVALID (this is the default value), then
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.
1144  ///
1145  /// Thus you can iterate through each edge between \c u and \c v
1146  /// as it follows.
1147  ///\code
1148  /// for(Edge e = findEdge(g,u,v); e != INVALID; e = findEdge(g,u,v,e)) {
1149  ///   ...
1150  /// }
1151  ///\endcode
1152  ///
1153  /// \note \ref ConEdgeIt provides iterator interface for the same
1154  /// functionality.
1155  ///
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
1164  /// \brief Iterator for iterating on parallel edges connecting the same nodes.
1165  ///
1166  /// Iterator for iterating on parallel edges connecting the same nodes.
1167  /// It is a higher level interface for the findEdge() function. You can
1168  /// use it the following way:
1169  ///\code
1170  /// for (ConEdgeIt<Graph> it(g, u, v); it != INVALID; ++it) {
1171  ///   ...
1172  /// }
1173  ///\endcode
1174  ///
1175  ///\sa findEdge()
1176  template <typename GR>
1177  class ConEdgeIt : public GR::Edge {
1178    typedef typename GR::Edge Parent;
1179
1180  public:
1181
1182    typedef typename GR::Edge Edge;
1183    typedef typename GR::Node Node;
1184
1185    /// \brief Constructor.
1186    ///
1187    /// Construct a new ConEdgeIt iterating on the edges that
1188    /// connects nodes \c u and \c v.
1189    ConEdgeIt(const GR& g, Node u, Node v) : _graph(g), _u(u), _v(v) {
1190      Parent::operator=(findEdge(_graph, _u, _v));
1191    }
1192
1193    /// \brief Constructor.
1194    ///
1195    /// Construct a new ConEdgeIt that continues iterating from edge \c e.
1196    ConEdgeIt(const GR& g, Edge e) : Parent(e), _graph(g) {}
1197
1198    /// \brief Increment operator.
1199    ///
1200    /// It increments the iterator and gives back the next edge.
1201    ConEdgeIt& operator++() {
1202      Parent::operator=(findEdge(_graph, _u, _v, *this));
1203      return *this;
1204    }
1205  private:
1206    const GR& _graph;
1207    Node _u, _v;
1208  };
1209
1210
1211  ///Dynamic arc look-up between given endpoints.
1212
1213  ///Using this class, you can find an arc in a digraph from a given
1214  ///source to a given target in amortized time <em>O</em>(log<em>d</em>),
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
1218  ///the \c operator() member.
1219  ///
1220  ///This is a dynamic data structure. Consider to use \ref ArcLookUp or
1221  ///\ref AllArcLookUp if your digraph is not changed so frequently.
1222  ///
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
1226  ///optimal time bound in a constant factor for any distribution of
1227  ///queries.
1228  ///
1229  ///\tparam GR The type of the underlying digraph.
1230  ///
1231  ///\sa ArcLookUp
1232  ///\sa AllArcLookUp
1233  template <typename GR>
1234  class DynArcLookUp
1235    : protected ItemSetTraits<GR, typename GR::Arc>::ItemNotifier::ObserverBase
1236  {
1237    typedef typename ItemSetTraits<GR, typename GR::Arc>
1238    ::ItemNotifier::ObserverBase Parent;
1239
1240    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1241
1242  public:
1243
1244    /// The Digraph type
1245    typedef GR Digraph;
1246
1247  protected:
1248
1249    class AutoNodeMap :
1250      public ItemSetTraits<GR, Node>::template Map<Arc>::Type {
1251      typedef typename ItemSetTraits<GR, Node>::template Map<Arc>::Type Parent;
1252
1253    public:
1254
1255      AutoNodeMap(const GR& digraph) : Parent(digraph, INVALID) {}
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
1289  protected:
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
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) {
1339        _head[n] = INVALID;
1340      }
1341    }
1342
1343    void insert(Arc arc) {
1344      Node s = _g.source(arc);
1345      Node t = _g.target(arc);
1346      _left[arc] = INVALID;
1347      _right[arc] = INVALID;
1348
1349      Arc e = _head[s];
1350      if (e == INVALID) {
1351        _head[s] = arc;
1352        _parent[arc] = INVALID;
1353        return;
1354      }
1355      while (true) {
1356        if (t < _g.target(e)) {
1357          if (_left[e] == INVALID) {
1358            _left[e] = arc;
1359            _parent[arc] = e;
1360            splay(arc);
1361            return;
1362          } else {
1363            e = _left[e];
1364          }
1365        } else {
1366          if (_right[e] == INVALID) {
1367            _right[e] = arc;
1368            _parent[arc] = e;
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) {
1381          _parent[_right[arc]] = _parent[arc];
1382        }
1383        if (_parent[arc] != INVALID) {
1384          if (_left[_parent[arc]] == arc) {
1385            _left[_parent[arc]] = _right[arc];
1386          } else {
1387            _right[_parent[arc]] = _right[arc];
1388          }
1389        } else {
1390          _head[_g.source(arc)] = _right[arc];
1391        }
1392      } else if (_right[arc] == INVALID) {
1393        _parent[_left[arc]] = _parent[arc];
1394        if (_parent[arc] != INVALID) {
1395          if (_left[_parent[arc]] == arc) {
1396            _left[_parent[arc]] = _left[arc];
1397          } else {
1398            _right[_parent[arc]] = _left[arc];
1399          }
1400        } else {
1401          _head[_g.source(arc)] = _left[arc];
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];
1411          _right[_parent[e]] = _left[e];
1412          if (_left[e] != INVALID) {
1413            _parent[_left[e]] = _parent[e];
1414          }
1415
1416          _left[e] = _left[arc];
1417          _parent[_left[arc]] = e;
1418          _right[e] = _right[arc];
1419          _parent[_right[arc]] = e;
1420
1421          _parent[e] = _parent[arc];
1422          if (_parent[arc] != INVALID) {
1423            if (_left[_parent[arc]] == arc) {
1424              _left[_parent[arc]] = e;
1425            } else {
1426              _right[_parent[arc]] = e;
1427            }
1428          }
1429          splay(s);
1430        } else {
1431          _right[e] = _right[arc];
1432          _parent[_right[arc]] = e;
1433          _parent[e] = _parent[arc];
1434
1435          if (_parent[arc] != INVALID) {
1436            if (_left[_parent[arc]] == arc) {
1437              _left[_parent[arc]] = e;
1438            } else {
1439              _right[_parent[arc]] = e;
1440            }
1441          } else {
1442            _head[_g.source(arc)] = e;
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);
1454        _left[me] = left;
1455        _parent[left] = me;
1456      } else {
1457        _left[me] = INVALID;
1458      }
1459      if (m < b) {
1460        Arc right = refreshRec(v,m+1,b);
1461        _right[me] = right;
1462        _parent[right] = me;
1463      } else {
1464        _right[me] = INVALID;
1465      }
1466      return me;
1467    }
1468
1469    void refresh() {
1470      for(NodeIt n(_g);n!=INVALID;++n) {
1471        std::vector<Arc> v;
1472        for(OutArcIt a(_g,n);a!=INVALID;++a) v.push_back(a);
1473        if (!v.empty()) {
1474          std::sort(v.begin(),v.end(),ArcLess(_g));
1475          Arc head = refreshRec(v,0,v.size()-1);
1476          _head[n] = head;
1477          _parent[head] = INVALID;
1478        }
1479        else _head[n] = INVALID;
1480      }
1481    }
1482
1483    void zig(Arc v) {
1484      Arc w = _parent[v];
1485      _parent[v] = _parent[w];
1486      _parent[w] = v;
1487      _left[w] = _right[v];
1488      _right[v] = w;
1489      if (_parent[v] != INVALID) {
1490        if (_right[_parent[v]] == w) {
1491          _right[_parent[v]] = v;
1492        } else {
1493          _left[_parent[v]] = v;
1494        }
1495      }
1496      if (_left[w] != INVALID){
1497        _parent[_left[w]] = w;
1498      }
1499    }
1500
1501    void zag(Arc v) {
1502      Arc w = _parent[v];
1503      _parent[v] = _parent[w];
1504      _parent[w] = v;
1505      _right[w] = _left[v];
1506      _left[v] = w;
1507      if (_parent[v] != INVALID){
1508        if (_left[_parent[v]] == w) {
1509          _left[_parent[v]] = v;
1510        } else {
1511          _right[_parent[v]] = v;
1512        }
1513      }
1514      if (_right[w] != INVALID){
1515        _parent[_right[w]] = w;
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
1555    ///Find an arc between two nodes.
1556    ///\param s The source node.
1557    ///\param t The target node.
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    ///...
1568    ///int n = 0;
1569    ///for(Arc a = ae(u,v); a != INVALID; a = ae(u,v,a)) n++;
1570    ///\endcode
1571    ///
1572    ///Finding the arcs take at most <em>O</em>(log<em>d</em>)
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
1578    ///structure is updated after each graph alteration. Thus although
1579    ///this data structure is theoretically faster than \ref ArcLookUp
1580    ///and \ref AllArcLookUp, it often provides worse performance than
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          }
1614          const_cast<DynArcLookUp&>(*this).splay(a);
1615        } else {
1616          while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
1617            a = _parent[a];
1618          }
1619          if (_parent[a] == INVALID) {
1620            return INVALID;
1621          } else {
1622            a = _parent[a];
1623            const_cast<DynArcLookUp&>(*this).splay(a);
1624          }
1625        }
1626        if (_g.target(a) == t) return a;
1627        else return INVALID;
1628      }
1629    }
1630
1631  };
1632
1633  ///Fast arc look-up between given endpoints.
1634
1635  ///Using this class, you can find an arc in a digraph from a given
1636  ///source to a given target in time <em>O</em>(log<em>d</em>),
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  ///
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).
1646  ///
1647  ///\tparam GR The type of the underlying digraph.
1648  ///
1649  ///\sa DynArcLookUp
1650  ///\sa AllArcLookUp
1651  template<class GR>
1652  class ArcLookUp
1653  {
1654    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1655
1656  public:
1657
1658    /// The Digraph type
1659    typedef GR Digraph;
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:
1697    ///Refresh the search data structure at a node.
1698
1699    ///Build up the search database of node \c n.
1700    ///
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.
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    ///
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
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
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.
1730    ///\param s The source node.
1731    ///\param t The target node.
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
1737    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
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
1749  ///Fast look-up of all arcs between given endpoints.
1750
1751  ///This class is the same as \ref ArcLookUp, with the addition
1752  ///that it makes it possible to find all parallel arcs between given
1753  ///endpoints.
1754  ///
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).
1759  ///
1760  ///\tparam GR The type of the underlying digraph.
1761  ///
1762  ///\sa DynArcLookUp
1763  ///\sa ArcLookUp
1764  template<class GR>
1765  class AllArcLookUp : public ArcLookUp<GR>
1766  {
1767    using ArcLookUp<GR>::_g;
1768    using ArcLookUp<GR>::_right;
1769    using ArcLookUp<GR>::_left;
1770    using ArcLookUp<GR>::_head;
1771
1772    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1773
1774    typename GR::template ArcMap<Arc> _next;
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:
1793
1794    /// The Digraph type
1795    typedef GR Digraph;
1796
1797    ///Constructor
1798
1799    ///Constructor.
1800    ///
1801    ///It builds up the search database, which remains valid until the digraph
1802    ///changes.
1803    AllArcLookUp(const Digraph &g) : ArcLookUp<GR>(g), _next(g) {refreshNext();}
1804
1805    ///Refresh the data structure at a node.
1806
1807    ///Build up the search database of node \c n.
1808    ///
1809    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em> is
1810    ///the number of the outgoing arcs of \c n.
1811    void refresh(Node n)
1812    {
1813      ArcLookUp<GR>::refresh(n);
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    ///
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
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.
1833    ///\param s The source node.
1834    ///\param t The target node.
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    ///...
1845    ///int n = 0;
1846    ///for(Arc a = ae(u,v); a != INVALID; a=ae(u,v,a)) n++;
1847    ///\endcode
1848    ///
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
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
1855    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
1856    ///
1857    Arc operator()(Node s, Node t, Arc prev=INVALID) const
1858    {
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];
1876    }
1877
1878  };
1879
1880  /// @}
1881
1882} //namespace lemon
1883
1884#endif
Note: See TracBrowser for help on using the repository browser.