lemon/graph_utils.h
author deba
Mon, 12 Sep 2005 09:19:52 +0000
changeset 1680 4f8b9cee576b
parent 1674 648aa2f33dc8
child 1695 e6f99fe1723f
permissions -rw-r--r--
Fixing and improving GridGraph
     1 /* -*- C++ -*-
     2  * lemon/graph_utils.h - Part of LEMON, a generic C++ optimization library
     3  *
     4  * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     5  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     6  *
     7  * Permission to use, modify and distribute this software is granted
     8  * provided that this copyright notice appears in all copies. For
     9  * precise terms see the accompanying LICENSE file.
    10  *
    11  * This software is provided "AS IS" with no warranty of any kind,
    12  * express or implied, and with no claim as to its suitability for any
    13  * purpose.
    14  *
    15  */
    16 
    17 #ifndef LEMON_GRAPH_UTILS_H
    18 #define LEMON_GRAPH_UTILS_H
    19 
    20 #include <iterator>
    21 #include <vector>
    22 #include <map>
    23 
    24 #include <lemon/invalid.h>
    25 #include <lemon/utility.h>
    26 #include <lemon/maps.h>
    27 #include <lemon/bits/alteration_notifier.h>
    28 
    29 ///\ingroup gutils
    30 ///\file
    31 ///\brief Graph utilities.
    32 ///
    33 ///
    34 
    35 
    36 namespace lemon {
    37 
    38   /// \addtogroup gutils
    39   /// @{
    40 
    41   /// \brief Function to count the items in the graph.
    42   ///
    43   /// This function counts the items (nodes, edges etc) in the graph.
    44   /// The complexity of the function is O(n) because
    45   /// it iterates on all of the items.
    46 
    47   template <typename Graph, typename ItemIt>
    48   inline int countItems(const Graph& g) {
    49     int num = 0;
    50     for (ItemIt it(g); it != INVALID; ++it) {
    51       ++num;
    52     }
    53     return num;
    54   }
    55 
    56   // Node counting:
    57 
    58   template <typename Graph>
    59   inline
    60   typename enable_if<typename Graph::NodeNumTag, int>::type
    61   _countNodes(const Graph &g) {
    62     return g.nodeNum();
    63   }
    64 
    65   template <typename Graph>
    66   inline int _countNodes(Wrap<Graph> w) {
    67     return countItems<Graph, typename Graph::NodeIt>(w.value);
    68   }
    69 
    70   /// \brief Function to count the nodes in the graph.
    71   ///
    72   /// This function counts the nodes in the graph.
    73   /// The complexity of the function is O(n) but for some
    74   /// graph structures it is specialized to run in O(1).
    75   ///
    76   /// \todo refer how to specialize it
    77 
    78   template <typename Graph>
    79   inline int countNodes(const Graph& g) {
    80     return _countNodes<Graph>(g);
    81   }
    82 
    83   // Edge counting:
    84 
    85   template <typename Graph>
    86   inline
    87   typename enable_if<typename Graph::EdgeNumTag, int>::type
    88   _countEdges(const Graph &g) {
    89     return g.edgeNum();
    90   }
    91 
    92   template <typename Graph>
    93   inline int _countEdges(Wrap<Graph> w) {
    94     return countItems<Graph, typename Graph::EdgeIt>(w.value);
    95   }
    96 
    97   /// \brief Function to count the edges in the graph.
    98   ///
    99   /// This function counts the edges in the graph.
   100   /// The complexity of the function is O(e) but for some
   101   /// graph structures it is specialized to run in O(1).
   102 
   103   template <typename Graph>
   104   inline int countEdges(const Graph& g) {
   105     return _countEdges<Graph>(g);
   106   }
   107 
   108   // Undirected edge counting:
   109 
   110   template <typename Graph>
   111   inline
   112   typename enable_if<typename Graph::EdgeNumTag, int>::type
   113   _countUndirEdges(const Graph &g) {
   114     return g.undirEdgeNum();
   115   }
   116 
   117   template <typename Graph>
   118   inline int _countUndirEdges(Wrap<Graph> w) {
   119     return countItems<Graph, typename Graph::UndirEdgeIt>(w.value);
   120   }
   121 
   122   /// \brief Function to count the undirected edges in the graph.
   123   ///
   124   /// This function counts the undirected edges in the graph.
   125   /// The complexity of the function is O(e) but for some
   126   /// graph structures it is specialized to run in O(1).
   127 
   128   template <typename Graph>
   129   inline int countUndirEdges(const Graph& g) {
   130     return _countUndirEdges<Graph>(g);
   131   }
   132 
   133 
   134 
   135   template <typename Graph, typename DegIt>
   136   inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
   137     int num = 0;
   138     for (DegIt it(_g, _n); it != INVALID; ++it) {
   139       ++num;
   140     }
   141     return num;
   142   }
   143 
   144   /// \brief Function to count the number of the out-edges from node \c n.
   145   ///
   146   /// This function counts the number of the out-edges from node \c n
   147   /// in the graph.  
   148   template <typename Graph>
   149   inline int countOutEdges(const Graph& _g,  const typename Graph::Node& _n) {
   150     return countNodeDegree<Graph, typename Graph::OutEdgeIt>(_g, _n);
   151   }
   152 
   153   /// \brief Function to count the number of the in-edges to node \c n.
   154   ///
   155   /// This function counts the number of the in-edges to node \c n
   156   /// in the graph.  
   157   template <typename Graph>
   158   inline int countInEdges(const Graph& _g,  const typename Graph::Node& _n) {
   159     return countNodeDegree<Graph, typename Graph::InEdgeIt>(_g, _n);
   160   }
   161 
   162   /// \brief Function to count the number of the in-edges to node \c n.
   163   ///
   164   /// This function counts the number of the in-edges to node \c n
   165   /// in the graph.  
   166   template <typename Graph>
   167   inline int countIncEdges(const Graph& _g,  const typename Graph::Node& _n) {
   168     return countNodeDegree<Graph, typename Graph::IncEdgeIt>(_g, _n);
   169   }
   170 
   171 
   172   template <typename Graph>
   173   inline
   174   typename enable_if<typename Graph::FindEdgeTag, typename Graph::Edge>::type 
   175   _findEdge(const Graph &g,
   176 	    typename Graph::Node u, typename Graph::Node v,
   177 	    typename Graph::Edge prev = INVALID) {
   178     return g.findEdge(u, v, prev);
   179   }
   180 
   181   template <typename Graph>
   182   inline typename Graph::Edge 
   183   _findEdge(Wrap<Graph> w,
   184 	    typename Graph::Node u, 
   185 	    typename Graph::Node v,
   186 	    typename Graph::Edge prev = INVALID) {
   187     const Graph& g = w.value;
   188     if (prev == INVALID) {
   189       typename Graph::OutEdgeIt e(g, u);
   190       while (e != INVALID && g.target(e) != v) ++e;
   191       return e;
   192     } else {
   193       typename Graph::OutEdgeIt e(g, prev); ++e;
   194       while (e != INVALID && g.target(e) != v) ++e;
   195       return e;
   196     }
   197   }
   198 
   199   /// \brief Finds an edge between two nodes of a graph.
   200   ///
   201   /// Finds an edge from node \c u to node \c v in graph \c g.
   202   ///
   203   /// If \c prev is \ref INVALID (this is the default value), then
   204   /// it finds the first edge from \c u to \c v. Otherwise it looks for
   205   /// the next edge from \c u to \c v after \c prev.
   206   /// \return The found edge or \ref INVALID if there is no such an edge.
   207   ///
   208   /// Thus you can iterate through each edge from \c u to \c v as it follows.
   209   /// \code
   210   /// for(Edge e=findEdge(g,u,v);e!=INVALID;e=findEdge(g,u,v,e)) {
   211   ///   ...
   212   /// }
   213   /// \endcode
   214   // /// \todo We may want to use the "GraphBase" 
   215   // /// interface here...
   216   // /// It would not work with the undirected graphs.
   217   template <typename Graph>
   218   inline typename Graph::Edge findEdge(const Graph &g,
   219 				       typename Graph::Node u, 
   220 				       typename Graph::Node v,
   221 				       typename Graph::Edge prev = INVALID) {
   222     return _findEdge<Graph>(g, u, v, prev);
   223   }
   224 
   225   /// \brief Iterator for iterating on edges connected the same nodes.
   226   ///
   227   /// Iterator for iterating on edges connected the same nodes. It is 
   228   /// higher level interface for the findEdge() function. You can
   229   /// use it the following way:
   230   /// \code
   231   /// for (ConEdgeIt<Graph> it(g, src, trg); it != INVALID; ++it) {
   232   ///   ...
   233   /// }
   234   /// \endcode
   235   ///
   236   /// \author Balazs Dezso 
   237   template <typename _Graph>
   238   class ConEdgeIt : public _Graph::Edge {
   239   public:
   240 
   241     typedef _Graph Graph;
   242     typedef typename Graph::Edge Parent;
   243 
   244     typedef typename Graph::Edge Edge;
   245     typedef typename Graph::Node Node;
   246 
   247     /// \brief Constructor.
   248     ///
   249     /// Construct a new ConEdgeIt iterating on the edges which
   250     /// connects the \c u and \c v node.
   251     ConEdgeIt(const Graph& g, Node u, Node v) : graph(g) {
   252       Parent::operator=(findEdge(graph, u, v));
   253     }
   254 
   255     /// \brief Constructor.
   256     ///
   257     /// Construct a new ConEdgeIt which continues the iterating from 
   258     /// the \c e edge.
   259     ConEdgeIt(const Graph& g, Edge e) : Parent(e), graph(g) {}
   260     
   261     /// \brief Increment operator.
   262     ///
   263     /// It increments the iterator and gives back the next edge.
   264     ConEdgeIt& operator++() {
   265       Parent::operator=(findEdge(graph, graph.source(*this), 
   266 				 graph.target(*this), *this));
   267       return *this;
   268     }
   269   private:
   270     const Graph& graph;
   271   };
   272 
   273   /// \brief Copy a map.
   274   ///
   275   /// This function copies the \c source map to the \c target map. It uses the
   276   /// given iterator to iterate on the data structure and it uses the \c ref
   277   /// mapping to convert the source's keys to the target's keys.
   278   template <typename Target, typename Source, 
   279 	    typename ItemIt, typename Ref>	    
   280   void copyMap(Target& target, const Source& source, 
   281 	       ItemIt it, const Ref& ref) {
   282     for (; it != INVALID; ++it) {
   283       target[ref[it]] = source[it];
   284     }
   285   }
   286 
   287   /// \brief Copy the source map to the target map.
   288   ///
   289   /// Copy the \c source map to the \c target map. It uses the given iterator
   290   /// to iterate on the data structure.
   291   template <typename Target, typename Source, 
   292 	    typename ItemIt>	    
   293   void copyMap(Target& target, const Source& source, ItemIt it) {
   294     for (; it != INVALID; ++it) {
   295       target[it] = source[it];
   296     }
   297   }
   298 
   299 
   300   /// \brief Class to copy a graph.
   301   ///
   302   /// Class to copy a graph to an other graph (duplicate a graph). The
   303   /// simplest way of using it is through the \c copyGraph() function.
   304   template <typename Target, typename Source>
   305   class GraphCopy {
   306   public: 
   307     typedef typename Source::Node Node;
   308     typedef typename Source::NodeIt NodeIt;
   309     typedef typename Source::Edge Edge;
   310     typedef typename Source::EdgeIt EdgeIt;
   311 
   312     typedef typename Source::template NodeMap<typename Target::Node>NodeRefMap;
   313     typedef typename Source::template EdgeMap<typename Target::Edge>EdgeRefMap;
   314 
   315     /// \brief Constructor for the GraphCopy.
   316     ///
   317     /// It copies the content of the \c _source graph into the
   318     /// \c _target graph. It creates also two references, one beetween
   319     /// the two nodeset and one beetween the two edgesets.
   320     GraphCopy(Target& _target, const Source& _source) 
   321       : source(_source), target(_target), 
   322 	nodeRefMap(_source), edgeRefMap(_source) {
   323       for (NodeIt it(source); it != INVALID; ++it) {
   324 	nodeRefMap[it] = target.addNode();
   325       }
   326       for (EdgeIt it(source); it != INVALID; ++it) {
   327 	edgeRefMap[it] = target.addEdge(nodeRefMap[source.source(it)], 
   328 					nodeRefMap[source.target(it)]);
   329       }
   330     }
   331 
   332     /// \brief Copies the node references into the given map.
   333     ///
   334     /// Copies the node references into the given map.
   335     template <typename NodeRef>
   336     const GraphCopy& nodeRef(NodeRef& map) const {
   337       for (NodeIt it(source); it != INVALID; ++it) {
   338 	map.set(it, nodeRefMap[it]);
   339       }
   340       return *this;
   341     }
   342 
   343     /// \brief Reverse and copies the node references into the given map.
   344     ///
   345     /// Reverse and copies the node references into the given map.
   346     template <typename NodeRef>
   347     const GraphCopy& nodeCrossRef(NodeRef& map) const {
   348       for (NodeIt it(source); it != INVALID; ++it) {
   349 	map.set(nodeRefMap[it], it);
   350       }
   351       return *this;
   352     }
   353 
   354     /// \brief Copies the edge references into the given map.
   355     ///
   356     /// Copies the edge references into the given map.
   357     template <typename EdgeRef>
   358     const GraphCopy& edgeRef(EdgeRef& map) const {
   359       for (EdgeIt it(source); it != INVALID; ++it) {
   360 	map.set(it, edgeRefMap[it]);
   361       }
   362       return *this;
   363     }
   364 
   365     /// \brief Reverse and copies the edge references into the given map.
   366     ///
   367     /// Reverse and copies the edge references into the given map.
   368     template <typename EdgeRef>
   369     const GraphCopy& edgeCrossRef(EdgeRef& map) const {
   370       for (EdgeIt it(source); it != INVALID; ++it) {
   371 	map.set(edgeRefMap[it], it);
   372       }
   373       return *this;
   374     }
   375 
   376     /// \brief Make copy of the given map.
   377     ///
   378     /// Makes copy of the given map for the newly created graph. 
   379     /// The new map's key type is the target graph's node type,
   380     /// and the copied map's key type is the source graph's node
   381     /// type.  
   382     template <typename TargetMap, typename SourceMap>
   383     const GraphCopy& nodeMap(TargetMap& tMap, const SourceMap& sMap) const {
   384       copyMap(tMap, sMap, NodeIt(source), nodeRefMap);
   385       return *this;
   386     }
   387 
   388     /// \brief Make copy of the given map.
   389     ///
   390     /// Makes copy of the given map for the newly created graph. 
   391     /// The new map's key type is the target graph's edge type,
   392     /// and the copied map's key type is the source graph's edge
   393     /// type.  
   394     template <typename TargetMap, typename SourceMap>
   395     const GraphCopy& edgeMap(TargetMap& tMap, const SourceMap& sMap) const {
   396       copyMap(tMap, sMap, EdgeIt(source), edgeRefMap);
   397       return *this;
   398     }
   399 
   400     /// \brief Gives back the stored node references.
   401     ///
   402     /// Gives back the stored node references.
   403     const NodeRefMap& nodeRef() const {
   404       return nodeRefMap;
   405     }
   406 
   407     /// \brief Gives back the stored edge references.
   408     ///
   409     /// Gives back the stored edge references.
   410     const EdgeRefMap& edgeRef() const {
   411       return edgeRefMap;
   412     }
   413 
   414   private:
   415     
   416     const Source& source;
   417     Target& target;
   418 
   419     NodeRefMap nodeRefMap;
   420     EdgeRefMap edgeRefMap;
   421   };
   422 
   423   /// \brief Copy a graph to an other graph.
   424   ///
   425   /// Copy a graph to an other graph.
   426   /// The usage of the function:
   427   /// 
   428   /// \code
   429   /// copyGraph(trg, src).nodeRef(nr).edgeCrossRef(ecr);
   430   /// \endcode
   431   /// 
   432   /// After the copy the \c nr map will contain the mapping from the
   433   /// source graph's nodes to the target graph's nodes and the \c ecr will
   434   /// contain the mapping from the target graph's edges to the source's
   435   /// edges.
   436   template <typename Target, typename Source>
   437   GraphCopy<Target, Source> copyGraph(Target& target, const Source& source) {
   438     return GraphCopy<Target, Source>(target, source);
   439   }
   440 
   441   template <typename _Graph, typename _Item>
   442   class ItemSetTraits {};
   443   
   444   template <typename _Graph>
   445   class ItemSetTraits<_Graph, typename _Graph::Node> {
   446   public:
   447     
   448     typedef _Graph Graph;
   449 
   450     typedef typename Graph::Node Item;
   451     typedef typename Graph::NodeIt ItemIt;
   452 
   453     template <typename _Value>
   454     class Map : public Graph::template NodeMap<_Value> {
   455     public:
   456       typedef typename Graph::template NodeMap<_Value> Parent; 
   457       typedef typename Parent::Value Value;
   458 
   459       Map(const Graph& _graph) : Parent(_graph) {}
   460       Map(const Graph& _graph, const Value& _value) 
   461 	: Parent(_graph, _value) {}
   462     };
   463 
   464   };
   465 
   466   template <typename _Graph>
   467   class ItemSetTraits<_Graph, typename _Graph::Edge> {
   468   public:
   469     
   470     typedef _Graph Graph;
   471 
   472     typedef typename Graph::Edge Item;
   473     typedef typename Graph::EdgeIt ItemIt;
   474 
   475     template <typename _Value>
   476     class Map : public Graph::template EdgeMap<_Value> {
   477     public:
   478       typedef typename Graph::template EdgeMap<_Value> Parent; 
   479       typedef typename Parent::Value Value;
   480 
   481       Map(const Graph& _graph) : Parent(_graph) {}
   482       Map(const Graph& _graph, const Value& _value) 
   483 	: Parent(_graph, _value) {}
   484     };
   485 
   486   };
   487 
   488   template <typename _Graph>
   489   class ItemSetTraits<_Graph, typename _Graph::UndirEdge> {
   490   public:
   491     
   492     typedef _Graph Graph;
   493 
   494     typedef typename Graph::UndirEdge Item;
   495     typedef typename Graph::UndirEdgeIt ItemIt;
   496 
   497     template <typename _Value>
   498     class Map : public Graph::template UndirEdgeMap<_Value> {
   499     public:
   500       typedef typename Graph::template UndirEdgeMap<_Value> Parent; 
   501       typedef typename Parent::Value Value;
   502 
   503       Map(const Graph& _graph) : Parent(_graph) {}
   504       Map(const Graph& _graph, const Value& _value) 
   505 	: Parent(_graph, _value) {}
   506     };
   507 
   508   };
   509 
   510   /// @}
   511 
   512   /// \addtogroup graph_maps
   513   /// @{
   514 
   515   template <typename Map, typename Enable = void>
   516   struct ReferenceMapTraits {
   517     typedef typename Map::Value Value;
   518     typedef typename Map::Value& Reference;
   519     typedef const typename Map::Value& ConstReference;
   520     typedef typename Map::Value* Pointer;
   521     typedef const typename Map::Value* ConstPointer;
   522   };
   523 
   524   template <typename Map>
   525   struct ReferenceMapTraits<
   526     Map, 
   527     typename enable_if<typename Map::FullTypeTag, void>::type
   528   > {
   529     typedef typename Map::Value Value;
   530     typedef typename Map::Reference Reference;
   531     typedef typename Map::ConstReference ConstReference;
   532     typedef typename Map::Pointer Pointer;
   533     typedef typename Map::ConstPointer ConstPointer;
   534   };
   535 
   536   /// Provides an immutable and unique id for each item in the graph.
   537 
   538   /// The IdMap class provides a unique and immutable id for each item of the
   539   /// same type (e.g. node) in the graph. This id is <ul><li>\b unique:
   540   /// different items (nodes) get different ids <li>\b immutable: the id of an
   541   /// item (node) does not change (even if you delete other nodes).  </ul>
   542   /// Through this map you get access (i.e. can read) the inner id values of
   543   /// the items stored in the graph. This map can be inverted with its member
   544   /// class \c InverseMap.
   545   ///
   546   template <typename _Graph, typename _Item>
   547   class IdMap {
   548   public:
   549     typedef _Graph Graph;
   550     typedef int Value;
   551     typedef _Item Item;
   552     typedef _Item Key;
   553 
   554     typedef True NeedCopy;
   555 
   556     /// \brief Constructor.
   557     ///
   558     /// Constructor for creating id map.
   559     IdMap(const Graph& _graph) : graph(&_graph) {}
   560 
   561     /// \brief Gives back the \e id of the item.
   562     ///
   563     /// Gives back the immutable and unique \e id of the map.
   564     int operator[](const Item& item) const { return graph->id(item);}
   565 
   566 
   567   private:
   568     const Graph* graph;
   569 
   570   public:
   571 
   572     /// \brief The class represents the inverse of its owner (IdMap).
   573     ///
   574     /// The class represents the inverse of its owner (IdMap).
   575     /// \see inverse()
   576     class InverseMap {
   577     public:
   578 
   579       typedef True NeedCopy;
   580 
   581       /// \brief Constructor.
   582       ///
   583       /// Constructor for creating an id-to-item map.
   584       InverseMap(const Graph& _graph) : graph(&_graph) {}
   585 
   586       /// \brief Constructor.
   587       ///
   588       /// Constructor for creating an id-to-item map.
   589       InverseMap(const IdMap& idMap) : graph(idMap.graph) {}
   590 
   591       /// \brief Gives back the given item from its id.
   592       ///
   593       /// Gives back the given item from its id.
   594       /// 
   595       Item operator[](int id) const { return graph->fromId(id, Item());}
   596     private:
   597       const Graph* graph;
   598     };
   599 
   600     /// \brief Gives back the inverse of the map.
   601     ///
   602     /// Gives back the inverse of the IdMap.
   603     InverseMap inverse() const { return InverseMap(*graph);} 
   604 
   605   };
   606 
   607   
   608   /// \brief General invertable graph-map type.
   609 
   610   /// This type provides simple invertable graph-maps. 
   611   /// The InvertableMap wraps an arbitrary ReadWriteMap 
   612   /// and if a key is set to a new value then store it
   613   /// in the inverse map.
   614   /// \param _Graph The graph type.
   615   /// \param _Map The map to extend with invertable functionality. 
   616   template <
   617     typename _Graph,
   618     typename _Item, 
   619     typename _Value,
   620     typename _Map 
   621     = typename ItemSetTraits<_Graph, _Item>::template Map<_Value>::Parent 
   622   >
   623   class InvertableMap : protected _Map {
   624 
   625   public:
   626  
   627     typedef _Map Map;
   628     typedef _Graph Graph;
   629 
   630     /// The key type of InvertableMap (Node, Edge, UndirEdge).
   631     typedef typename _Map::Key Key;
   632     /// The value type of the InvertableMap.
   633     typedef typename _Map::Value Value;
   634 
   635     /// \brief Constructor.
   636     ///
   637     /// Construct a new InvertableMap for the graph.
   638     ///
   639     InvertableMap(const Graph& graph) : Map(graph) {} 
   640     
   641     /// \brief The setter function of the map.
   642     ///
   643     /// Sets the mapped value.
   644     void set(const Key& key, const Value& val) {
   645       Value oldval = Map::operator[](key);
   646       typename Container::iterator it = invMap.find(oldval);
   647       if (it != invMap.end() && it->second == key) {
   648 	invMap.erase(it);
   649       }      
   650       invMap.insert(make_pair(val, key));
   651       Map::set(key, val);
   652     }
   653 
   654     /// \brief The getter function of the map.
   655     ///
   656     /// It gives back the value associated with the key.
   657     const Value operator[](const Key& key) const {
   658       return Map::operator[](key);
   659     }
   660 
   661   protected:
   662 
   663     /// \brief Add a new key to the map.
   664     ///
   665     /// Add a new key to the map. It is called by the
   666     /// \c AlterationNotifier.
   667     virtual void add(const Key& key) {
   668       Map::add(key);
   669     }
   670 
   671     /// \brief Erase the key from the map.
   672     ///
   673     /// Erase the key to the map. It is called by the
   674     /// \c AlterationNotifier.
   675     virtual void erase(const Key& key) {
   676       Value val = Map::operator[](key);
   677       typename Container::iterator it = invMap.find(val);
   678       if (it != invMap.end() && it->second == key) {
   679 	invMap.erase(it);
   680       }
   681       Map::erase(key);
   682     }
   683 
   684     /// \brief Clear the keys from the map and inverse map.
   685     ///
   686     /// Clear the keys from the map and inverse map. It is called by the
   687     /// \c AlterationNotifier.
   688     virtual void clear() {
   689       invMap.clear();
   690       Map::clear();
   691     }
   692 
   693   private:
   694     
   695     typedef std::map<Value, Key> Container;
   696     Container invMap;    
   697 
   698   public:
   699 
   700     /// \brief The inverse map type.
   701     ///
   702     /// The inverse of this map. The subscript operator of the map
   703     /// gives back always the item what was last assigned to the value. 
   704     class InverseMap {
   705     public:
   706       /// \brief Constructor of the InverseMap.
   707       ///
   708       /// Constructor of the InverseMap.
   709       InverseMap(const InvertableMap& _inverted) : inverted(_inverted) {}
   710 
   711       /// The value type of the InverseMap.
   712       typedef typename InvertableMap::Key Value;
   713       /// The key type of the InverseMap.
   714       typedef typename InvertableMap::Value Key; 
   715 
   716       /// \brief Subscript operator. 
   717       ///
   718       /// Subscript operator. It gives back always the item 
   719       /// what was last assigned to the value.
   720       Value operator[](const Key& key) const {
   721 	typename Container::const_iterator it = inverted.invMap.find(key);
   722 	return it->second;
   723       }
   724       
   725     private:
   726       const InvertableMap& inverted;
   727     };
   728 
   729     /// \brief It gives back the just readeable inverse map.
   730     ///
   731     /// It gives back the just readeable inverse map.
   732     InverseMap inverse() const {
   733       return InverseMap(*this);
   734     } 
   735 
   736 
   737     
   738   };
   739 
   740   /// \brief Provides a mutable, continuous and unique descriptor for each 
   741   /// item in the graph.
   742   ///
   743   /// The DescriptorMap class provides a unique and continuous (but mutable)
   744   /// descriptor (id) for each item of the same type (e.g. node) in the
   745   /// graph. This id is <ul><li>\b unique: different items (nodes) get
   746   /// different ids <li>\b continuous: the range of the ids is the set of
   747   /// integers between 0 and \c n-1, where \c n is the number of the items of
   748   /// this type (e.g. nodes) (so the id of a node can change if you delete an
   749   /// other node, i.e. this id is mutable).  </ul> This map can be inverted
   750   /// with its member class \c InverseMap.
   751   ///
   752   /// \param _Graph The graph class the \c DescriptorMap belongs to.
   753   /// \param _Item The Item is the Key of the Map. It may be Node, Edge or 
   754   /// UndirEdge.
   755   /// \param _Map A ReadWriteMap mapping from the item type to integer.
   756   template <
   757     typename _Graph,   
   758     typename _Item,
   759     typename _Map 
   760     = typename ItemSetTraits<_Graph, _Item>::template Map<int>::Parent
   761   >
   762   class DescriptorMap : protected _Map {
   763 
   764     typedef _Item Item;
   765     typedef _Map Map;
   766 
   767   public:
   768     /// The graph class of DescriptorMap.
   769     typedef _Graph Graph;
   770 
   771     /// The key type of DescriptorMap (Node, Edge, UndirEdge).
   772     typedef typename _Map::Key Key;
   773     /// The value type of DescriptorMap.
   774     typedef typename _Map::Value Value;
   775 
   776     /// \brief Constructor.
   777     ///
   778     /// Constructor for descriptor map.
   779     DescriptorMap(const Graph& _graph) : Map(_graph) {
   780       build();
   781     }
   782 
   783   protected:
   784 
   785     /// \brief Add a new key to the map.
   786     ///
   787     /// Add a new key to the map. It is called by the
   788     /// \c AlterationNotifier.
   789     virtual void add(const Item& item) {
   790       Map::add(item);
   791       Map::set(item, invMap.size());
   792       invMap.push_back(item);
   793     }
   794 
   795     /// \brief Erase the key from the map.
   796     ///
   797     /// Erase the key to the map. It is called by the
   798     /// \c AlterationNotifier.
   799     virtual void erase(const Item& item) {
   800       Map::set(invMap.back(), Map::operator[](item));
   801       invMap[Map::operator[](item)] = invMap.back();
   802       invMap.pop_back();
   803       Map::erase(item);
   804     }
   805 
   806     /// \brief Build the unique map.
   807     ///
   808     /// Build the unique map. It is called by the
   809     /// \c AlterationNotifier.
   810     virtual void build() {
   811       Map::build();
   812       Item it;
   813       const typename Map::Graph* graph = Map::getGraph(); 
   814       for (graph->first(it); it != INVALID; graph->next(it)) {
   815 	Map::set(it, invMap.size());
   816 	invMap.push_back(it);	
   817       }      
   818     }
   819     
   820     /// \brief Clear the keys from the map.
   821     ///
   822     /// Clear the keys from the map. It is called by the
   823     /// \c AlterationNotifier.
   824     virtual void clear() {
   825       invMap.clear();
   826       Map::clear();
   827     }
   828 
   829   public:
   830 
   831     /// \brief Swaps the position of the two items in the map.
   832     ///
   833     /// Swaps the position of the two items in the map.
   834     void swap(const Item& p, const Item& q) {
   835       int pi = Map::operator[](p);
   836       int qi = Map::operator[](q);
   837       Map::set(p, qi);
   838       invMap[qi] = p;
   839       Map::set(q, pi);
   840       invMap[pi] = q;
   841     }
   842 
   843     /// \brief Gives back the \e descriptor of the item.
   844     ///
   845     /// Gives back the mutable and unique \e descriptor of the map.
   846     int operator[](const Item& item) const {
   847       return Map::operator[](item);
   848     }
   849     
   850   private:
   851 
   852     typedef std::vector<Item> Container;
   853     Container invMap;
   854 
   855   public:
   856     /// \brief The inverse map type of DescriptorMap.
   857     ///
   858     /// The inverse map type of DescriptorMap.
   859     class InverseMap {
   860     public:
   861       /// \brief Constructor of the InverseMap.
   862       ///
   863       /// Constructor of the InverseMap.
   864       InverseMap(const DescriptorMap& _inverted) 
   865 	: inverted(_inverted) {}
   866 
   867 
   868       /// The value type of the InverseMap.
   869       typedef typename DescriptorMap::Key Value;
   870       /// The key type of the InverseMap.
   871       typedef typename DescriptorMap::Value Key; 
   872 
   873       /// \brief Subscript operator. 
   874       ///
   875       /// Subscript operator. It gives back the item 
   876       /// that the descriptor belongs to currently.
   877       Value operator[](const Key& key) const {
   878 	return inverted.invMap[key];
   879       }
   880 
   881       /// \brief Size of the map.
   882       ///
   883       /// Returns the size of the map.
   884       int size() const {
   885 	return inverted.invMap.size();
   886       }
   887       
   888     private:
   889       const DescriptorMap& inverted;
   890     };
   891 
   892     /// \brief Gives back the inverse of the map.
   893     ///
   894     /// Gives back the inverse of the map.
   895     const InverseMap inverse() const {
   896       return InverseMap(*this);
   897     }
   898   };
   899 
   900   /// \brief Returns the source of the given edge.
   901   ///
   902   /// The SourceMap gives back the source Node of the given edge. 
   903   /// \author Balazs Dezso
   904   template <typename Graph>
   905   class SourceMap {
   906   public:
   907 
   908     typedef True NeedCopy;
   909 
   910     typedef typename Graph::Node Value;
   911     typedef typename Graph::Edge Key;
   912 
   913     /// \brief Constructor
   914     ///
   915     /// Constructor
   916     /// \param _graph The graph that the map belongs to.
   917     SourceMap(const Graph& _graph) : graph(_graph) {}
   918 
   919     /// \brief The subscript operator.
   920     ///
   921     /// The subscript operator.
   922     /// \param edge The edge 
   923     /// \return The source of the edge 
   924     Value operator[](const Key& edge) const {
   925       return graph.source(edge);
   926     }
   927 
   928   private:
   929     const Graph& graph;
   930   };
   931 
   932   /// \brief Returns a \ref SourceMap class
   933   ///
   934   /// This function just returns an \ref SourceMap class.
   935   /// \relates SourceMap
   936   template <typename Graph>
   937   inline SourceMap<Graph> sourceMap(const Graph& graph) {
   938     return SourceMap<Graph>(graph);
   939   } 
   940 
   941   /// \brief Returns the target of the given edge.
   942   ///
   943   /// The TargetMap gives back the target Node of the given edge. 
   944   /// \author Balazs Dezso
   945   template <typename Graph>
   946   class TargetMap {
   947   public:
   948 
   949     typedef True NeedCopy;
   950 
   951     typedef typename Graph::Node Value;
   952     typedef typename Graph::Edge Key;
   953 
   954     /// \brief Constructor
   955     ///
   956     /// Constructor
   957     /// \param _graph The graph that the map belongs to.
   958     TargetMap(const Graph& _graph) : graph(_graph) {}
   959 
   960     /// \brief The subscript operator.
   961     ///
   962     /// The subscript operator.
   963     /// \param e The edge 
   964     /// \return The target of the edge 
   965     Value operator[](const Key& e) const {
   966       return graph.target(e);
   967     }
   968 
   969   private:
   970     const Graph& graph;
   971   };
   972 
   973   /// \brief Returns a \ref TargetMap class
   974   ///
   975   /// This function just returns a \ref TargetMap class.
   976   /// \relates TargetMap
   977   template <typename Graph>
   978   inline TargetMap<Graph> targetMap(const Graph& graph) {
   979     return TargetMap<Graph>(graph);
   980   }
   981 
   982   /// \brief Returns the "forward" directed edge view of an undirected edge.
   983   ///
   984   /// Returns the "forward" directed edge view of an undirected edge.
   985   /// \author Balazs Dezso
   986   template <typename Graph>
   987   class ForwardMap {
   988   public:
   989 
   990     typedef True NeedCopy;
   991 
   992     typedef typename Graph::Edge Value;
   993     typedef typename Graph::UndirEdge Key;
   994 
   995     /// \brief Constructor
   996     ///
   997     /// Constructor
   998     /// \param _graph The graph that the map belongs to.
   999     ForwardMap(const Graph& _graph) : graph(_graph) {}
  1000 
  1001     /// \brief The subscript operator.
  1002     ///
  1003     /// The subscript operator.
  1004     /// \param key An undirected edge 
  1005     /// \return The "forward" directed edge view of undirected edge 
  1006     Value operator[](const Key& key) const {
  1007       return graph.direct(key, true);
  1008     }
  1009 
  1010   private:
  1011     const Graph& graph;
  1012   };
  1013 
  1014   /// \brief Returns a \ref ForwardMap class
  1015   ///
  1016   /// This function just returns an \ref ForwardMap class.
  1017   /// \relates ForwardMap
  1018   template <typename Graph>
  1019   inline ForwardMap<Graph> forwardMap(const Graph& graph) {
  1020     return ForwardMap<Graph>(graph);
  1021   }
  1022 
  1023   /// \brief Returns the "backward" directed edge view of an undirected edge.
  1024   ///
  1025   /// Returns the "backward" directed edge view of an undirected edge.
  1026   /// \author Balazs Dezso
  1027   template <typename Graph>
  1028   class BackwardMap {
  1029   public:
  1030     typedef True NeedCopy;
  1031 
  1032     typedef typename Graph::Edge Value;
  1033     typedef typename Graph::UndirEdge Key;
  1034 
  1035     /// \brief Constructor
  1036     ///
  1037     /// Constructor
  1038     /// \param _graph The graph that the map belongs to.
  1039     BackwardMap(const Graph& _graph) : graph(_graph) {}
  1040 
  1041     /// \brief The subscript operator.
  1042     ///
  1043     /// The subscript operator.
  1044     /// \param key An undirected edge 
  1045     /// \return The "backward" directed edge view of undirected edge 
  1046     Value operator[](const Key& key) const {
  1047       return graph.direct(key, false);
  1048     }
  1049 
  1050   private:
  1051     const Graph& graph;
  1052   };
  1053 
  1054   /// \brief Returns a \ref BackwardMap class
  1055 
  1056   /// This function just returns a \ref BackwardMap class.
  1057   /// \relates BackwardMap
  1058   template <typename Graph>
  1059   inline BackwardMap<Graph> backwardMap(const Graph& graph) {
  1060     return BackwardMap<Graph>(graph);
  1061   }
  1062 
  1063   template <typename _Graph>
  1064   class DegMapBase {
  1065   public:
  1066     
  1067     typedef _Graph Graph;
  1068 
  1069   protected:
  1070 
  1071     typedef typename Graph::template NodeMap<int> IntNodeMap;
  1072     
  1073   };
  1074 
  1075   /// \brief Map of the node in-degrees.
  1076   ///
  1077   /// This map returns the in-degree of a node. Once it is constructed,
  1078   /// the degrees are stored in a standard NodeMap, so each query is done
  1079   /// in constant time. On the other hand, the values are updated automatically
  1080   /// whenever the graph changes.
  1081   ///
  1082   /// \warning Besides addNode() and addEdge(), a graph structure may provide
  1083   /// alternative ways to mogify the graph. The correct behavior of InDegMap
  1084   /// is not guarantied if these additional featureas are used. For example
  1085   /// the funstions \ref ListGraph::changeSource() "changeSource()",
  1086   /// \ref ListGraph::changeTarget() "changeTarget()" and
  1087   /// \ref ListGraph::reverseEdge() "reverseEdge()"
  1088   /// of \ref ListGraph will \e not update the degree values correctly.
  1089   ///
  1090   /// \sa OutDegMap
  1091 
  1092   template <typename _Graph>
  1093   class InDegMap  
  1094     : protected AlterationNotifier<typename _Graph::Edge>::ObserverBase {
  1095 
  1096   public:
  1097     
  1098     typedef _Graph Graph;
  1099     typedef int Value;
  1100     typedef typename Graph::Node Key;
  1101 
  1102   private:
  1103 
  1104     class AutoNodeMap : public Graph::template NodeMap<int> {
  1105     public:
  1106 
  1107       typedef typename Graph::template NodeMap<int> Parent;
  1108 
  1109       typedef typename Parent::Key Key;
  1110       typedef typename Parent::Value Value;
  1111       
  1112       AutoNodeMap(const Graph& graph) : Parent(graph, 0) {}
  1113       
  1114       void add(const Key& key) {
  1115 	Parent::add(key);
  1116 	Parent::set(key, 0);
  1117       }
  1118     };
  1119 
  1120   public:
  1121 
  1122     /// \brief Constructor.
  1123     ///
  1124     /// Constructor for creating in-degree map.
  1125     InDegMap(const Graph& _graph) : graph(_graph), deg(_graph) {
  1126       AlterationNotifier<typename _Graph::Edge>
  1127 	::ObserverBase::attach(graph.getNotifier(typename _Graph::Edge()));
  1128       
  1129       for(typename _Graph::NodeIt it(graph); it != INVALID; ++it) {
  1130 	deg[it] = countInEdges(graph, it);
  1131       }
  1132     }
  1133 
  1134     virtual ~InDegMap() {
  1135       AlterationNotifier<typename _Graph::Edge>::
  1136 	ObserverBase::detach();
  1137     }
  1138     
  1139     /// Gives back the in-degree of a Node.
  1140     int operator[](const Key& key) const {
  1141       return deg[key];
  1142     }
  1143 
  1144   protected:
  1145     
  1146     typedef typename Graph::Edge Edge;
  1147 
  1148     virtual void add(const Edge& edge) {
  1149       ++deg[graph.target(edge)];
  1150     }
  1151 
  1152     virtual void erase(const Edge& edge) {
  1153       --deg[graph.target(edge)];
  1154     }
  1155 
  1156 
  1157     virtual void build() {
  1158       for(typename _Graph::NodeIt it(graph); it != INVALID; ++it) {
  1159 	deg[it] = countInEdges(graph, it);
  1160       }      
  1161     }
  1162 
  1163     virtual void clear() {
  1164       for(typename _Graph::NodeIt it(graph); it != INVALID; ++it) {
  1165 	deg[it] = 0;
  1166       }
  1167     }
  1168   private:
  1169     
  1170     const _Graph& graph;
  1171     AutoNodeMap deg;
  1172   };
  1173 
  1174   /// \brief Map of the node out-degrees.
  1175   ///
  1176   /// This map returns the out-degree of a node. Once it is constructed,
  1177   /// the degrees are stored in a standard NodeMap, so each query is done
  1178   /// in constant time. On the other hand, the values are updated automatically
  1179   /// whenever the graph changes.
  1180   ///
  1181   /// \warning Besides addNode() and addEdge(), a graph structure may provide
  1182   /// alternative ways to mogify the graph. The correct behavior of OutDegMap
  1183   /// is not guarantied if these additional featureas are used. For example
  1184   /// the funstions \ref ListGraph::changeSource() "changeSource()",
  1185   /// \ref ListGraph::changeTarget() "changeTarget()" and
  1186   /// \ref ListGraph::reverseEdge() "reverseEdge()"
  1187   /// of \ref ListGraph will \e not update the degree values correctly.
  1188   ///
  1189   /// \sa InDegMap
  1190 
  1191   template <typename _Graph>
  1192   class OutDegMap  
  1193     : protected AlterationNotifier<typename _Graph::Edge>::ObserverBase {
  1194 
  1195   public:
  1196     
  1197     typedef _Graph Graph;
  1198     typedef int Value;
  1199     typedef typename Graph::Node Key;
  1200 
  1201   private:
  1202 
  1203     class AutoNodeMap : public Graph::template NodeMap<int> {
  1204     public:
  1205 
  1206       typedef typename Graph::template NodeMap<int> Parent;
  1207 
  1208       typedef typename Parent::Key Key;
  1209       typedef typename Parent::Value Value;
  1210       
  1211       AutoNodeMap(const Graph& graph) : Parent(graph, 0) {}
  1212       
  1213       void add(const Key& key) {
  1214 	Parent::add(key);
  1215 	Parent::set(key, 0);
  1216       }
  1217     };
  1218 
  1219   public:
  1220 
  1221     /// \brief Constructor.
  1222     ///
  1223     /// Constructor for creating out-degree map.
  1224     OutDegMap(const Graph& _graph) : graph(_graph), deg(_graph) {
  1225       AlterationNotifier<typename _Graph::Edge>
  1226 	::ObserverBase::attach(graph.getNotifier(typename _Graph::Edge()));
  1227       
  1228       for(typename _Graph::NodeIt it(graph); it != INVALID; ++it) {
  1229 	deg[it] = countOutEdges(graph, it);
  1230       }
  1231     }
  1232 
  1233     virtual ~OutDegMap() {
  1234       AlterationNotifier<typename _Graph::Edge>::
  1235 	ObserverBase::detach();
  1236     }
  1237     
  1238     /// Gives back the in-degree of a Node.
  1239     int operator[](const Key& key) const {
  1240       return deg[key];
  1241     }
  1242 
  1243   protected:
  1244     
  1245     typedef typename Graph::Edge Edge;
  1246 
  1247     virtual void add(const Edge& edge) {
  1248       ++deg[graph.source(edge)];
  1249     }
  1250 
  1251     virtual void erase(const Edge& edge) {
  1252       --deg[graph.source(edge)];
  1253     }
  1254 
  1255 
  1256     virtual void build() {
  1257       for(typename _Graph::NodeIt it(graph); it != INVALID; ++it) {
  1258 	deg[it] = countOutEdges(graph, it);
  1259       }      
  1260     }
  1261 
  1262     virtual void clear() {
  1263       for(typename _Graph::NodeIt it(graph); it != INVALID; ++it) {
  1264 	deg[it] = 0;
  1265       }
  1266     }
  1267   private:
  1268     
  1269     const _Graph& graph;
  1270     AutoNodeMap deg;
  1271   };
  1272 
  1273   /// @}
  1274 
  1275 } //END OF NAMESPACE LEMON
  1276 
  1277 #endif