COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/core.h @ 260:c691064dfd4f

Last change on this file since 260:c691064dfd4f was 233:28239207a8a3, checked in by Balazs Dezso <deba@…>, 16 years ago

Unify DynArcLookUp? interface (ticket #127)

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