lemon/smart_graph.h
author alpar
Mon, 28 Aug 2006 16:10:12 +0000
changeset 2183 b6602864e456
parent 2151 38ec4a930c05
child 2190 dd887831e9c1
permissions -rw-r--r--
Update header list
     1 /* -*- C++ -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library
     4  *
     5  * Copyright (C) 2003-2006
     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_SMART_GRAPH_H
    20 #define LEMON_SMART_GRAPH_H
    21 
    22 ///\ingroup graphs
    23 ///\file
    24 ///\brief SmartGraph and SmartUGraph classes.
    25 
    26 #include <vector>
    27 
    28 #include <lemon/bits/invalid.h>
    29 
    30 #include <lemon/bits/base_extender.h>
    31 #include <lemon/bits/graph_extender.h>
    32 
    33 #include <lemon/bits/utility.h>
    34 #include <lemon/error.h>
    35 
    36 #include <lemon/bits/graph_extender.h>
    37 
    38 namespace lemon {
    39 
    40   class SmartGraph;
    41   ///Base of SmartGraph
    42 
    43   ///Base of SmartGraph
    44   ///
    45   class SmartGraphBase {
    46 
    47     friend class SmatGraph;
    48 
    49   protected:
    50     struct NodeT 
    51     {
    52       int first_in,first_out;      
    53       NodeT() : first_in(-1), first_out(-1) {}
    54     };
    55     struct EdgeT 
    56     {
    57       int target, source, next_in, next_out;      
    58       //FIXME: is this necessary?
    59       EdgeT() : next_in(-1), next_out(-1) {}  
    60     };
    61 
    62     std::vector<NodeT> nodes;
    63 
    64     std::vector<EdgeT> edges;
    65     
    66     
    67   public:
    68 
    69     typedef SmartGraphBase Graph;
    70 
    71     class Node;
    72     class Edge;
    73 
    74     
    75   public:
    76 
    77     SmartGraphBase() : nodes(), edges() { }
    78     SmartGraphBase(const SmartGraphBase &_g) 
    79       : nodes(_g.nodes), edges(_g.edges) { }
    80     
    81     typedef True NodeNumTag;
    82     typedef True EdgeNumTag;
    83 
    84     ///Number of nodes.
    85     int nodeNum() const { return nodes.size(); }
    86     ///Number of edges.
    87     int edgeNum() const { return edges.size(); }
    88 
    89     /// Maximum node ID.
    90     
    91     /// Maximum node ID.
    92     ///\sa id(Node)
    93     int maxNodeId() const { return nodes.size()-1; }
    94     /// Maximum edge ID.
    95     
    96     /// Maximum edge ID.
    97     ///\sa id(Edge)
    98     int maxEdgeId() const { return edges.size()-1; }
    99 
   100     Node addNode() {
   101       Node n; n.n=nodes.size();
   102       nodes.push_back(NodeT()); //FIXME: Hmmm...
   103       return n;
   104     }
   105     
   106     Edge addEdge(Node u, Node v) {
   107       Edge e; e.n=edges.size(); edges.push_back(EdgeT()); //FIXME: Hmmm...
   108       edges[e.n].source=u.n; edges[e.n].target=v.n;
   109       edges[e.n].next_out=nodes[u.n].first_out;
   110       edges[e.n].next_in=nodes[v.n].first_in;
   111       nodes[u.n].first_out=nodes[v.n].first_in=e.n;
   112 
   113       return e;
   114     }
   115 
   116 
   117     Node source(Edge e) const { return edges[e.n].source; }
   118     Node target(Edge e) const { return edges[e.n].target; }
   119 
   120     /// Node ID.
   121     
   122     /// The ID of a valid Node is a nonnegative integer not greater than
   123     /// \ref maxNodeId(). The range of the ID's is not surely continuous
   124     /// and the greatest node ID can be actually less then \ref maxNodeId().
   125     ///
   126     /// The ID of the \ref INVALID node is -1.
   127     ///\return The ID of the node \c v. 
   128     static int id(Node v) { return v.n; }
   129     /// Edge ID.
   130     
   131     /// The ID of a valid Edge is a nonnegative integer not greater than
   132     /// \ref maxEdgeId(). The range of the ID's is not surely continuous
   133     /// and the greatest edge ID can be actually less then \ref maxEdgeId().
   134     ///
   135     /// The ID of the \ref INVALID edge is -1.
   136     ///\return The ID of the edge \c e. 
   137     static int id(Edge e) { return e.n; }
   138 
   139     /// \brief Returns the node from its \c id.
   140     ///
   141     /// Returns the node from its \c id. If there is not node
   142     /// with the given id the effect of the function is undefinied.
   143     static Node nodeFromId(int id) { return Node(id);}
   144 
   145     /// \brief Returns the edge from its \c id.
   146     ///
   147     /// Returns the edge from its \c id. If there is not edge
   148     /// with the given id the effect of the function is undefinied.
   149     static Edge edgeFromId(int id) { return Edge(id);}
   150 
   151     class Node {
   152       friend class SmartGraphBase;
   153       friend class SmartGraph;
   154 
   155     protected:
   156       int n;
   157       Node(int nn) {n=nn;}
   158     public:
   159       Node() {}
   160       Node (Invalid) { n=-1; }
   161       bool operator==(const Node i) const {return n==i.n;}
   162       bool operator!=(const Node i) const {return n!=i.n;}
   163       bool operator<(const Node i) const {return n<i.n;}
   164     };
   165     
   166 
   167     class Edge {
   168       friend class SmartGraphBase;
   169       friend class SmartGraph;
   170 
   171     protected:
   172       int n;
   173       Edge(int nn) {n=nn;}
   174     public:
   175       Edge() { }
   176       Edge (Invalid) { n=-1; }
   177       bool operator==(const Edge i) const {return n==i.n;}
   178       bool operator!=(const Edge i) const {return n!=i.n;}
   179       bool operator<(const Edge i) const {return n<i.n;}
   180     };
   181 
   182     void first(Node& node) const {
   183       node.n = nodes.size() - 1;
   184     }
   185 
   186     static void next(Node& node) {
   187       --node.n;
   188     }
   189 
   190     void first(Edge& edge) const {
   191       edge.n = edges.size() - 1;
   192     }
   193 
   194     static void next(Edge& edge) {
   195       --edge.n;
   196     }
   197 
   198     void firstOut(Edge& edge, const Node& node) const {
   199       edge.n = nodes[node.n].first_out;
   200     }
   201 
   202     void nextOut(Edge& edge) const {
   203       edge.n = edges[edge.n].next_out;
   204     }
   205 
   206     void firstIn(Edge& edge, const Node& node) const {
   207       edge.n = nodes[node.n].first_in;
   208     }
   209     
   210     void nextIn(Edge& edge) const {
   211       edge.n = edges[edge.n].next_in;
   212     }
   213 
   214   };
   215 
   216   typedef GraphExtender<SmartGraphBase> ExtendedSmartGraphBase;
   217 
   218   /// \ingroup graphs
   219 
   220   ///A smart graph class.
   221 
   222   ///This is a simple and fast graph implementation.
   223   ///It is also quite memory efficient, but at the price
   224   ///that <b> it does support only limited (only stack-like)
   225   ///node and edge deletions</b>.
   226   ///It conforms to 
   227   ///the \ref concept::Graph "Graph concept".
   228   ///\sa concept::Graph.
   229   ///
   230   ///\author Alpar Juttner
   231   class SmartGraph : public ExtendedSmartGraphBase {
   232   public:
   233 
   234     typedef ExtendedSmartGraphBase Parent;
   235 
   236     class Snapshot;
   237     friend class Snapshot;
   238 
   239   private:
   240     ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
   241 
   242     ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
   243     ///
   244     SmartGraph(const SmartGraph &) :ExtendedSmartGraphBase() {};
   245     ///\brief Assignment of SmartGraph to another one is \e not allowed.
   246     ///Use GraphCopy() instead.
   247 
   248     ///Assignment of SmartGraph to another one is \e not allowed.
   249     ///Use GraphCopy() instead.
   250     void operator=(const SmartGraph &) {}
   251   protected:
   252     void restoreSnapshot(const Snapshot &s)
   253     {
   254       while(s.edge_num<edges.size()) {
   255 	Parent::getNotifier(Edge()).erase(Edge(edges.size()-1));
   256 	nodes[edges.back().target].first_in=edges.back().next_in;
   257 	nodes[edges.back().source].first_out=edges.back().next_out;
   258 	edges.pop_back();
   259       }
   260       //nodes.resize(s.nodes_num);
   261       while(s.node_num<nodes.size()) {
   262 	Parent::getNotifier(Node()).erase(Node(nodes.size()-1));
   263 	nodes.pop_back();
   264       }
   265     }    
   266 
   267   public:
   268     
   269     /// Constructor
   270     
   271     /// Constructor.
   272     ///
   273     SmartGraph() {};
   274     
   275     ///Add a new node to the graph.
   276     
   277     /// \return the new node.
   278     ///
   279     Node addNode() { return Parent::addNode(); }
   280     
   281     ///Add a new edge to the graph.
   282     
   283     ///Add a new edge to the graph with source node \c s
   284     ///and target node \c t.
   285     ///\return the new edge.
   286     Edge addEdge(const Node& s, const Node& t) { 
   287       return Parent::addEdge(s, t); 
   288     }
   289 
   290     ///\e
   291     
   292     ///\bug Undocumented
   293     ///\bug Doesn't destruct the maps.
   294     void clear() {
   295       edges.clear();
   296       nodes.clear();
   297     }
   298 
   299     ///Split a node.
   300     
   301     ///This function splits a node. First a new node is added to the graph,
   302     ///then the source of each outgoing edge of \c n is moved to this new node.
   303     ///If \c connect is \c true (this is the default value), then a new edge
   304     ///from \c n to the newly created node is also added.
   305     ///\return The newly created node.
   306     ///
   307     ///\note The <tt>Edge</tt>s
   308     ///referencing a moved edge remain
   309     ///valid. However <tt>InEdge</tt>'s and <tt>OutEdge</tt>'s
   310     ///may be invalidated.
   311     ///\warning This functionality cannot be used together with the Snapshot
   312     ///feature.
   313     ///\todo It could be implemented in a bit faster way.
   314     Node split(Node n, bool connect = true)
   315     {
   316       Node b = addNode();
   317       nodes[b.n].first_out=nodes[n.n].first_out;
   318       nodes[n.n].first_out=-1;
   319       for(int i=nodes[b.n].first_out;i!=-1;i++) edges[i].source=b.n;
   320       if(connect) addEdge(n,b);
   321       return b;
   322     }
   323 
   324     ///Class to make a snapshot of the graph and to restrore to it later.
   325 
   326     ///Class to make a snapshot of the graph and to restrore to it later.
   327     ///
   328     ///The newly added nodes and edges can be removed using the
   329     ///restore() function.
   330     ///\note After you restore a state, you cannot restore
   331     ///a later state, in other word you cannot add again the edges deleted
   332     ///by restore() using another one Snapshot instance.
   333     ///
   334     class Snapshot 
   335     {
   336       SmartGraph *g;
   337     protected:
   338       friend class SmartGraph;
   339       unsigned int node_num;
   340       unsigned int edge_num;
   341     public:
   342       ///Default constructor.
   343       
   344       ///Default constructor.
   345       ///To actually make a snapshot you must call save().
   346       ///
   347       Snapshot() : g(0) {}
   348       ///Constructor that immediately makes a snapshot
   349       
   350       ///This constructor immediately makes a snapshot of the graph.
   351       ///\param _g The graph we make a snapshot of.
   352       Snapshot(SmartGraph &_g) :g(&_g) {
   353 	node_num=g->nodes.size();
   354 	edge_num=g->edges.size();
   355       }
   356 
   357       ///Make a snapshot.
   358 
   359       ///Make a snapshot of the graph.
   360       ///
   361       ///This function can be called more than once. In case of a repeated
   362       ///call, the previous snapshot gets lost.
   363       ///\param _g The graph we make the snapshot of.
   364       void save(SmartGraph &_g) 
   365       {
   366 	g=&_g;
   367 	node_num=g->nodes.size();
   368 	edge_num=g->edges.size();
   369       }
   370 
   371       ///Undo the changes until a snapshot.
   372       
   373       ///Undo the changes until a snapshot created by save().
   374       ///
   375       ///\note After you restored a state, you cannot restore
   376       ///a later state, in other word you cannot add again the edges deleted
   377       ///by restore().
   378       ///
   379       ///\todo This function might be called undo().
   380       
   381       void restore()
   382       {
   383 	g->restoreSnapshot(*this);
   384       }
   385     };
   386   };
   387 
   388 
   389   /**************** Undirected List Graph ****************/
   390 
   391   typedef UGraphExtender<UndirGraphExtender<SmartGraphBase> >
   392   ExtendedSmartUGraphBase;
   393 
   394   /// \ingroup graphs
   395   ///
   396   /// \brief A smart undirected graph class.
   397   ///
   398   /// This is a simple and fast undirected graph implementation.
   399   /// It is also quite memory efficient, but at the price
   400   /// that <b> it does support only limited (only stack-like)
   401   /// node and edge deletions</b>.
   402   /// Except from this it conforms to 
   403   /// the \ref concept::UGraph "UGraph concept".
   404   /// \sa concept::UGraph.
   405   ///
   406   /// \todo Snapshot hasn't been implemented yet.
   407   ///
   408   class SmartUGraph : public ExtendedSmartUGraphBase {
   409   private:
   410     ///SmartUGraph is \e not copy constructible. Use UGraphCopy() instead.
   411 
   412     ///SmartUGraph is \e not copy constructible. Use UGraphCopy() instead.
   413     ///
   414     SmartUGraph(const SmartUGraph &) : ExtendedSmartUGraphBase() {};
   415     ///\brief Assignment of SmartUGraph to another one is \e not allowed.
   416     ///Use UGraphCopy() instead.
   417 
   418     ///Assignment of SmartUGraph to another one is \e not allowed.
   419     ///Use UGraphCopy() instead.
   420     void operator=(const SmartUGraph &) {}
   421   public:
   422     /// Constructor
   423     
   424     /// Constructor.
   425     ///
   426     SmartUGraph() {}
   427   };
   428 
   429 
   430   class SmartBpUGraphBase {
   431   public:
   432 
   433     class NodeSetError : public LogicError {
   434     public:
   435       virtual const char* what() const throw() { 
   436 	return "lemon::SmartBpUGraph::NodeSetError";
   437       }
   438     };
   439 
   440   protected:
   441 
   442     struct NodeT {
   443       int first;
   444       NodeT() {}
   445       NodeT(int _first) : first(_first) {}
   446     };
   447 
   448     struct UEdgeT {
   449       int aNode, next_out;
   450       int bNode, next_in;
   451     };
   452 
   453     std::vector<NodeT> aNodes;
   454     std::vector<NodeT> bNodes;
   455 
   456     std::vector<UEdgeT> edges;
   457 
   458   public:
   459   
   460     class Node {
   461       friend class SmartBpUGraphBase;
   462     protected:
   463       int id;
   464 
   465       Node(int _id) : id(_id) {}
   466     public:
   467       Node() {}
   468       Node(Invalid) { id = -1; }
   469       bool operator==(const Node i) const {return id==i.id;}
   470       bool operator!=(const Node i) const {return id!=i.id;}
   471       bool operator<(const Node i) const {return id<i.id;}
   472     };
   473 
   474     class UEdge {
   475       friend class SmartBpUGraphBase;
   476     protected:
   477       int id;
   478 
   479       UEdge(int _id) { id = _id;}
   480     public:
   481       UEdge() {}
   482       UEdge (Invalid) { id = -1; }
   483       bool operator==(const UEdge i) const {return id==i.id;}
   484       bool operator!=(const UEdge i) const {return id!=i.id;}
   485       bool operator<(const UEdge i) const {return id<i.id;}
   486     };
   487 
   488     void firstANode(Node& node) const {
   489       node.id = 2 * aNodes.size() - 2;
   490       if (node.id < 0) node.id = -1; 
   491     }
   492     void nextANode(Node& node) const {
   493       node.id -= 2;
   494       if (node.id < 0) node.id = -1; 
   495     }
   496 
   497     void firstBNode(Node& node) const {
   498       node.id = 2 * bNodes.size() - 1;
   499     }
   500     void nextBNode(Node& node) const {
   501       node.id -= 2;
   502     }
   503 
   504     void first(Node& node) const {
   505       if (aNodes.size() > 0) {
   506 	node.id = 2 * aNodes.size() - 2;
   507       } else {
   508 	node.id = 2 * bNodes.size() - 1;
   509       }
   510     }
   511     void next(Node& node) const {
   512       node.id -= 2;
   513       if (node.id == -2) {
   514 	node.id = 2 * bNodes.size() - 1;
   515       }
   516     }
   517   
   518     void first(UEdge& edge) const {
   519       edge.id = edges.size() - 1;
   520     }
   521     void next(UEdge& edge) const {
   522       --edge.id;
   523     }
   524 
   525     void firstFromANode(UEdge& edge, const Node& node) const {
   526       LEMON_ASSERT((node.id & 1) == 0, NodeSetError());
   527       edge.id = aNodes[node.id >> 1].first;
   528     }
   529     void nextFromANode(UEdge& edge) const {
   530       edge.id = edges[edge.id].next_out;
   531     }
   532 
   533     void firstFromBNode(UEdge& edge, const Node& node) const {
   534       LEMON_ASSERT((node.id & 1) == 1, NodeSetError());
   535       edge.id = bNodes[node.id >> 1].first;
   536     }
   537     void nextFromBNode(UEdge& edge) const {
   538       edge.id = edges[edge.id].next_in;
   539     }
   540 
   541     static int id(const Node& node) {
   542       return node.id;
   543     }
   544     static Node nodeFromId(int id) {
   545       return Node(id);
   546     }
   547     int maxNodeId() const {
   548       return aNodes.size() > bNodes.size() ?
   549 	aNodes.size() * 2 - 2 : bNodes.size() * 2 - 1;
   550     }
   551   
   552     static int id(const UEdge& edge) {
   553       return edge.id;
   554     }
   555     static UEdge uEdgeFromId(int id) {
   556       return UEdge(id);
   557     }
   558     int maxUEdgeId() const {
   559       return edges.size();
   560     }
   561   
   562     static int aNodeId(const Node& node) {
   563       return node.id >> 1;
   564     }
   565     static Node fromANodeId(int id) {
   566       return Node(id << 1);
   567     }
   568     int maxANodeId() const {
   569       return aNodes.size();
   570     }
   571 
   572     static int bNodeId(const Node& node) {
   573       return node.id >> 1;
   574     }
   575     static Node fromBNodeId(int id) {
   576       return Node((id << 1) + 1);
   577     }
   578     int maxBNodeId() const {
   579       return bNodes.size();
   580     }
   581 
   582     Node aNode(const UEdge& edge) const {
   583       return Node(edges[edge.id].aNode);
   584     }
   585     Node bNode(const UEdge& edge) const {
   586       return Node(edges[edge.id].bNode);
   587     }
   588 
   589     static bool aNode(const Node& node) {
   590       return (node.id & 1) == 0;
   591     }
   592 
   593     static bool bNode(const Node& node) {
   594       return (node.id & 1) == 1;
   595     }
   596 
   597     Node addANode() {
   598       NodeT nodeT;
   599       nodeT.first = -1;
   600       aNodes.push_back(nodeT);
   601       return Node(aNodes.size() * 2 - 2);
   602     }
   603 
   604     Node addBNode() {
   605       NodeT nodeT;
   606       nodeT.first = -1;
   607       bNodes.push_back(nodeT);
   608       return Node(bNodes.size() * 2 - 1);
   609     }
   610 
   611     UEdge addEdge(const Node& source, const Node& target) {
   612       LEMON_ASSERT(((source.id ^ target.id) & 1) == 1, NodeSetError());
   613       UEdgeT edgeT;
   614       if ((source.id & 1) == 0) {
   615 	edgeT.aNode = source.id;
   616 	edgeT.bNode = target.id;
   617       } else {
   618 	edgeT.aNode = target.id;
   619 	edgeT.bNode = source.id;
   620       }
   621       edgeT.next_out = aNodes[edgeT.aNode >> 1].first;
   622       aNodes[edgeT.aNode >> 1].first = edges.size();
   623       edgeT.next_in = bNodes[edgeT.bNode >> 1].first;
   624       bNodes[edgeT.bNode >> 1].first = edges.size();
   625       edges.push_back(edgeT);
   626       return UEdge(edges.size() - 1);
   627     }
   628 
   629     void clear() {
   630       aNodes.clear();
   631       bNodes.clear();
   632       edges.clear();
   633     }
   634 
   635     typedef True NodeNumTag;
   636     int nodeNum() const { return aNodes.size() + bNodes.size(); }
   637     int aNodeNum() const { return aNodes.size(); }
   638     int bNodeNum() const { return bNodes.size(); }
   639 
   640     typedef True EdgeNumTag;
   641     int uEdgeNum() const { return edges.size(); }
   642 
   643   };
   644 
   645 
   646   typedef BpUGraphExtender<SmartBpUGraphBase> ExtendedSmartBpUGraphBase;
   647 
   648   /// \ingroup graphs
   649   ///
   650   /// \brief A smart bipartite undirected graph class.
   651   ///
   652   /// This is a simple and fast bipartite undirected graph implementation.
   653   /// It is also quite memory efficient, but at the price
   654   /// that <b> it does not support node and edge deletions</b>.
   655   /// Except from this it conforms to 
   656   /// the \ref concept::BpUGraph "BpUGraph concept".
   657   /// \sa concept::BpUGraph.
   658   ///
   659   class SmartBpUGraph : public ExtendedSmartBpUGraphBase {};
   660 
   661   
   662   /// @}  
   663 } //namespace lemon
   664 
   665 
   666 #endif //LEMON_SMART_GRAPH_H