COIN-OR::LEMON - Graph Library

source: lemon/lemon/core.h @ 1327:18c89646185e

Last change on this file since 1327:18c89646185e was 1327:18c89646185e, checked in by Alpar Juttner <alpar@…>, 4 years ago

Suppress MSVC warning C4267 (#519)

C4267: conversion from 'size_t' to 'type', possible loss of data

File size: 82.6 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-2013
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// C4267: conversion from 'size_t' to 'type', possible loss of data
33// C4355: 'this' : used in base member initializer list
34// C4503: 'function' : decorated name length exceeded, name was truncated
35// C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
36// C4996: 'function': was declared deprecated
37#ifdef _MSC_VER
38#pragma warning( disable : 4250 4267 4355 4503 4800 4996 )
39#endif
40
41#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
42// Needed by the [DI]GRAPH_TYPEDEFS marcos for gcc 4.8
43#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
44#endif
45
46///\file
47///\brief LEMON core utilities.
48///
49///This header file contains core utilities for LEMON.
50///It is automatically included by all graph types, therefore it usually
51///do not have to be included directly.
52
53namespace lemon {
54
55  /// \brief Dummy type to make it easier to create invalid iterators.
56  ///
57  /// Dummy type to make it easier to create invalid iterators.
58  /// See \ref INVALID for the usage.
59  struct Invalid {
60  public:
61    bool operator==(Invalid) { return true;  }
62    bool operator!=(Invalid) { return false; }
63    bool operator< (Invalid) { return false; }
64  };
65
66  /// \brief Invalid iterators.
67  ///
68  /// \ref Invalid is a global type that converts to each iterator
69  /// in such a way that the value of the target iterator will be invalid.
70#ifdef LEMON_ONLY_TEMPLATES
71  const Invalid INVALID = Invalid();
72#else
73  extern const Invalid INVALID;
74#endif
75
76  /// \addtogroup gutils
77  /// @{
78
79  ///Create convenience typedefs for the digraph types and iterators
80
81  ///This \c \#define creates convenient type definitions for the following
82  ///types of \c Digraph: \c Node,  \c NodeIt, \c Arc, \c ArcIt, \c InArcIt,
83  ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap,
84  ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap.
85  ///
86  ///\note If the graph type is a dependent type, ie. the graph type depend
87  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
88  ///macro.
89#define DIGRAPH_TYPEDEFS(Digraph)                                       \
90  typedef Digraph::Node Node;                                           \
91  typedef Digraph::NodeIt NodeIt;                                       \
92  typedef Digraph::Arc Arc;                                             \
93  typedef Digraph::ArcIt ArcIt;                                         \
94  typedef Digraph::InArcIt InArcIt;                                     \
95  typedef Digraph::OutArcIt OutArcIt;                                   \
96  typedef Digraph::NodeMap<bool> BoolNodeMap;                           \
97  typedef Digraph::NodeMap<int> IntNodeMap;                             \
98  typedef Digraph::NodeMap<double> DoubleNodeMap;                       \
99  typedef Digraph::ArcMap<bool> BoolArcMap;                             \
100  typedef Digraph::ArcMap<int> IntArcMap;                               \
101  typedef Digraph::ArcMap<double> DoubleArcMap
102
103  ///Create convenience typedefs for the digraph types and iterators
104
105  ///\see DIGRAPH_TYPEDEFS
106  ///
107  ///\note Use this macro, if the graph type is a dependent type,
108  ///ie. the graph type depend on a template parameter.
109#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph)                              \
110  typedef typename Digraph::Node Node;                                  \
111  typedef typename Digraph::NodeIt NodeIt;                              \
112  typedef typename Digraph::Arc Arc;                                    \
113  typedef typename Digraph::ArcIt ArcIt;                                \
114  typedef typename Digraph::InArcIt InArcIt;                            \
115  typedef typename Digraph::OutArcIt OutArcIt;                          \
116  typedef typename Digraph::template NodeMap<bool> BoolNodeMap;         \
117  typedef typename Digraph::template NodeMap<int> IntNodeMap;           \
118  typedef typename Digraph::template NodeMap<double> DoubleNodeMap;     \
119  typedef typename Digraph::template ArcMap<bool> BoolArcMap;           \
120  typedef typename Digraph::template ArcMap<int> IntArcMap;             \
121  typedef typename Digraph::template ArcMap<double> DoubleArcMap
122
123  ///Create convenience typedefs for the graph types and iterators
124
125  ///This \c \#define creates the same convenient type definitions as defined
126  ///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates
127  ///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap,
128  ///\c DoubleEdgeMap.
129  ///
130  ///\note If the graph type is a dependent type, ie. the graph type depend
131  ///on a template parameter, then use \c TEMPLATE_GRAPH_TYPEDEFS()
132  ///macro.
133#define GRAPH_TYPEDEFS(Graph)                                           \
134  DIGRAPH_TYPEDEFS(Graph);                                              \
135  typedef Graph::Edge Edge;                                             \
136  typedef Graph::EdgeIt EdgeIt;                                         \
137  typedef Graph::IncEdgeIt IncEdgeIt;                                   \
138  typedef Graph::EdgeMap<bool> BoolEdgeMap;                             \
139  typedef Graph::EdgeMap<int> IntEdgeMap;                               \
140  typedef Graph::EdgeMap<double> DoubleEdgeMap
141
142  ///Create convenience typedefs for the graph types and iterators
143
144  ///\see GRAPH_TYPEDEFS
145  ///
146  ///\note Use this macro, if the graph type is a dependent type,
147  ///ie. the graph type depend on a template parameter.
148#define TEMPLATE_GRAPH_TYPEDEFS(Graph)                                  \
149  TEMPLATE_DIGRAPH_TYPEDEFS(Graph);                                     \
150  typedef typename Graph::Edge Edge;                                    \
151  typedef typename Graph::EdgeIt EdgeIt;                                \
152  typedef typename Graph::IncEdgeIt IncEdgeIt;                          \
153  typedef typename Graph::template EdgeMap<bool> BoolEdgeMap;           \
154  typedef typename Graph::template EdgeMap<int> IntEdgeMap;             \
155  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
156
157  ///Create convenience typedefs for the bipartite graph types and iterators
158
159  ///This \c \#define creates the same convenient type definitions as
160  ///defined by \ref GRAPH_TYPEDEFS(BpGraph) and ten more, namely it
161  ///creates \c RedNode, \c RedNodeIt, \c BoolRedNodeMap,
162  ///\c IntRedNodeMap, \c DoubleRedNodeMap, \c BlueNode, \c BlueNodeIt,
163  ///\c BoolBlueNodeMap, \c IntBlueNodeMap, \c DoubleBlueNodeMap.
164  ///
165  ///\note If the graph type is a dependent type, ie. the graph type depend
166  ///on a template parameter, then use \c TEMPLATE_BPGRAPH_TYPEDEFS()
167  ///macro.
168#define BPGRAPH_TYPEDEFS(BpGraph)                                       \
169  GRAPH_TYPEDEFS(BpGraph);                                              \
170  typedef BpGraph::RedNode RedNode;                                     \
171  typedef BpGraph::RedNodeIt RedNodeIt;                                 \
172  typedef BpGraph::RedNodeMap<bool> BoolRedNodeMap;                     \
173  typedef BpGraph::RedNodeMap<int> IntRedNodeMap;                       \
174  typedef BpGraph::RedNodeMap<double> DoubleRedNodeMap;                 \
175  typedef BpGraph::BlueNode BlueNode;                                   \
176  typedef BpGraph::BlueNodeIt BlueNodeIt;                               \
177  typedef BpGraph::BlueNodeMap<bool> BoolBlueNodeMap;                   \
178  typedef BpGraph::BlueNodeMap<int> IntBlueNodeMap;                     \
179  typedef BpGraph::BlueNodeMap<double> DoubleBlueNodeMap
180
181  ///Create convenience typedefs for the bipartite graph types and iterators
182
183  ///\see BPGRAPH_TYPEDEFS
184  ///
185  ///\note Use this macro, if the graph type is a dependent type,
186  ///ie. the graph type depend on a template parameter.
187#define TEMPLATE_BPGRAPH_TYPEDEFS(BpGraph)                                  \
188  TEMPLATE_GRAPH_TYPEDEFS(BpGraph);                                         \
189  typedef typename BpGraph::RedNode RedNode;                                \
190  typedef typename BpGraph::RedNodeIt RedNodeIt;                            \
191  typedef typename BpGraph::template RedNodeMap<bool> BoolRedNodeMap;       \
192  typedef typename BpGraph::template RedNodeMap<int> IntRedNodeMap;         \
193  typedef typename BpGraph::template RedNodeMap<double> DoubleRedNodeMap;   \
194  typedef typename BpGraph::BlueNode BlueNode;                              \
195  typedef typename BpGraph::BlueNodeIt BlueNodeIt;                          \
196  typedef typename BpGraph::template BlueNodeMap<bool> BoolBlueNodeMap;     \
197  typedef typename BpGraph::template BlueNodeMap<int> IntBlueNodeMap;       \
198  typedef typename BpGraph::template BlueNodeMap<double> DoubleBlueNodeMap
199
200  /// \brief Function to count the items in a graph.
201  ///
202  /// This function counts the items (nodes, arcs etc.) in a graph.
203  /// The complexity of the function is linear because
204  /// it iterates on all of the items.
205  template <typename Graph, typename Item>
206  inline int countItems(const Graph& g) {
207    typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt;
208    int num = 0;
209    for (ItemIt it(g); it != INVALID; ++it) {
210      ++num;
211    }
212    return num;
213  }
214
215  // Node counting:
216
217  namespace _core_bits {
218
219    template <typename Graph, typename Enable = void>
220    struct CountNodesSelector {
221      static int count(const Graph &g) {
222        return countItems<Graph, typename Graph::Node>(g);
223      }
224    };
225
226    template <typename Graph>
227    struct CountNodesSelector<
228      Graph, typename
229      enable_if<typename Graph::NodeNumTag, void>::type>
230    {
231      static int count(const Graph &g) {
232        return g.nodeNum();
233      }
234    };
235  }
236
237  /// \brief Function to count the nodes in the graph.
238  ///
239  /// This function counts the nodes in the graph.
240  /// The complexity of the function is <em>O</em>(<em>n</em>), but for some
241  /// graph structures it is specialized to run in <em>O</em>(1).
242  ///
243  /// \note If the graph contains a \c nodeNum() member function and a
244  /// \c NodeNumTag tag then this function calls directly the member
245  /// function to query the cardinality of the node set.
246  template <typename Graph>
247  inline int countNodes(const Graph& g) {
248    return _core_bits::CountNodesSelector<Graph>::count(g);
249  }
250
251  namespace _graph_utils_bits {
252
253    template <typename Graph, typename Enable = void>
254    struct CountRedNodesSelector {
255      static int count(const Graph &g) {
256        return countItems<Graph, typename Graph::RedNode>(g);
257      }
258    };
259
260    template <typename Graph>
261    struct CountRedNodesSelector<
262      Graph, typename
263      enable_if<typename Graph::NodeNumTag, void>::type>
264    {
265      static int count(const Graph &g) {
266        return g.redNum();
267      }
268    };
269  }
270
271  /// \brief Function to count the red nodes in the graph.
272  ///
273  /// This function counts the red nodes in the graph.
274  /// The complexity of the function is O(n) but for some
275  /// graph structures it is specialized to run in O(1).
276  ///
277  /// If the graph contains a \e redNum() member function and a
278  /// \e NodeNumTag tag then this function calls directly the member
279  /// function to query the cardinality of the node set.
280  template <typename Graph>
281  inline int countRedNodes(const Graph& g) {
282    return _graph_utils_bits::CountRedNodesSelector<Graph>::count(g);
283  }
284
285  namespace _graph_utils_bits {
286
287    template <typename Graph, typename Enable = void>
288    struct CountBlueNodesSelector {
289      static int count(const Graph &g) {
290        return countItems<Graph, typename Graph::BlueNode>(g);
291      }
292    };
293
294    template <typename Graph>
295    struct CountBlueNodesSelector<
296      Graph, typename
297      enable_if<typename Graph::NodeNumTag, void>::type>
298    {
299      static int count(const Graph &g) {
300        return g.blueNum();
301      }
302    };
303  }
304
305  /// \brief Function to count the blue nodes in the graph.
306  ///
307  /// This function counts the blue nodes in the graph.
308  /// The complexity of the function is O(n) but for some
309  /// graph structures it is specialized to run in O(1).
310  ///
311  /// If the graph contains a \e blueNum() member function and a
312  /// \e NodeNumTag tag then this function calls directly the member
313  /// function to query the cardinality of the node set.
314  template <typename Graph>
315  inline int countBlueNodes(const Graph& g) {
316    return _graph_utils_bits::CountBlueNodesSelector<Graph>::count(g);
317  }
318
319  // Arc counting:
320
321  namespace _core_bits {
322
323    template <typename Graph, typename Enable = void>
324    struct CountArcsSelector {
325      static int count(const Graph &g) {
326        return countItems<Graph, typename Graph::Arc>(g);
327      }
328    };
329
330    template <typename Graph>
331    struct CountArcsSelector<
332      Graph,
333      typename enable_if<typename Graph::ArcNumTag, void>::type>
334    {
335      static int count(const Graph &g) {
336        return g.arcNum();
337      }
338    };
339  }
340
341  /// \brief Function to count the arcs in the graph.
342  ///
343  /// This function counts the arcs in the graph.
344  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
345  /// graph structures it is specialized to run in <em>O</em>(1).
346  ///
347  /// \note If the graph contains a \c arcNum() member function and a
348  /// \c ArcNumTag tag then this function calls directly the member
349  /// function to query the cardinality of the arc set.
350  template <typename Graph>
351  inline int countArcs(const Graph& g) {
352    return _core_bits::CountArcsSelector<Graph>::count(g);
353  }
354
355  // Edge counting:
356
357  namespace _core_bits {
358
359    template <typename Graph, typename Enable = void>
360    struct CountEdgesSelector {
361      static int count(const Graph &g) {
362        return countItems<Graph, typename Graph::Edge>(g);
363      }
364    };
365
366    template <typename Graph>
367    struct CountEdgesSelector<
368      Graph,
369      typename enable_if<typename Graph::EdgeNumTag, void>::type>
370    {
371      static int count(const Graph &g) {
372        return g.edgeNum();
373      }
374    };
375  }
376
377  /// \brief Function to count the edges in the graph.
378  ///
379  /// This function counts the edges in the graph.
380  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
381  /// graph structures it is specialized to run in <em>O</em>(1).
382  ///
383  /// \note If the graph contains a \c edgeNum() member function and a
384  /// \c EdgeNumTag tag then this function calls directly the member
385  /// function to query the cardinality of the edge set.
386  template <typename Graph>
387  inline int countEdges(const Graph& g) {
388    return _core_bits::CountEdgesSelector<Graph>::count(g);
389
390  }
391
392
393  template <typename Graph, typename DegIt>
394  inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
395    int num = 0;
396    for (DegIt it(_g, _n); it != INVALID; ++it) {
397      ++num;
398    }
399    return num;
400  }
401
402  /// \brief Function to count the number of the out-arcs from node \c n.
403  ///
404  /// This function counts the number of the out-arcs from node \c n
405  /// in the graph \c g.
406  template <typename Graph>
407  inline int countOutArcs(const Graph& g,  const typename Graph::Node& n) {
408    return countNodeDegree<Graph, typename Graph::OutArcIt>(g, n);
409  }
410
411  /// \brief Function to count the number of the in-arcs to node \c n.
412  ///
413  /// This function counts the number of the in-arcs to node \c n
414  /// in the graph \c g.
415  template <typename Graph>
416  inline int countInArcs(const Graph& g,  const typename Graph::Node& n) {
417    return countNodeDegree<Graph, typename Graph::InArcIt>(g, n);
418  }
419
420  /// \brief Function to count the number of the inc-edges to node \c n.
421  ///
422  /// This function counts the number of the inc-edges to node \c n
423  /// in the undirected graph \c g.
424  template <typename Graph>
425  inline int countIncEdges(const Graph& g,  const typename Graph::Node& n) {
426    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(g, n);
427  }
428
429  namespace _core_bits {
430
431    template <typename Digraph, typename Item, typename RefMap>
432    class MapCopyBase {
433    public:
434      virtual void copy(const Digraph& from, const RefMap& refMap) = 0;
435
436      virtual ~MapCopyBase() {}
437    };
438
439    template <typename Digraph, typename Item, typename RefMap,
440              typename FromMap, typename ToMap>
441    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
442    public:
443
444      MapCopy(const FromMap& map, ToMap& tmap)
445        : _map(map), _tmap(tmap) {}
446
447      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
448        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
449        for (ItemIt it(digraph); it != INVALID; ++it) {
450          _tmap.set(refMap[it], _map[it]);
451        }
452      }
453
454    private:
455      const FromMap& _map;
456      ToMap& _tmap;
457    };
458
459    template <typename Digraph, typename Item, typename RefMap, typename It>
460    class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> {
461    public:
462
463      ItemCopy(const Item& item, It& it) : _item(item), _it(it) {}
464
465      virtual void copy(const Digraph&, const RefMap& refMap) {
466        _it = refMap[_item];
467      }
468
469    private:
470      Item _item;
471      It& _it;
472    };
473
474    template <typename Digraph, typename Item, typename RefMap, typename Ref>
475    class RefCopy : public MapCopyBase<Digraph, Item, RefMap> {
476    public:
477
478      RefCopy(Ref& map) : _map(map) {}
479
480      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
481        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
482        for (ItemIt it(digraph); it != INVALID; ++it) {
483          _map.set(it, refMap[it]);
484        }
485      }
486
487    private:
488      Ref& _map;
489    };
490
491    template <typename Digraph, typename Item, typename RefMap,
492              typename CrossRef>
493    class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> {
494    public:
495
496      CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {}
497
498      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
499        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
500        for (ItemIt it(digraph); it != INVALID; ++it) {
501          _cmap.set(refMap[it], it);
502        }
503      }
504
505    private:
506      CrossRef& _cmap;
507    };
508
509    template <typename Digraph, typename Enable = void>
510    struct DigraphCopySelector {
511      template <typename From, typename NodeRefMap, typename ArcRefMap>
512      static void copy(const From& from, Digraph &to,
513                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
514        to.clear();
515        for (typename From::NodeIt it(from); it != INVALID; ++it) {
516          nodeRefMap[it] = to.addNode();
517        }
518        for (typename From::ArcIt it(from); it != INVALID; ++it) {
519          arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)],
520                                    nodeRefMap[from.target(it)]);
521        }
522      }
523    };
524
525    template <typename Digraph>
526    struct DigraphCopySelector<
527      Digraph,
528      typename enable_if<typename Digraph::BuildTag, void>::type>
529    {
530      template <typename From, typename NodeRefMap, typename ArcRefMap>
531      static void copy(const From& from, Digraph &to,
532                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
533        to.build(from, nodeRefMap, arcRefMap);
534      }
535    };
536
537    template <typename Graph, typename Enable = void>
538    struct GraphCopySelector {
539      template <typename From, typename NodeRefMap, typename EdgeRefMap>
540      static void copy(const From& from, Graph &to,
541                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
542        to.clear();
543        for (typename From::NodeIt it(from); it != INVALID; ++it) {
544          nodeRefMap[it] = to.addNode();
545        }
546        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
547          edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)],
548                                      nodeRefMap[from.v(it)]);
549        }
550      }
551    };
552
553    template <typename Graph>
554    struct GraphCopySelector<
555      Graph,
556      typename enable_if<typename Graph::BuildTag, void>::type>
557    {
558      template <typename From, typename NodeRefMap, typename EdgeRefMap>
559      static void copy(const From& from, Graph &to,
560                       NodeRefMap& nodeRefMap,
561                       EdgeRefMap& edgeRefMap) {
562        to.build(from, nodeRefMap, edgeRefMap);
563      }
564    };
565
566    template <typename BpGraph, typename Enable = void>
567    struct BpGraphCopySelector {
568      template <typename From, typename RedNodeRefMap,
569                typename BlueNodeRefMap, typename EdgeRefMap>
570      static void copy(const From& from, BpGraph &to,
571                       RedNodeRefMap& redNodeRefMap,
572                       BlueNodeRefMap& blueNodeRefMap,
573                       EdgeRefMap& edgeRefMap) {
574        to.clear();
575        for (typename From::RedNodeIt it(from); it != INVALID; ++it) {
576          redNodeRefMap[it] = to.addRedNode();
577        }
578        for (typename From::BlueNodeIt it(from); it != INVALID; ++it) {
579          blueNodeRefMap[it] = to.addBlueNode();
580        }
581        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
582          edgeRefMap[it] = to.addEdge(redNodeRefMap[from.redNode(it)],
583                                      blueNodeRefMap[from.blueNode(it)]);
584        }
585      }
586    };
587
588    template <typename BpGraph>
589    struct BpGraphCopySelector<
590      BpGraph,
591      typename enable_if<typename BpGraph::BuildTag, void>::type>
592    {
593      template <typename From, typename RedNodeRefMap,
594                typename BlueNodeRefMap, typename EdgeRefMap>
595      static void copy(const From& from, BpGraph &to,
596                       RedNodeRefMap& redNodeRefMap,
597                       BlueNodeRefMap& blueNodeRefMap,
598                       EdgeRefMap& edgeRefMap) {
599        to.build(from, redNodeRefMap, blueNodeRefMap, edgeRefMap);
600      }
601    };
602
603  }
604
605  /// \brief Check whether a graph is undirected.
606  ///
607  /// This function returns \c true if the given graph is undirected.
608#ifdef DOXYGEN
609  template <typename GR>
610  bool undirected(const GR& g) { return false; }
611#else
612  template <typename GR>
613  typename enable_if<UndirectedTagIndicator<GR>, bool>::type
614  undirected(const GR&) {
615    return true;
616  }
617  template <typename GR>
618  typename disable_if<UndirectedTagIndicator<GR>, bool>::type
619  undirected(const GR&) {
620    return false;
621  }
622#endif
623
624  /// \brief Class to copy a digraph.
625  ///
626  /// Class to copy a digraph to another digraph (duplicate a digraph). The
627  /// simplest way of using it is through the \c digraphCopy() function.
628  ///
629  /// This class not only make a copy of a digraph, but it can create
630  /// references and cross references between the nodes and arcs of
631  /// the two digraphs, and it can copy maps to use with the newly created
632  /// digraph.
633  ///
634  /// To make a copy from a digraph, first an instance of DigraphCopy
635  /// should be created, then the data belongs to the digraph should
636  /// assigned to copy. In the end, the \c run() member should be
637  /// called.
638  ///
639  /// The next code copies a digraph with several data:
640  ///\code
641  ///  DigraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
642  ///  // Create references for the nodes
643  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
644  ///  cg.nodeRef(nr);
645  ///  // Create cross references (inverse) for the arcs
646  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
647  ///  cg.arcCrossRef(acr);
648  ///  // Copy an arc map
649  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
650  ///  NewGraph::ArcMap<double> namap(new_graph);
651  ///  cg.arcMap(oamap, namap);
652  ///  // Copy a node
653  ///  OrigGraph::Node on;
654  ///  NewGraph::Node nn;
655  ///  cg.node(on, nn);
656  ///  // Execute copying
657  ///  cg.run();
658  ///\endcode
659  template <typename From, typename To>
660  class DigraphCopy {
661  private:
662
663    typedef typename From::Node Node;
664    typedef typename From::NodeIt NodeIt;
665    typedef typename From::Arc Arc;
666    typedef typename From::ArcIt ArcIt;
667
668    typedef typename To::Node TNode;
669    typedef typename To::Arc TArc;
670
671    typedef typename From::template NodeMap<TNode> NodeRefMap;
672    typedef typename From::template ArcMap<TArc> ArcRefMap;
673
674  public:
675
676    /// \brief Constructor of DigraphCopy.
677    ///
678    /// Constructor of DigraphCopy for copying the content of the
679    /// \c from digraph into the \c to digraph.
680    DigraphCopy(const From& from, To& to)
681      : _from(from), _to(to) {}
682
683    /// \brief Destructor of DigraphCopy
684    ///
685    /// Destructor of DigraphCopy.
686    ~DigraphCopy() {
687      for (int i = 0; i < int(_node_maps.size()); ++i) {
688        delete _node_maps[i];
689      }
690      for (int i = 0; i < int(_arc_maps.size()); ++i) {
691        delete _arc_maps[i];
692      }
693
694    }
695
696    /// \brief Copy the node references into the given map.
697    ///
698    /// This function copies the node references into the given map.
699    /// The parameter should be a map, whose key type is the Node type of
700    /// the source digraph, while the value type is the Node type of the
701    /// destination digraph.
702    template <typename NodeRef>
703    DigraphCopy& nodeRef(NodeRef& map) {
704      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
705                           NodeRefMap, NodeRef>(map));
706      return *this;
707    }
708
709    /// \brief Copy the node cross references into the given map.
710    ///
711    /// This function copies the node cross references (reverse references)
712    /// into the given map. The parameter should be a map, whose key type
713    /// is the Node type of the destination digraph, while the value type is
714    /// the Node type of the source digraph.
715    template <typename NodeCrossRef>
716    DigraphCopy& nodeCrossRef(NodeCrossRef& map) {
717      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
718                           NodeRefMap, NodeCrossRef>(map));
719      return *this;
720    }
721
722    /// \brief Make a copy of the given node map.
723    ///
724    /// This function makes a copy of the given node map for the newly
725    /// created digraph.
726    /// The key type of the new map \c tmap should be the Node type of the
727    /// destination digraph, and the key type of the original map \c map
728    /// should be the Node type of the source digraph.
729    template <typename FromMap, typename ToMap>
730    DigraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
731      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
732                           NodeRefMap, FromMap, ToMap>(map, tmap));
733      return *this;
734    }
735
736    /// \brief Make a copy of the given node.
737    ///
738    /// This function makes a copy of the given node.
739    DigraphCopy& node(const Node& node, TNode& tnode) {
740      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
741                           NodeRefMap, TNode>(node, tnode));
742      return *this;
743    }
744
745    /// \brief Copy the arc references into the given map.
746    ///
747    /// This function copies the arc references into the given map.
748    /// The parameter should be a map, whose key type is the Arc type of
749    /// the source digraph, while the value type is the Arc type of the
750    /// destination digraph.
751    template <typename ArcRef>
752    DigraphCopy& arcRef(ArcRef& map) {
753      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
754                          ArcRefMap, ArcRef>(map));
755      return *this;
756    }
757
758    /// \brief Copy the arc cross references into the given map.
759    ///
760    /// This function copies the arc cross references (reverse references)
761    /// into the given map. The parameter should be a map, whose key type
762    /// is the Arc type of the destination digraph, while the value type is
763    /// the Arc type of the source digraph.
764    template <typename ArcCrossRef>
765    DigraphCopy& arcCrossRef(ArcCrossRef& map) {
766      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
767                          ArcRefMap, ArcCrossRef>(map));
768      return *this;
769    }
770
771    /// \brief Make a copy of the given arc map.
772    ///
773    /// This function makes a copy of the given arc map for the newly
774    /// created digraph.
775    /// The key type of the new map \c tmap should be the Arc type of the
776    /// destination digraph, and the key type of the original map \c map
777    /// should be the Arc type of the source digraph.
778    template <typename FromMap, typename ToMap>
779    DigraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
780      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
781                          ArcRefMap, FromMap, ToMap>(map, tmap));
782      return *this;
783    }
784
785    /// \brief Make a copy of the given arc.
786    ///
787    /// This function makes a copy of the given arc.
788    DigraphCopy& arc(const Arc& arc, TArc& tarc) {
789      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
790                          ArcRefMap, TArc>(arc, tarc));
791      return *this;
792    }
793
794    /// \brief Execute copying.
795    ///
796    /// This function executes the copying of the digraph along with the
797    /// copying of the assigned data.
798    void run() {
799      NodeRefMap nodeRefMap(_from);
800      ArcRefMap arcRefMap(_from);
801      _core_bits::DigraphCopySelector<To>::
802        copy(_from, _to, nodeRefMap, arcRefMap);
803      for (int i = 0; i < int(_node_maps.size()); ++i) {
804        _node_maps[i]->copy(_from, nodeRefMap);
805      }
806      for (int i = 0; i < int(_arc_maps.size()); ++i) {
807        _arc_maps[i]->copy(_from, arcRefMap);
808      }
809    }
810
811  protected:
812
813    const From& _from;
814    To& _to;
815
816    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
817      _node_maps;
818
819    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
820      _arc_maps;
821
822  };
823
824  /// \brief Copy a digraph to another digraph.
825  ///
826  /// This function copies a digraph to another digraph.
827  /// The complete usage of it is detailed in the DigraphCopy class, but
828  /// a short example shows a basic work:
829  ///\code
830  /// digraphCopy(src, trg).nodeRef(nr).arcCrossRef(acr).run();
831  ///\endcode
832  ///
833  /// After the copy the \c nr map will contain the mapping from the
834  /// nodes of the \c from digraph to the nodes of the \c to digraph and
835  /// \c acr will contain the mapping from the arcs of the \c to digraph
836  /// to the arcs of the \c from digraph.
837  ///
838  /// \see DigraphCopy
839  template <typename From, typename To>
840  DigraphCopy<From, To> digraphCopy(const From& from, To& to) {
841    return DigraphCopy<From, To>(from, to);
842  }
843
844  /// \brief Class to copy a graph.
845  ///
846  /// Class to copy a graph to another graph (duplicate a graph). The
847  /// simplest way of using it is through the \c graphCopy() function.
848  ///
849  /// This class not only make a copy of a graph, but it can create
850  /// references and cross references between the nodes, edges and arcs of
851  /// the two graphs, and it can copy maps for using with the newly created
852  /// graph.
853  ///
854  /// To make a copy from a graph, first an instance of GraphCopy
855  /// should be created, then the data belongs to the graph should
856  /// assigned to copy. In the end, the \c run() member should be
857  /// called.
858  ///
859  /// The next code copies a graph with several data:
860  ///\code
861  ///  GraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
862  ///  // Create references for the nodes
863  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
864  ///  cg.nodeRef(nr);
865  ///  // Create cross references (inverse) for the edges
866  ///  NewGraph::EdgeMap<OrigGraph::Edge> ecr(new_graph);
867  ///  cg.edgeCrossRef(ecr);
868  ///  // Copy an edge map
869  ///  OrigGraph::EdgeMap<double> oemap(orig_graph);
870  ///  NewGraph::EdgeMap<double> nemap(new_graph);
871  ///  cg.edgeMap(oemap, nemap);
872  ///  // Copy a node
873  ///  OrigGraph::Node on;
874  ///  NewGraph::Node nn;
875  ///  cg.node(on, nn);
876  ///  // Execute copying
877  ///  cg.run();
878  ///\endcode
879  template <typename From, typename To>
880  class GraphCopy {
881  private:
882
883    typedef typename From::Node Node;
884    typedef typename From::NodeIt NodeIt;
885    typedef typename From::Arc Arc;
886    typedef typename From::ArcIt ArcIt;
887    typedef typename From::Edge Edge;
888    typedef typename From::EdgeIt EdgeIt;
889
890    typedef typename To::Node TNode;
891    typedef typename To::Arc TArc;
892    typedef typename To::Edge TEdge;
893
894    typedef typename From::template NodeMap<TNode> NodeRefMap;
895    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
896
897    struct ArcRefMap {
898      ArcRefMap(const From& from, const To& to,
899                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
900        : _from(from), _to(to),
901          _edge_ref(edge_ref), _node_ref(node_ref) {}
902
903      typedef typename From::Arc Key;
904      typedef typename To::Arc Value;
905
906      Value operator[](const Key& key) const {
907        bool forward = _from.u(key) != _from.v(key) ?
908          _node_ref[_from.source(key)] ==
909          _to.source(_to.direct(_edge_ref[key], true)) :
910          _from.direction(key);
911        return _to.direct(_edge_ref[key], forward);
912      }
913
914      const From& _from;
915      const To& _to;
916      const EdgeRefMap& _edge_ref;
917      const NodeRefMap& _node_ref;
918    };
919
920  public:
921
922    /// \brief Constructor of GraphCopy.
923    ///
924    /// Constructor of GraphCopy for copying the content of the
925    /// \c from graph into the \c to graph.
926    GraphCopy(const From& from, To& to)
927      : _from(from), _to(to) {}
928
929    /// \brief Destructor of GraphCopy
930    ///
931    /// Destructor of GraphCopy.
932    ~GraphCopy() {
933      for (int i = 0; i < int(_node_maps.size()); ++i) {
934        delete _node_maps[i];
935      }
936      for (int i = 0; i < int(_arc_maps.size()); ++i) {
937        delete _arc_maps[i];
938      }
939      for (int i = 0; i < int(_edge_maps.size()); ++i) {
940        delete _edge_maps[i];
941      }
942    }
943
944    /// \brief Copy the node references into the given map.
945    ///
946    /// This function copies the node references into the given map.
947    /// The parameter should be a map, whose key type is the Node type of
948    /// the source graph, while the value type is the Node type of the
949    /// destination graph.
950    template <typename NodeRef>
951    GraphCopy& nodeRef(NodeRef& map) {
952      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
953                           NodeRefMap, NodeRef>(map));
954      return *this;
955    }
956
957    /// \brief Copy the node cross references into the given map.
958    ///
959    /// This function copies the node cross references (reverse references)
960    /// into the given map. The parameter should be a map, whose key type
961    /// is the Node type of the destination graph, while the value type is
962    /// the Node type of the source graph.
963    template <typename NodeCrossRef>
964    GraphCopy& nodeCrossRef(NodeCrossRef& map) {
965      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
966                           NodeRefMap, NodeCrossRef>(map));
967      return *this;
968    }
969
970    /// \brief Make a copy of the given node map.
971    ///
972    /// This function makes a copy of the given node map for the newly
973    /// created graph.
974    /// The key type of the new map \c tmap should be the Node type of the
975    /// destination graph, and the key type of the original map \c map
976    /// should be the Node type of the source graph.
977    template <typename FromMap, typename ToMap>
978    GraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
979      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
980                           NodeRefMap, FromMap, ToMap>(map, tmap));
981      return *this;
982    }
983
984    /// \brief Make a copy of the given node.
985    ///
986    /// This function makes a copy of the given node.
987    GraphCopy& node(const Node& node, TNode& tnode) {
988      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
989                           NodeRefMap, TNode>(node, tnode));
990      return *this;
991    }
992
993    /// \brief Copy the arc references into the given map.
994    ///
995    /// This function copies the arc references into the given map.
996    /// The parameter should be a map, whose key type is the Arc type of
997    /// the source graph, while the value type is the Arc type of the
998    /// destination graph.
999    template <typename ArcRef>
1000    GraphCopy& arcRef(ArcRef& map) {
1001      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
1002                          ArcRefMap, ArcRef>(map));
1003      return *this;
1004    }
1005
1006    /// \brief Copy the arc cross references into the given map.
1007    ///
1008    /// This function copies the arc cross references (reverse references)
1009    /// into the given map. The parameter should be a map, whose key type
1010    /// is the Arc type of the destination graph, while the value type is
1011    /// the Arc type of the source graph.
1012    template <typename ArcCrossRef>
1013    GraphCopy& arcCrossRef(ArcCrossRef& map) {
1014      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
1015                          ArcRefMap, ArcCrossRef>(map));
1016      return *this;
1017    }
1018
1019    /// \brief Make a copy of the given arc map.
1020    ///
1021    /// This function makes a copy of the given arc map for the newly
1022    /// created graph.
1023    /// The key type of the new map \c tmap should be the Arc type of the
1024    /// destination graph, and the key type of the original map \c map
1025    /// should be the Arc type of the source graph.
1026    template <typename FromMap, typename ToMap>
1027    GraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
1028      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
1029                          ArcRefMap, FromMap, ToMap>(map, tmap));
1030      return *this;
1031    }
1032
1033    /// \brief Make a copy of the given arc.
1034    ///
1035    /// This function makes a copy of the given arc.
1036    GraphCopy& arc(const Arc& arc, TArc& tarc) {
1037      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
1038                          ArcRefMap, TArc>(arc, tarc));
1039      return *this;
1040    }
1041
1042    /// \brief Copy the edge references into the given map.
1043    ///
1044    /// This function copies the edge references into the given map.
1045    /// The parameter should be a map, whose key type is the Edge type of
1046    /// the source graph, while the value type is the Edge type of the
1047    /// destination graph.
1048    template <typename EdgeRef>
1049    GraphCopy& edgeRef(EdgeRef& map) {
1050      _edge_maps.push_back(new _core_bits::RefCopy<From, Edge,
1051                           EdgeRefMap, EdgeRef>(map));
1052      return *this;
1053    }
1054
1055    /// \brief Copy the edge cross references into the given map.
1056    ///
1057    /// This function copies the edge cross references (reverse references)
1058    /// into the given map. The parameter should be a map, whose key type
1059    /// is the Edge type of the destination graph, while the value type is
1060    /// the Edge type of the source graph.
1061    template <typename EdgeCrossRef>
1062    GraphCopy& edgeCrossRef(EdgeCrossRef& map) {
1063      _edge_maps.push_back(new _core_bits::CrossRefCopy<From,
1064                           Edge, EdgeRefMap, EdgeCrossRef>(map));
1065      return *this;
1066    }
1067
1068    /// \brief Make a copy of the given edge map.
1069    ///
1070    /// This function makes a copy of the given edge map for the newly
1071    /// created graph.
1072    /// The key type of the new map \c tmap should be the Edge type of the
1073    /// destination graph, and the key type of the original map \c map
1074    /// should be the Edge type of the source graph.
1075    template <typename FromMap, typename ToMap>
1076    GraphCopy& edgeMap(const FromMap& map, ToMap& tmap) {
1077      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
1078                           EdgeRefMap, FromMap, ToMap>(map, tmap));
1079      return *this;
1080    }
1081
1082    /// \brief Make a copy of the given edge.
1083    ///
1084    /// This function makes a copy of the given edge.
1085    GraphCopy& edge(const Edge& edge, TEdge& tedge) {
1086      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
1087                           EdgeRefMap, TEdge>(edge, tedge));
1088      return *this;
1089    }
1090
1091    /// \brief Execute copying.
1092    ///
1093    /// This function executes the copying of the graph along with the
1094    /// copying of the assigned data.
1095    void run() {
1096      NodeRefMap nodeRefMap(_from);
1097      EdgeRefMap edgeRefMap(_from);
1098      ArcRefMap arcRefMap(_from, _to, edgeRefMap, nodeRefMap);
1099      _core_bits::GraphCopySelector<To>::
1100        copy(_from, _to, nodeRefMap, edgeRefMap);
1101      for (int i = 0; i < int(_node_maps.size()); ++i) {
1102        _node_maps[i]->copy(_from, nodeRefMap);
1103      }
1104      for (int i = 0; i < int(_edge_maps.size()); ++i) {
1105        _edge_maps[i]->copy(_from, edgeRefMap);
1106      }
1107      for (int i = 0; i < int(_arc_maps.size()); ++i) {
1108        _arc_maps[i]->copy(_from, arcRefMap);
1109      }
1110    }
1111
1112  private:
1113
1114    const From& _from;
1115    To& _to;
1116
1117    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
1118      _node_maps;
1119
1120    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
1121      _arc_maps;
1122
1123    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
1124      _edge_maps;
1125
1126  };
1127
1128  /// \brief Copy a graph to another graph.
1129  ///
1130  /// This function copies a graph to another graph.
1131  /// The complete usage of it is detailed in the GraphCopy class,
1132  /// but a short example shows a basic work:
1133  ///\code
1134  /// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run();
1135  ///\endcode
1136  ///
1137  /// After the copy the \c nr map will contain the mapping from the
1138  /// nodes of the \c from graph to the nodes of the \c to graph and
1139  /// \c ecr will contain the mapping from the edges of the \c to graph
1140  /// to the edges of the \c from graph.
1141  ///
1142  /// \see GraphCopy
1143  template <typename From, typename To>
1144  GraphCopy<From, To>
1145  graphCopy(const From& from, To& to) {
1146    return GraphCopy<From, To>(from, to);
1147  }
1148
1149  /// \brief Class to copy a bipartite graph.
1150  ///
1151  /// Class to copy a bipartite graph to another graph (duplicate a
1152  /// graph). The simplest way of using it is through the
1153  /// \c bpGraphCopy() function.
1154  ///
1155  /// This class not only make a copy of a bipartite graph, but it can
1156  /// create references and cross references between the nodes, edges
1157  /// and arcs of the two graphs, and it can copy maps for using with
1158  /// the newly created graph.
1159  ///
1160  /// To make a copy from a graph, first an instance of BpGraphCopy
1161  /// should be created, then the data belongs to the graph should
1162  /// assigned to copy. In the end, the \c run() member should be
1163  /// called.
1164  ///
1165  /// The next code copies a graph with several data:
1166  ///\code
1167  ///  BpGraphCopy<OrigBpGraph, NewBpGraph> cg(orig_graph, new_graph);
1168  ///  // Create references for the nodes
1169  ///  OrigBpGraph::NodeMap<NewBpGraph::Node> nr(orig_graph);
1170  ///  cg.nodeRef(nr);
1171  ///  // Create cross references (inverse) for the edges
1172  ///  NewBpGraph::EdgeMap<OrigBpGraph::Edge> ecr(new_graph);
1173  ///  cg.edgeCrossRef(ecr);
1174  ///  // Copy a red node map
1175  ///  OrigBpGraph::RedNodeMap<double> ormap(orig_graph);
1176  ///  NewBpGraph::RedNodeMap<double> nrmap(new_graph);
1177  ///  cg.redNodeMap(ormap, nrmap);
1178  ///  // Copy a node
1179  ///  OrigBpGraph::Node on;
1180  ///  NewBpGraph::Node nn;
1181  ///  cg.node(on, nn);
1182  ///  // Execute copying
1183  ///  cg.run();
1184  ///\endcode
1185  template <typename From, typename To>
1186  class BpGraphCopy {
1187  private:
1188
1189    typedef typename From::Node Node;
1190    typedef typename From::RedNode RedNode;
1191    typedef typename From::BlueNode BlueNode;
1192    typedef typename From::NodeIt NodeIt;
1193    typedef typename From::Arc Arc;
1194    typedef typename From::ArcIt ArcIt;
1195    typedef typename From::Edge Edge;
1196    typedef typename From::EdgeIt EdgeIt;
1197
1198    typedef typename To::Node TNode;
1199    typedef typename To::RedNode TRedNode;
1200    typedef typename To::BlueNode TBlueNode;
1201    typedef typename To::Arc TArc;
1202    typedef typename To::Edge TEdge;
1203
1204    typedef typename From::template RedNodeMap<TRedNode> RedNodeRefMap;
1205    typedef typename From::template BlueNodeMap<TBlueNode> BlueNodeRefMap;
1206    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
1207
1208    struct NodeRefMap {
1209      NodeRefMap(const From& from, const RedNodeRefMap& red_node_ref,
1210                 const BlueNodeRefMap& blue_node_ref)
1211        : _from(from), _red_node_ref(red_node_ref),
1212          _blue_node_ref(blue_node_ref) {}
1213
1214      typedef typename From::Node Key;
1215      typedef typename To::Node Value;
1216
1217      Value operator[](const Key& key) const {
1218        if (_from.red(key)) {
1219          return _red_node_ref[_from.asRedNodeUnsafe(key)];
1220        } else {
1221          return _blue_node_ref[_from.asBlueNodeUnsafe(key)];
1222        }
1223      }
1224
1225      const From& _from;
1226      const RedNodeRefMap& _red_node_ref;
1227      const BlueNodeRefMap& _blue_node_ref;
1228    };
1229
1230    struct ArcRefMap {
1231      ArcRefMap(const From& from, const To& to, const EdgeRefMap& edge_ref)
1232        : _from(from), _to(to), _edge_ref(edge_ref) {}
1233
1234      typedef typename From::Arc Key;
1235      typedef typename To::Arc Value;
1236
1237      Value operator[](const Key& key) const {
1238        return _to.direct(_edge_ref[key], _from.direction(key));
1239      }
1240
1241      const From& _from;
1242      const To& _to;
1243      const EdgeRefMap& _edge_ref;
1244    };
1245
1246  public:
1247
1248    /// \brief Constructor of BpGraphCopy.
1249    ///
1250    /// Constructor of BpGraphCopy for copying the content of the
1251    /// \c from graph into the \c to graph.
1252    BpGraphCopy(const From& from, To& to)
1253      : _from(from), _to(to) {}
1254
1255    /// \brief Destructor of BpGraphCopy
1256    ///
1257    /// Destructor of BpGraphCopy.
1258    ~BpGraphCopy() {
1259      for (int i = 0; i < int(_node_maps.size()); ++i) {
1260        delete _node_maps[i];
1261      }
1262      for (int i = 0; i < int(_red_maps.size()); ++i) {
1263        delete _red_maps[i];
1264      }
1265      for (int i = 0; i < int(_blue_maps.size()); ++i) {
1266        delete _blue_maps[i];
1267      }
1268      for (int i = 0; i < int(_arc_maps.size()); ++i) {
1269        delete _arc_maps[i];
1270      }
1271      for (int i = 0; i < int(_edge_maps.size()); ++i) {
1272        delete _edge_maps[i];
1273      }
1274    }
1275
1276    /// \brief Copy the node references into the given map.
1277    ///
1278    /// This function copies the node references into the given map.
1279    /// The parameter should be a map, whose key type is the Node type of
1280    /// the source graph, while the value type is the Node type of the
1281    /// destination graph.
1282    template <typename NodeRef>
1283    BpGraphCopy& nodeRef(NodeRef& map) {
1284      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
1285                           NodeRefMap, NodeRef>(map));
1286      return *this;
1287    }
1288
1289    /// \brief Copy the node cross references into the given map.
1290    ///
1291    /// This function copies the node cross references (reverse references)
1292    /// into the given map. The parameter should be a map, whose key type
1293    /// is the Node type of the destination graph, while the value type is
1294    /// the Node type of the source graph.
1295    template <typename NodeCrossRef>
1296    BpGraphCopy& nodeCrossRef(NodeCrossRef& map) {
1297      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
1298                           NodeRefMap, NodeCrossRef>(map));
1299      return *this;
1300    }
1301
1302    /// \brief Make a copy of the given node map.
1303    ///
1304    /// This function makes a copy of the given node map for the newly
1305    /// created graph.
1306    /// The key type of the new map \c tmap should be the Node type of the
1307    /// destination graph, and the key type of the original map \c map
1308    /// should be the Node type of the source graph.
1309    template <typename FromMap, typename ToMap>
1310    BpGraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
1311      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
1312                           NodeRefMap, FromMap, ToMap>(map, tmap));
1313      return *this;
1314    }
1315
1316    /// \brief Make a copy of the given node.
1317    ///
1318    /// This function makes a copy of the given node.
1319    BpGraphCopy& node(const Node& node, TNode& tnode) {
1320      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
1321                           NodeRefMap, TNode>(node, tnode));
1322      return *this;
1323    }
1324
1325    /// \brief Copy the red node references into the given map.
1326    ///
1327    /// This function copies the red node references into the given
1328    /// map.  The parameter should be a map, whose key type is the
1329    /// Node type of the source graph with the red item set, while the
1330    /// value type is the Node type of the destination graph.
1331    template <typename RedRef>
1332    BpGraphCopy& redRef(RedRef& map) {
1333      _red_maps.push_back(new _core_bits::RefCopy<From, RedNode,
1334                          RedNodeRefMap, RedRef>(map));
1335      return *this;
1336    }
1337
1338    /// \brief Copy the red node cross references into the given map.
1339    ///
1340    /// This function copies the red node cross references (reverse
1341    /// references) into the given map. The parameter should be a map,
1342    /// whose key type is the Node type of the destination graph with
1343    /// the red item set, while the value type is the Node type of the
1344    /// source graph.
1345    template <typename RedCrossRef>
1346    BpGraphCopy& redCrossRef(RedCrossRef& map) {
1347      _red_maps.push_back(new _core_bits::CrossRefCopy<From, RedNode,
1348                          RedNodeRefMap, RedCrossRef>(map));
1349      return *this;
1350    }
1351
1352    /// \brief Make a copy of the given red node map.
1353    ///
1354    /// This function makes a copy of the given red node map for the newly
1355    /// created graph.
1356    /// The key type of the new map \c tmap should be the Node type of
1357    /// the destination graph with the red items, and the key type of
1358    /// the original map \c map should be the Node type of the source
1359    /// graph.
1360    template <typename FromMap, typename ToMap>
1361    BpGraphCopy& redNodeMap(const FromMap& map, ToMap& tmap) {
1362      _red_maps.push_back(new _core_bits::MapCopy<From, RedNode,
1363                          RedNodeRefMap, FromMap, ToMap>(map, tmap));
1364      return *this;
1365    }
1366
1367    /// \brief Make a copy of the given red node.
1368    ///
1369    /// This function makes a copy of the given red node.
1370    BpGraphCopy& redNode(const RedNode& node, TRedNode& tnode) {
1371      _red_maps.push_back(new _core_bits::ItemCopy<From, RedNode,
1372                          RedNodeRefMap, TRedNode>(node, tnode));
1373      return *this;
1374    }
1375
1376    /// \brief Copy the blue node references into the given map.
1377    ///
1378    /// This function copies the blue node references into the given
1379    /// map.  The parameter should be a map, whose key type is the
1380    /// Node type of the source graph with the blue item set, while the
1381    /// value type is the Node type of the destination graph.
1382    template <typename BlueRef>
1383    BpGraphCopy& blueRef(BlueRef& map) {
1384      _blue_maps.push_back(new _core_bits::RefCopy<From, BlueNode,
1385                           BlueNodeRefMap, BlueRef>(map));
1386      return *this;
1387    }
1388
1389    /// \brief Copy the blue node cross references into the given map.
1390    ///
1391    /// This function copies the blue node cross references (reverse
1392    /// references) into the given map. The parameter should be a map,
1393    /// whose key type is the Node type of the destination graph with
1394    /// the blue item set, while the value type is the Node type of the
1395    /// source graph.
1396    template <typename BlueCrossRef>
1397    BpGraphCopy& blueCrossRef(BlueCrossRef& map) {
1398      _blue_maps.push_back(new _core_bits::CrossRefCopy<From, BlueNode,
1399                           BlueNodeRefMap, BlueCrossRef>(map));
1400      return *this;
1401    }
1402
1403    /// \brief Make a copy of the given blue node map.
1404    ///
1405    /// This function makes a copy of the given blue node map for the newly
1406    /// created graph.
1407    /// The key type of the new map \c tmap should be the Node type of
1408    /// the destination graph with the blue items, and the key type of
1409    /// the original map \c map should be the Node type of the source
1410    /// graph.
1411    template <typename FromMap, typename ToMap>
1412    BpGraphCopy& blueNodeMap(const FromMap& map, ToMap& tmap) {
1413      _blue_maps.push_back(new _core_bits::MapCopy<From, BlueNode,
1414                           BlueNodeRefMap, FromMap, ToMap>(map, tmap));
1415      return *this;
1416    }
1417
1418    /// \brief Make a copy of the given blue node.
1419    ///
1420    /// This function makes a copy of the given blue node.
1421    BpGraphCopy& blueNode(const BlueNode& node, TBlueNode& tnode) {
1422      _blue_maps.push_back(new _core_bits::ItemCopy<From, BlueNode,
1423                           BlueNodeRefMap, TBlueNode>(node, tnode));
1424      return *this;
1425    }
1426
1427    /// \brief Copy the arc references into the given map.
1428    ///
1429    /// This function copies the arc references into the given map.
1430    /// The parameter should be a map, whose key type is the Arc type of
1431    /// the source graph, while the value type is the Arc type of the
1432    /// destination graph.
1433    template <typename ArcRef>
1434    BpGraphCopy& arcRef(ArcRef& map) {
1435      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
1436                          ArcRefMap, ArcRef>(map));
1437      return *this;
1438    }
1439
1440    /// \brief Copy the arc cross references into the given map.
1441    ///
1442    /// This function copies the arc cross references (reverse references)
1443    /// into the given map. The parameter should be a map, whose key type
1444    /// is the Arc type of the destination graph, while the value type is
1445    /// the Arc type of the source graph.
1446    template <typename ArcCrossRef>
1447    BpGraphCopy& arcCrossRef(ArcCrossRef& map) {
1448      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
1449                          ArcRefMap, ArcCrossRef>(map));
1450      return *this;
1451    }
1452
1453    /// \brief Make a copy of the given arc map.
1454    ///
1455    /// This function makes a copy of the given arc map for the newly
1456    /// created graph.
1457    /// The key type of the new map \c tmap should be the Arc type of the
1458    /// destination graph, and the key type of the original map \c map
1459    /// should be the Arc type of the source graph.
1460    template <typename FromMap, typename ToMap>
1461    BpGraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
1462      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
1463                          ArcRefMap, FromMap, ToMap>(map, tmap));
1464      return *this;
1465    }
1466
1467    /// \brief Make a copy of the given arc.
1468    ///
1469    /// This function makes a copy of the given arc.
1470    BpGraphCopy& arc(const Arc& arc, TArc& tarc) {
1471      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
1472                          ArcRefMap, TArc>(arc, tarc));
1473      return *this;
1474    }
1475
1476    /// \brief Copy the edge references into the given map.
1477    ///
1478    /// This function copies the edge references into the given map.
1479    /// The parameter should be a map, whose key type is the Edge type of
1480    /// the source graph, while the value type is the Edge type of the
1481    /// destination graph.
1482    template <typename EdgeRef>
1483    BpGraphCopy& edgeRef(EdgeRef& map) {
1484      _edge_maps.push_back(new _core_bits::RefCopy<From, Edge,
1485                           EdgeRefMap, EdgeRef>(map));
1486      return *this;
1487    }
1488
1489    /// \brief Copy the edge cross references into the given map.
1490    ///
1491    /// This function copies the edge cross references (reverse references)
1492    /// into the given map. The parameter should be a map, whose key type
1493    /// is the Edge type of the destination graph, while the value type is
1494    /// the Edge type of the source graph.
1495    template <typename EdgeCrossRef>
1496    BpGraphCopy& edgeCrossRef(EdgeCrossRef& map) {
1497      _edge_maps.push_back(new _core_bits::CrossRefCopy<From,
1498                           Edge, EdgeRefMap, EdgeCrossRef>(map));
1499      return *this;
1500    }
1501
1502    /// \brief Make a copy of the given edge map.
1503    ///
1504    /// This function makes a copy of the given edge map for the newly
1505    /// created graph.
1506    /// The key type of the new map \c tmap should be the Edge type of the
1507    /// destination graph, and the key type of the original map \c map
1508    /// should be the Edge type of the source graph.
1509    template <typename FromMap, typename ToMap>
1510    BpGraphCopy& edgeMap(const FromMap& map, ToMap& tmap) {
1511      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
1512                           EdgeRefMap, FromMap, ToMap>(map, tmap));
1513      return *this;
1514    }
1515
1516    /// \brief Make a copy of the given edge.
1517    ///
1518    /// This function makes a copy of the given edge.
1519    BpGraphCopy& edge(const Edge& edge, TEdge& tedge) {
1520      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
1521                           EdgeRefMap, TEdge>(edge, tedge));
1522      return *this;
1523    }
1524
1525    /// \brief Execute copying.
1526    ///
1527    /// This function executes the copying of the graph along with the
1528    /// copying of the assigned data.
1529    void run() {
1530      RedNodeRefMap redNodeRefMap(_from);
1531      BlueNodeRefMap blueNodeRefMap(_from);
1532      NodeRefMap nodeRefMap(_from, redNodeRefMap, blueNodeRefMap);
1533      EdgeRefMap edgeRefMap(_from);
1534      ArcRefMap arcRefMap(_from, _to, edgeRefMap);
1535      _core_bits::BpGraphCopySelector<To>::
1536        copy(_from, _to, redNodeRefMap, blueNodeRefMap, edgeRefMap);
1537      for (int i = 0; i < int(_node_maps.size()); ++i) {
1538        _node_maps[i]->copy(_from, nodeRefMap);
1539      }
1540      for (int i = 0; i < int(_red_maps.size()); ++i) {
1541        _red_maps[i]->copy(_from, redNodeRefMap);
1542      }
1543      for (int i = 0; i < int(_blue_maps.size()); ++i) {
1544        _blue_maps[i]->copy(_from, blueNodeRefMap);
1545      }
1546      for (int i = 0; i < int(_edge_maps.size()); ++i) {
1547        _edge_maps[i]->copy(_from, edgeRefMap);
1548      }
1549      for (int i = 0; i < int(_arc_maps.size()); ++i) {
1550        _arc_maps[i]->copy(_from, arcRefMap);
1551      }
1552    }
1553
1554  private:
1555
1556    const From& _from;
1557    To& _to;
1558
1559    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
1560      _node_maps;
1561
1562    std::vector<_core_bits::MapCopyBase<From, RedNode, RedNodeRefMap>* >
1563      _red_maps;
1564
1565    std::vector<_core_bits::MapCopyBase<From, BlueNode, BlueNodeRefMap>* >
1566      _blue_maps;
1567
1568    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
1569      _arc_maps;
1570
1571    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
1572      _edge_maps;
1573
1574  };
1575
1576  /// \brief Copy a graph to another graph.
1577  ///
1578  /// This function copies a graph to another graph.
1579  /// The complete usage of it is detailed in the BpGraphCopy class,
1580  /// but a short example shows a basic work:
1581  ///\code
1582  /// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run();
1583  ///\endcode
1584  ///
1585  /// After the copy the \c nr map will contain the mapping from the
1586  /// nodes of the \c from graph to the nodes of the \c to graph and
1587  /// \c ecr will contain the mapping from the edges of the \c to graph
1588  /// to the edges of the \c from graph.
1589  ///
1590  /// \see BpGraphCopy
1591  template <typename From, typename To>
1592  BpGraphCopy<From, To>
1593  bpGraphCopy(const From& from, To& to) {
1594    return BpGraphCopy<From, To>(from, to);
1595  }
1596
1597  namespace _core_bits {
1598
1599    template <typename Graph, typename Enable = void>
1600    struct FindArcSelector {
1601      typedef typename Graph::Node Node;
1602      typedef typename Graph::Arc Arc;
1603      static Arc find(const Graph &g, Node u, Node v, Arc e) {
1604        if (e == INVALID) {
1605          g.firstOut(e, u);
1606        } else {
1607          g.nextOut(e);
1608        }
1609        while (e != INVALID && g.target(e) != v) {
1610          g.nextOut(e);
1611        }
1612        return e;
1613      }
1614    };
1615
1616    template <typename Graph>
1617    struct FindArcSelector<
1618      Graph,
1619      typename enable_if<typename Graph::FindArcTag, void>::type>
1620    {
1621      typedef typename Graph::Node Node;
1622      typedef typename Graph::Arc Arc;
1623      static Arc find(const Graph &g, Node u, Node v, Arc prev) {
1624        return g.findArc(u, v, prev);
1625      }
1626    };
1627  }
1628
1629  /// \brief Find an arc between two nodes of a digraph.
1630  ///
1631  /// This function finds an arc from node \c u to node \c v in the
1632  /// digraph \c g.
1633  ///
1634  /// If \c prev is \ref INVALID (this is the default value), then
1635  /// it finds the first arc from \c u to \c v. Otherwise it looks for
1636  /// the next arc from \c u to \c v after \c prev.
1637  /// \return The found arc or \ref INVALID if there is no such an arc.
1638  ///
1639  /// Thus you can iterate through each arc from \c u to \c v as it follows.
1640  ///\code
1641  /// for(Arc e = findArc(g,u,v); e != INVALID; e = findArc(g,u,v,e)) {
1642  ///   ...
1643  /// }
1644  ///\endcode
1645  ///
1646  /// \note \ref ConArcIt provides iterator interface for the same
1647  /// functionality.
1648  ///
1649  ///\sa ConArcIt
1650  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1651  template <typename Graph>
1652  inline typename Graph::Arc
1653  findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1654          typename Graph::Arc prev = INVALID) {
1655    return _core_bits::FindArcSelector<Graph>::find(g, u, v, prev);
1656  }
1657
1658  /// \brief Iterator for iterating on parallel arcs connecting the same nodes.
1659  ///
1660  /// Iterator for iterating on parallel arcs connecting the same nodes. It is
1661  /// a higher level interface for the \ref findArc() function. You can
1662  /// use it the following way:
1663  ///\code
1664  /// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) {
1665  ///   ...
1666  /// }
1667  ///\endcode
1668  ///
1669  ///\sa findArc()
1670  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1671  template <typename GR>
1672  class ConArcIt : public GR::Arc {
1673    typedef typename GR::Arc Parent;
1674
1675  public:
1676
1677    typedef typename GR::Arc Arc;
1678    typedef typename GR::Node Node;
1679
1680    /// \brief Constructor.
1681    ///
1682    /// Construct a new ConArcIt iterating on the arcs that
1683    /// connects nodes \c u and \c v.
1684    ConArcIt(const GR& g, Node u, Node v) : _graph(g) {
1685      Parent::operator=(findArc(_graph, u, v));
1686    }
1687
1688    /// \brief Constructor.
1689    ///
1690    /// Construct a new ConArcIt that continues the iterating from arc \c a.
1691    ConArcIt(const GR& g, Arc a) : Parent(a), _graph(g) {}
1692
1693    /// \brief Increment operator.
1694    ///
1695    /// It increments the iterator and gives back the next arc.
1696    ConArcIt& operator++() {
1697      Parent::operator=(findArc(_graph, _graph.source(*this),
1698                                _graph.target(*this), *this));
1699      return *this;
1700    }
1701  private:
1702    const GR& _graph;
1703  };
1704
1705  namespace _core_bits {
1706
1707    template <typename Graph, typename Enable = void>
1708    struct FindEdgeSelector {
1709      typedef typename Graph::Node Node;
1710      typedef typename Graph::Edge Edge;
1711      static Edge find(const Graph &g, Node u, Node v, Edge e) {
1712        bool b;
1713        if (u != v) {
1714          if (e == INVALID) {
1715            g.firstInc(e, b, u);
1716          } else {
1717            b = g.u(e) == u;
1718            g.nextInc(e, b);
1719          }
1720          while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) {
1721            g.nextInc(e, b);
1722          }
1723        } else {
1724          if (e == INVALID) {
1725            g.firstInc(e, b, u);
1726          } else {
1727            b = true;
1728            g.nextInc(e, b);
1729          }
1730          while (e != INVALID && (!b || g.v(e) != v)) {
1731            g.nextInc(e, b);
1732          }
1733        }
1734        return e;
1735      }
1736    };
1737
1738    template <typename Graph>
1739    struct FindEdgeSelector<
1740      Graph,
1741      typename enable_if<typename Graph::FindEdgeTag, void>::type>
1742    {
1743      typedef typename Graph::Node Node;
1744      typedef typename Graph::Edge Edge;
1745      static Edge find(const Graph &g, Node u, Node v, Edge prev) {
1746        return g.findEdge(u, v, prev);
1747      }
1748    };
1749  }
1750
1751  /// \brief Find an edge between two nodes of a graph.
1752  ///
1753  /// This function finds an edge from node \c u to node \c v in graph \c g.
1754  /// If node \c u and node \c v is equal then each loop edge
1755  /// will be enumerated once.
1756  ///
1757  /// If \c prev is \ref INVALID (this is the default value), then
1758  /// it finds the first edge from \c u to \c v. Otherwise it looks for
1759  /// the next edge from \c u to \c v after \c prev.
1760  /// \return The found edge or \ref INVALID if there is no such an edge.
1761  ///
1762  /// Thus you can iterate through each edge between \c u and \c v
1763  /// as it follows.
1764  ///\code
1765  /// for(Edge e = findEdge(g,u,v); e != INVALID; e = findEdge(g,u,v,e)) {
1766  ///   ...
1767  /// }
1768  ///\endcode
1769  ///
1770  /// \note \ref ConEdgeIt provides iterator interface for the same
1771  /// functionality.
1772  ///
1773  ///\sa ConEdgeIt
1774  template <typename Graph>
1775  inline typename Graph::Edge
1776  findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1777            typename Graph::Edge p = INVALID) {
1778    return _core_bits::FindEdgeSelector<Graph>::find(g, u, v, p);
1779  }
1780
1781  /// \brief Iterator for iterating on parallel edges connecting the same nodes.
1782  ///
1783  /// Iterator for iterating on parallel edges connecting the same nodes.
1784  /// It is a higher level interface for the findEdge() function. You can
1785  /// use it the following way:
1786  ///\code
1787  /// for (ConEdgeIt<Graph> it(g, u, v); it != INVALID; ++it) {
1788  ///   ...
1789  /// }
1790  ///\endcode
1791  ///
1792  ///\sa findEdge()
1793  template <typename GR>
1794  class ConEdgeIt : public GR::Edge {
1795    typedef typename GR::Edge Parent;
1796
1797  public:
1798
1799    typedef typename GR::Edge Edge;
1800    typedef typename GR::Node Node;
1801
1802    /// \brief Constructor.
1803    ///
1804    /// Construct a new ConEdgeIt iterating on the edges that
1805    /// connects nodes \c u and \c v.
1806    ConEdgeIt(const GR& g, Node u, Node v) : _graph(g), _u(u), _v(v) {
1807      Parent::operator=(findEdge(_graph, _u, _v));
1808    }
1809
1810    /// \brief Constructor.
1811    ///
1812    /// Construct a new ConEdgeIt that continues iterating from edge \c e.
1813    ConEdgeIt(const GR& g, Edge e) : Parent(e), _graph(g) {}
1814
1815    /// \brief Increment operator.
1816    ///
1817    /// It increments the iterator and gives back the next edge.
1818    ConEdgeIt& operator++() {
1819      Parent::operator=(findEdge(_graph, _u, _v, *this));
1820      return *this;
1821    }
1822  private:
1823    const GR& _graph;
1824    Node _u, _v;
1825  };
1826
1827
1828  ///Dynamic arc look-up between given endpoints.
1829
1830  ///Using this class, you can find an arc in a digraph from a given
1831  ///source to a given target in amortized time <em>O</em>(log<em>d</em>),
1832  ///where <em>d</em> is the out-degree of the source node.
1833  ///
1834  ///It is possible to find \e all parallel arcs between two nodes with
1835  ///the \c operator() member.
1836  ///
1837  ///This is a dynamic data structure. Consider to use \ref ArcLookUp or
1838  ///\ref AllArcLookUp if your digraph is not changed so frequently.
1839  ///
1840  ///This class uses a self-adjusting binary search tree, the Splay tree
1841  ///of Sleator and Tarjan to guarantee the logarithmic amortized
1842  ///time bound for arc look-ups. This class also guarantees the
1843  ///optimal time bound in a constant factor for any distribution of
1844  ///queries.
1845  ///
1846  ///\tparam GR The type of the underlying digraph.
1847  ///
1848  ///\sa ArcLookUp
1849  ///\sa AllArcLookUp
1850  template <typename GR>
1851  class DynArcLookUp
1852    : protected ItemSetTraits<GR, typename GR::Arc>::ItemNotifier::ObserverBase
1853  {
1854    typedef typename ItemSetTraits<GR, typename GR::Arc>
1855    ::ItemNotifier::ObserverBase Parent;
1856
1857    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1858
1859  public:
1860
1861    /// The Digraph type
1862    typedef GR Digraph;
1863
1864  protected:
1865
1866    class AutoNodeMap : public ItemSetTraits<GR, Node>::template Map<Arc>::Type
1867    {
1868      typedef typename ItemSetTraits<GR, Node>::template Map<Arc>::Type Parent;
1869
1870    public:
1871
1872      AutoNodeMap(const GR& digraph) : Parent(digraph, INVALID) {}
1873
1874      virtual void add(const Node& node) {
1875        Parent::add(node);
1876        Parent::set(node, INVALID);
1877      }
1878
1879      virtual void add(const std::vector<Node>& nodes) {
1880        Parent::add(nodes);
1881        for (int i = 0; i < int(nodes.size()); ++i) {
1882          Parent::set(nodes[i], INVALID);
1883        }
1884      }
1885
1886      virtual void build() {
1887        Parent::build();
1888        Node it;
1889        typename Parent::Notifier* nf = Parent::notifier();
1890        for (nf->first(it); it != INVALID; nf->next(it)) {
1891          Parent::set(it, INVALID);
1892        }
1893      }
1894    };
1895
1896    class ArcLess {
1897      const Digraph &g;
1898    public:
1899      ArcLess(const Digraph &_g) : g(_g) {}
1900      bool operator()(Arc a,Arc b) const
1901      {
1902        return g.target(a)<g.target(b);
1903      }
1904    };
1905
1906  protected:
1907
1908    const Digraph &_g;
1909    AutoNodeMap _head;
1910    typename Digraph::template ArcMap<Arc> _parent;
1911    typename Digraph::template ArcMap<Arc> _left;
1912    typename Digraph::template ArcMap<Arc> _right;
1913
1914  public:
1915
1916    ///Constructor
1917
1918    ///Constructor.
1919    ///
1920    ///It builds up the search database.
1921    DynArcLookUp(const Digraph &g)
1922      : _g(g),_head(g),_parent(g),_left(g),_right(g)
1923    {
1924      Parent::attach(_g.notifier(typename Digraph::Arc()));
1925      refresh();
1926    }
1927
1928  protected:
1929
1930    virtual void add(const Arc& arc) {
1931      insert(arc);
1932    }
1933
1934    virtual void add(const std::vector<Arc>& arcs) {
1935      for (int i = 0; i < int(arcs.size()); ++i) {
1936        insert(arcs[i]);
1937      }
1938    }
1939
1940    virtual void erase(const Arc& arc) {
1941      remove(arc);
1942    }
1943
1944    virtual void erase(const std::vector<Arc>& arcs) {
1945      for (int i = 0; i < int(arcs.size()); ++i) {
1946        remove(arcs[i]);
1947      }
1948    }
1949
1950    virtual void build() {
1951      refresh();
1952    }
1953
1954    virtual void clear() {
1955      for(NodeIt n(_g);n!=INVALID;++n) {
1956        _head[n] = INVALID;
1957      }
1958    }
1959
1960    void insert(Arc arc) {
1961      Node s = _g.source(arc);
1962      Node t = _g.target(arc);
1963      _left[arc] = INVALID;
1964      _right[arc] = INVALID;
1965
1966      Arc e = _head[s];
1967      if (e == INVALID) {
1968        _head[s] = arc;
1969        _parent[arc] = INVALID;
1970        return;
1971      }
1972      while (true) {
1973        if (t < _g.target(e)) {
1974          if (_left[e] == INVALID) {
1975            _left[e] = arc;
1976            _parent[arc] = e;
1977            splay(arc);
1978            return;
1979          } else {
1980            e = _left[e];
1981          }
1982        } else {
1983          if (_right[e] == INVALID) {
1984            _right[e] = arc;
1985            _parent[arc] = e;
1986            splay(arc);
1987            return;
1988          } else {
1989            e = _right[e];
1990          }
1991        }
1992      }
1993    }
1994
1995    void remove(Arc arc) {
1996      if (_left[arc] == INVALID) {
1997        if (_right[arc] != INVALID) {
1998          _parent[_right[arc]] = _parent[arc];
1999        }
2000        if (_parent[arc] != INVALID) {
2001          if (_left[_parent[arc]] == arc) {
2002            _left[_parent[arc]] = _right[arc];
2003          } else {
2004            _right[_parent[arc]] = _right[arc];
2005          }
2006        } else {
2007          _head[_g.source(arc)] = _right[arc];
2008        }
2009      } else if (_right[arc] == INVALID) {
2010        _parent[_left[arc]] = _parent[arc];
2011        if (_parent[arc] != INVALID) {
2012          if (_left[_parent[arc]] == arc) {
2013            _left[_parent[arc]] = _left[arc];
2014          } else {
2015            _right[_parent[arc]] = _left[arc];
2016          }
2017        } else {
2018          _head[_g.source(arc)] = _left[arc];
2019        }
2020      } else {
2021        Arc e = _left[arc];
2022        if (_right[e] != INVALID) {
2023          e = _right[e];
2024          while (_right[e] != INVALID) {
2025            e = _right[e];
2026          }
2027          Arc s = _parent[e];
2028          _right[_parent[e]] = _left[e];
2029          if (_left[e] != INVALID) {
2030            _parent[_left[e]] = _parent[e];
2031          }
2032
2033          _left[e] = _left[arc];
2034          _parent[_left[arc]] = e;
2035          _right[e] = _right[arc];
2036          _parent[_right[arc]] = e;
2037
2038          _parent[e] = _parent[arc];
2039          if (_parent[arc] != INVALID) {
2040            if (_left[_parent[arc]] == arc) {
2041              _left[_parent[arc]] = e;
2042            } else {
2043              _right[_parent[arc]] = e;
2044            }
2045          }
2046          splay(s);
2047        } else {
2048          _right[e] = _right[arc];
2049          _parent[_right[arc]] = e;
2050          _parent[e] = _parent[arc];
2051
2052          if (_parent[arc] != INVALID) {
2053            if (_left[_parent[arc]] == arc) {
2054              _left[_parent[arc]] = e;
2055            } else {
2056              _right[_parent[arc]] = e;
2057            }
2058          } else {
2059            _head[_g.source(arc)] = e;
2060          }
2061        }
2062      }
2063    }
2064
2065    Arc refreshRec(std::vector<Arc> &v,int a,int b)
2066    {
2067      int m=(a+b)/2;
2068      Arc me=v[m];
2069      if (a < m) {
2070        Arc left = refreshRec(v,a,m-1);
2071        _left[me] = left;
2072        _parent[left] = me;
2073      } else {
2074        _left[me] = INVALID;
2075      }
2076      if (m < b) {
2077        Arc right = refreshRec(v,m+1,b);
2078        _right[me] = right;
2079        _parent[right] = me;
2080      } else {
2081        _right[me] = INVALID;
2082      }
2083      return me;
2084    }
2085
2086    void refresh() {
2087      for(NodeIt n(_g);n!=INVALID;++n) {
2088        std::vector<Arc> v;
2089        for(OutArcIt a(_g,n);a!=INVALID;++a) v.push_back(a);
2090        if (!v.empty()) {
2091          std::sort(v.begin(),v.end(),ArcLess(_g));
2092          Arc head = refreshRec(v,0,v.size()-1);
2093          _head[n] = head;
2094          _parent[head] = INVALID;
2095        }
2096        else _head[n] = INVALID;
2097      }
2098    }
2099
2100    void zig(Arc v) {
2101      Arc w = _parent[v];
2102      _parent[v] = _parent[w];
2103      _parent[w] = v;
2104      _left[w] = _right[v];
2105      _right[v] = w;
2106      if (_parent[v] != INVALID) {
2107        if (_right[_parent[v]] == w) {
2108          _right[_parent[v]] = v;
2109        } else {
2110          _left[_parent[v]] = v;
2111        }
2112      }
2113      if (_left[w] != INVALID){
2114        _parent[_left[w]] = w;
2115      }
2116    }
2117
2118    void zag(Arc v) {
2119      Arc w = _parent[v];
2120      _parent[v] = _parent[w];
2121      _parent[w] = v;
2122      _right[w] = _left[v];
2123      _left[v] = w;
2124      if (_parent[v] != INVALID){
2125        if (_left[_parent[v]] == w) {
2126          _left[_parent[v]] = v;
2127        } else {
2128          _right[_parent[v]] = v;
2129        }
2130      }
2131      if (_right[w] != INVALID){
2132        _parent[_right[w]] = w;
2133      }
2134    }
2135
2136    void splay(Arc v) {
2137      while (_parent[v] != INVALID) {
2138        if (v == _left[_parent[v]]) {
2139          if (_parent[_parent[v]] == INVALID) {
2140            zig(v);
2141          } else {
2142            if (_parent[v] == _left[_parent[_parent[v]]]) {
2143              zig(_parent[v]);
2144              zig(v);
2145            } else {
2146              zig(v);
2147              zag(v);
2148            }
2149          }
2150        } else {
2151          if (_parent[_parent[v]] == INVALID) {
2152            zag(v);
2153          } else {
2154            if (_parent[v] == _left[_parent[_parent[v]]]) {
2155              zag(v);
2156              zig(v);
2157            } else {
2158              zag(_parent[v]);
2159              zag(v);
2160            }
2161          }
2162        }
2163      }
2164      _head[_g.source(v)] = v;
2165    }
2166
2167
2168  public:
2169
2170    ///Find an arc between two nodes.
2171
2172    ///Find an arc between two nodes.
2173    ///\param s The source node.
2174    ///\param t The target node.
2175    ///\param p The previous arc between \c s and \c t. It it is INVALID or
2176    ///not given, the operator finds the first appropriate arc.
2177    ///\return An arc from \c s to \c t after \c p or
2178    ///\ref INVALID if there is no more.
2179    ///
2180    ///For example, you can count the number of arcs from \c u to \c v in the
2181    ///following way.
2182    ///\code
2183    ///DynArcLookUp<ListDigraph> ae(g);
2184    ///...
2185    ///int n = 0;
2186    ///for(Arc a = ae(u,v); a != INVALID; a = ae(u,v,a)) n++;
2187    ///\endcode
2188    ///
2189    ///Finding the arcs take at most <em>O</em>(log<em>d</em>)
2190    ///amortized time, specifically, the time complexity of the lookups
2191    ///is equal to the optimal search tree implementation for the
2192    ///current query distribution in a constant factor.
2193    ///
2194    ///\note This is a dynamic data structure, therefore the data
2195    ///structure is updated after each graph alteration. Thus although
2196    ///this data structure is theoretically faster than \ref ArcLookUp
2197    ///and \ref AllArcLookUp, it often provides worse performance than
2198    ///them.
2199    Arc operator()(Node s, Node t, Arc p = INVALID) const  {
2200      if (p == INVALID) {
2201        Arc a = _head[s];
2202        if (a == INVALID) return INVALID;
2203        Arc r = INVALID;
2204        while (true) {
2205          if (_g.target(a) < t) {
2206            if (_right[a] == INVALID) {
2207              const_cast<DynArcLookUp&>(*this).splay(a);
2208              return r;
2209            } else {
2210              a = _right[a];
2211            }
2212          } else {
2213            if (_g.target(a) == t) {
2214              r = a;
2215            }
2216            if (_left[a] == INVALID) {
2217              const_cast<DynArcLookUp&>(*this).splay(a);
2218              return r;
2219            } else {
2220              a = _left[a];
2221            }
2222          }
2223        }
2224      } else {
2225        Arc a = p;
2226        if (_right[a] != INVALID) {
2227          a = _right[a];
2228          while (_left[a] != INVALID) {
2229            a = _left[a];
2230          }
2231          const_cast<DynArcLookUp&>(*this).splay(a);
2232        } else {
2233          while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
2234            a = _parent[a];
2235          }
2236          if (_parent[a] == INVALID) {
2237            return INVALID;
2238          } else {
2239            a = _parent[a];
2240            const_cast<DynArcLookUp&>(*this).splay(a);
2241          }
2242        }
2243        if (_g.target(a) == t) return a;
2244        else return INVALID;
2245      }
2246    }
2247
2248  };
2249
2250  ///Fast arc look-up between given endpoints.
2251
2252  ///Using this class, you can find an arc in a digraph from a given
2253  ///source to a given target in time <em>O</em>(log<em>d</em>),
2254  ///where <em>d</em> is the out-degree of the source node.
2255  ///
2256  ///It is not possible to find \e all parallel arcs between two nodes.
2257  ///Use \ref AllArcLookUp for this purpose.
2258  ///
2259  ///\warning This class is static, so you should call refresh() (or at
2260  ///least refresh(Node)) to refresh this data structure whenever the
2261  ///digraph changes. This is a time consuming (superlinearly proportional
2262  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
2263  ///
2264  ///\tparam GR The type of the underlying digraph.
2265  ///
2266  ///\sa DynArcLookUp
2267  ///\sa AllArcLookUp
2268  template<class GR>
2269  class ArcLookUp
2270  {
2271    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
2272
2273  public:
2274
2275    /// The Digraph type
2276    typedef GR Digraph;
2277
2278  protected:
2279    const Digraph &_g;
2280    typename Digraph::template NodeMap<Arc> _head;
2281    typename Digraph::template ArcMap<Arc> _left;
2282    typename Digraph::template ArcMap<Arc> _right;
2283
2284    class ArcLess {
2285      const Digraph &g;
2286    public:
2287      ArcLess(const Digraph &_g) : g(_g) {}
2288      bool operator()(Arc a,Arc b) const
2289      {
2290        return g.target(a)<g.target(b);
2291      }
2292    };
2293
2294  public:
2295
2296    ///Constructor
2297
2298    ///Constructor.
2299    ///
2300    ///It builds up the search database, which remains valid until the digraph
2301    ///changes.
2302    ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();}
2303
2304  private:
2305    Arc refreshRec(std::vector<Arc> &v,int a,int b)
2306    {
2307      int m=(a+b)/2;
2308      Arc me=v[m];
2309      _left[me] = a<m?refreshRec(v,a,m-1):INVALID;
2310      _right[me] = m<b?refreshRec(v,m+1,b):INVALID;
2311      return me;
2312    }
2313  public:
2314    ///Refresh the search data structure at a node.
2315
2316    ///Build up the search database of node \c n.
2317    ///
2318    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em>
2319    ///is the number of the outgoing arcs of \c n.
2320    void refresh(Node n)
2321    {
2322      std::vector<Arc> v;
2323      for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
2324      if(v.size()) {
2325        std::sort(v.begin(),v.end(),ArcLess(_g));
2326        _head[n]=refreshRec(v,0,v.size()-1);
2327      }
2328      else _head[n]=INVALID;
2329    }
2330    ///Refresh the full data structure.
2331
2332    ///Build up the full search database. In fact, it simply calls
2333    ///\ref refresh(Node) "refresh(n)" for each node \c n.
2334    ///
2335    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
2336    ///the number of the arcs in the digraph and <em>D</em> is the maximum
2337    ///out-degree of the digraph.
2338    void refresh()
2339    {
2340      for(NodeIt n(_g);n!=INVALID;++n) refresh(n);
2341    }
2342
2343    ///Find an arc between two nodes.
2344
2345    ///Find an arc between two nodes in time <em>O</em>(log<em>d</em>),
2346    ///where <em>d</em> is the number of outgoing arcs of \c s.
2347    ///\param s The source node.
2348    ///\param t The target node.
2349    ///\return An arc from \c s to \c t if there exists,
2350    ///\ref INVALID otherwise.
2351    ///
2352    ///\warning If you change the digraph, refresh() must be called before using
2353    ///this operator. If you change the outgoing arcs of
2354    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
2355    Arc operator()(Node s, Node t) const
2356    {
2357      Arc e;
2358      for(e=_head[s];
2359          e!=INVALID&&_g.target(e)!=t;
2360          e = t < _g.target(e)?_left[e]:_right[e]) ;
2361      return e;
2362    }
2363
2364  };
2365
2366  ///Fast look-up of all arcs between given endpoints.
2367
2368  ///This class is the same as \ref ArcLookUp, with the addition
2369  ///that it makes it possible to find all parallel arcs between given
2370  ///endpoints.
2371  ///
2372  ///\warning This class is static, so you should call refresh() (or at
2373  ///least refresh(Node)) to refresh this data structure whenever the
2374  ///digraph changes. This is a time consuming (superlinearly proportional
2375  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
2376  ///
2377  ///\tparam GR The type of the underlying digraph.
2378  ///
2379  ///\sa DynArcLookUp
2380  ///\sa ArcLookUp
2381  template<class GR>
2382  class AllArcLookUp : public ArcLookUp<GR>
2383  {
2384    using ArcLookUp<GR>::_g;
2385    using ArcLookUp<GR>::_right;
2386    using ArcLookUp<GR>::_left;
2387    using ArcLookUp<GR>::_head;
2388
2389    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
2390
2391    typename GR::template ArcMap<Arc> _next;
2392
2393    Arc refreshNext(Arc head,Arc next=INVALID)
2394    {
2395      if(head==INVALID) return next;
2396      else {
2397        next=refreshNext(_right[head],next);
2398        _next[head]=( next!=INVALID && _g.target(next)==_g.target(head))
2399          ? next : INVALID;
2400        return refreshNext(_left[head],head);
2401      }
2402    }
2403
2404    void refreshNext()
2405    {
2406      for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]);
2407    }
2408
2409  public:
2410
2411    /// The Digraph type
2412    typedef GR Digraph;
2413
2414    ///Constructor
2415
2416    ///Constructor.
2417    ///
2418    ///It builds up the search database, which remains valid until the digraph
2419    ///changes.
2420    AllArcLookUp(const Digraph &g) : ArcLookUp<GR>(g), _next(g) {refreshNext();}
2421
2422    ///Refresh the data structure at a node.
2423
2424    ///Build up the search database of node \c n.
2425    ///
2426    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em> is
2427    ///the number of the outgoing arcs of \c n.
2428    void refresh(Node n)
2429    {
2430      ArcLookUp<GR>::refresh(n);
2431      refreshNext(_head[n]);
2432    }
2433
2434    ///Refresh the full data structure.
2435
2436    ///Build up the full search database. In fact, it simply calls
2437    ///\ref refresh(Node) "refresh(n)" for each node \c n.
2438    ///
2439    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
2440    ///the number of the arcs in the digraph and <em>D</em> is the maximum
2441    ///out-degree of the digraph.
2442    void refresh()
2443    {
2444      for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]);
2445    }
2446
2447    ///Find an arc between two nodes.
2448
2449    ///Find an arc between two nodes.
2450    ///\param s The source node.
2451    ///\param t The target node.
2452    ///\param prev The previous arc between \c s and \c t. It it is INVALID or
2453    ///not given, the operator finds the first appropriate arc.
2454    ///\return An arc from \c s to \c t after \c prev or
2455    ///\ref INVALID if there is no more.
2456    ///
2457    ///For example, you can count the number of arcs from \c u to \c v in the
2458    ///following way.
2459    ///\code
2460    ///AllArcLookUp<ListDigraph> ae(g);
2461    ///...
2462    ///int n = 0;
2463    ///for(Arc a = ae(u,v); a != INVALID; a=ae(u,v,a)) n++;
2464    ///\endcode
2465    ///
2466    ///Finding the first arc take <em>O</em>(log<em>d</em>) time,
2467    ///where <em>d</em> is the number of outgoing arcs of \c s. Then the
2468    ///consecutive arcs are found in constant time.
2469    ///
2470    ///\warning If you change the digraph, refresh() must be called before using
2471    ///this operator. If you change the outgoing arcs of
2472    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
2473    ///
2474    Arc operator()(Node s, Node t, Arc prev=INVALID) const
2475    {
2476      if(prev==INVALID)
2477        {
2478          Arc f=INVALID;
2479          Arc e;
2480          for(e=_head[s];
2481              e!=INVALID&&_g.target(e)!=t;
2482              e = t < _g.target(e)?_left[e]:_right[e]) ;
2483          while(e!=INVALID)
2484            if(_g.target(e)==t)
2485              {
2486                f = e;
2487                e = _left[e];
2488              }
2489            else e = _right[e];
2490          return f;
2491        }
2492      else return _next[prev];
2493    }
2494
2495  };
2496
2497  /// @}
2498
2499} //namespace lemon
2500
2501#endif
Note: See TracBrowser for help on using the repository browser.