lemon/smart_graph.h
author klao
Thu, 02 Feb 2006 17:09:09 +0000
changeset 1945 e5c0c5cc477f
parent 1909 2d806130e700
child 1956 a055123339d5
permissions -rw-r--r--
NEWS: major changes since 0.4 added
     1 /* -*- C++ -*-
     2  * lemon/smart_graph.h - Part of LEMON, a generic C++ optimization library
     3  *
     4  * Copyright (C) 2006 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_SMART_GRAPH_H
    18 #define LEMON_SMART_GRAPH_H
    19 
    20 ///\ingroup graphs
    21 ///\file
    22 ///\brief SmartGraph and SmartUGraph classes.
    23 
    24 #include <vector>
    25 
    26 #include <lemon/invalid.h>
    27 
    28 #include <lemon/bits/clearable_graph_extender.h>
    29 #include <lemon/bits/extendable_graph_extender.h>
    30 #include <lemon/bits/iterable_graph_extender.h>
    31 #include <lemon/bits/alteration_notifier.h>
    32 #include <lemon/bits/default_map.h>
    33 #include <lemon/bits/graph_extender.h>
    34 
    35 #include <lemon/utility.h>
    36 #include <lemon/error.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 source(Edge e) const { return edges[e.n].source; }
   101     Node target(Edge e) const { return edges[e.n].target; }
   102 
   103     /// Node ID.
   104     
   105     /// The ID of a valid Node is a nonnegative integer not greater than
   106     /// \ref maxNodeId(). The range of the ID's is not surely continuous
   107     /// and the greatest node ID can be actually less then \ref maxNodeId().
   108     ///
   109     /// The ID of the \ref INVALID node is -1.
   110     ///\return The ID of the node \c v. 
   111     static int id(Node v) { return v.n; }
   112     /// Edge ID.
   113     
   114     /// The ID of a valid Edge is a nonnegative integer not greater than
   115     /// \ref maxEdgeId(). The range of the ID's is not surely continuous
   116     /// and the greatest edge ID can be actually less then \ref maxEdgeId().
   117     ///
   118     /// The ID of the \ref INVALID edge is -1.
   119     ///\return The ID of the edge \c e. 
   120     static int id(Edge e) { return e.n; }
   121 
   122     static Node nodeFromId(int id) { return Node(id);}
   123 
   124     static Edge edgeFromId(int id) { return Edge(id);}
   125 
   126     Node addNode() {
   127       Node n; n.n=nodes.size();
   128       nodes.push_back(NodeT()); //FIXME: Hmmm...
   129       return n;
   130     }
   131     
   132     Edge addEdge(Node u, Node v) {
   133       Edge e; e.n=edges.size(); edges.push_back(EdgeT()); //FIXME: Hmmm...
   134       edges[e.n].source=u.n; edges[e.n].target=v.n;
   135       edges[e.n].next_out=nodes[u.n].first_out;
   136       edges[e.n].next_in=nodes[v.n].first_in;
   137       nodes[u.n].first_out=nodes[v.n].first_in=e.n;
   138 
   139       return e;
   140     }
   141 
   142     void clear() {
   143       edges.clear();
   144       nodes.clear();
   145     }
   146 
   147 
   148     class Node {
   149       friend class SmartGraphBase;
   150       friend class SmartGraph;
   151 
   152     protected:
   153       int n;
   154       Node(int nn) {n=nn;}
   155     public:
   156       Node() {}
   157       Node (Invalid) { n=-1; }
   158       bool operator==(const Node i) const {return n==i.n;}
   159       bool operator!=(const Node i) const {return n!=i.n;}
   160       bool operator<(const Node i) const {return n<i.n;}
   161     };
   162     
   163 
   164     class Edge {
   165       friend class SmartGraphBase;
   166       friend class SmartGraph;
   167 
   168     protected:
   169       int n;
   170       Edge(int nn) {n=nn;}
   171     public:
   172       Edge() { }
   173       Edge (Invalid) { n=-1; }
   174       bool operator==(const Edge i) const {return n==i.n;}
   175       bool operator!=(const Edge i) const {return n!=i.n;}
   176       bool operator<(const Edge i) const {return n<i.n;}
   177     };
   178 
   179     void first(Node& node) const {
   180       node.n = nodes.size() - 1;
   181     }
   182 
   183     static void next(Node& node) {
   184       --node.n;
   185     }
   186 
   187     void first(Edge& edge) const {
   188       edge.n = edges.size() - 1;
   189     }
   190 
   191     static void next(Edge& edge) {
   192       --edge.n;
   193     }
   194 
   195     void firstOut(Edge& edge, const Node& node) const {
   196       edge.n = nodes[node.n].first_out;
   197     }
   198 
   199     void nextOut(Edge& edge) const {
   200       edge.n = edges[edge.n].next_out;
   201     }
   202 
   203     void firstIn(Edge& edge, const Node& node) const {
   204       edge.n = nodes[node.n].first_in;
   205     }
   206     
   207     void nextIn(Edge& edge) const {
   208       edge.n = edges[edge.n].next_in;
   209     }
   210 
   211     Node _split(Node n, bool connect = true)
   212     {
   213       Node b = addNode();
   214       nodes[b.n].first_out=nodes[n.n].first_out;
   215       nodes[n.n].first_out=-1;
   216       for(int i=nodes[b.n].first_out;i!=-1;i++) edges[i].source=b.n;
   217       if(connect) addEdge(n,b);
   218       return b;
   219     }
   220 
   221   };
   222 
   223   typedef ClearableGraphExtender<
   224     ExtendableGraphExtender<
   225     MappableGraphExtender<
   226     IterableGraphExtender<
   227     AlterableGraphExtender<
   228     GraphExtender<SmartGraphBase> > > > > > ExtendedSmartGraphBase;
   229 
   230   /// \ingroup graphs
   231 
   232   ///A smart graph class.
   233 
   234   ///This is a simple and fast graph implementation.
   235   ///It is also quite memory efficient, but at the price
   236   ///that <b> it does support only limited (only stack-like)
   237   ///node and edge deletions</b>.
   238   ///It conforms to 
   239   ///the \ref concept::ExtendableGraph "ExtendableGraph" concept.
   240   ///\sa concept::ExtendableGraph.
   241   ///
   242   ///\author Alpar Juttner
   243   class SmartGraph : public ExtendedSmartGraphBase {
   244   public:
   245     
   246     class Snapshot;
   247     friend class Snapshot;
   248 
   249   protected:
   250     void restoreSnapshot(const Snapshot &s)
   251     {
   252       while(s.edge_num<edges.size()) {
   253 	Parent::getNotifier(Edge()).erase(Edge(edges.size()-1));
   254 	nodes[edges.back().target].first_in=edges.back().next_in;
   255 	nodes[edges.back().source].first_out=edges.back().next_out;
   256 	edges.pop_back();
   257       }
   258       //nodes.resize(s.nodes_num);
   259       while(s.node_num<nodes.size()) {
   260 	Parent::getNotifier(Node()).erase(Node(nodes.size()-1));
   261 	nodes.pop_back();
   262       }
   263     }    
   264 
   265   public:
   266 
   267     ///Split a node.
   268     
   269     ///This function splits a node. First a new node is added to the graph,
   270     ///then the source of each outgoing edge of \c n is moved to this new node.
   271     ///If \c connect is \c true (this is the default value), then a new edge
   272     ///from \c n to the newly created node is also added.
   273     ///\return The newly created node.
   274     ///
   275     ///\note The <tt>Edge</tt>s
   276     ///referencing a moved edge remain
   277     ///valid. However <tt>InEdge</tt>'s and <tt>OutEdge</tt>'s
   278     ///may be invalidated.
   279     ///\warning This functionality cannot be used together with the Snapshot
   280     ///feature.
   281     ///\todo It could be implemented in a bit faster way.
   282     Node split(Node n, bool connect = true) 
   283     {
   284       Node b = _split(n,connect);
   285       return b;
   286     }
   287   
   288 
   289     ///Class to make a snapshot of the graph and to restrore to it later.
   290 
   291     ///Class to make a snapshot of the graph and to restrore to it later.
   292     ///
   293     ///The newly added nodes and edges can be removed using the
   294     ///restore() function.
   295     ///\note After you restore a state, you cannot restore
   296     ///a later state, in other word you cannot add again the edges deleted
   297     ///by restore() using another Snapshot instance.
   298     ///
   299     class Snapshot 
   300     {
   301       SmartGraph *g;
   302     protected:
   303       friend class SmartGraph;
   304       unsigned int node_num;
   305       unsigned int edge_num;
   306     public:
   307       ///Default constructor.
   308       
   309       ///Default constructor.
   310       ///To actually make a snapshot you must call save().
   311       ///
   312       Snapshot() : g(0) {}
   313       ///Constructor that immediately makes a snapshot
   314       
   315       ///This constructor immediately makes a snapshot of the graph.
   316       ///\param _g The graph we make a snapshot of.
   317       Snapshot(SmartGraph &_g) :g(&_g) {
   318 	node_num=g->nodes.size();
   319 	edge_num=g->edges.size();
   320       }
   321 
   322       ///Make a snapshot.
   323 
   324       ///Make a snapshot of the graph.
   325       ///
   326       ///This function can be called more than once. In case of a repeated
   327       ///call, the previous snapshot gets lost.
   328       ///\param _g The graph we make the snapshot of.
   329       void save(SmartGraph &_g) 
   330       {
   331 	g=&_g;
   332 	node_num=g->nodes.size();
   333 	edge_num=g->edges.size();
   334       }
   335 
   336       ///Undo the changes until a snapshot.
   337       
   338       ///Undo the changes until a snapshot created by save().
   339       ///
   340       ///\note After you restored a state, you cannot restore
   341       ///a later state, in other word you cannot add again the edges deleted
   342       ///by restore().
   343       ///
   344       ///\todo This function might be called undo().
   345       
   346       void restore()
   347       {
   348 	g->restoreSnapshot(*this);
   349       }
   350     };
   351   };
   352 
   353 
   354   /**************** Undirected List Graph ****************/
   355 
   356   typedef ClearableUGraphExtender<
   357     ExtendableUGraphExtender<
   358     MappableUGraphExtender<
   359     IterableUGraphExtender<
   360     AlterableUGraphExtender<
   361     UGraphExtender<SmartGraphBase> > > > > > ExtendedSmartUGraphBase;
   362 
   363   /// \ingroup graphs
   364   ///
   365   /// \brief A smart undirected graph class.
   366   ///
   367   /// This is a simple and fast undirected graph implementation.
   368   /// It is also quite memory efficient, but at the price
   369   /// that <b> it does support only limited (only stack-like)
   370   /// node and edge deletions</b>.
   371   /// Except from this it conforms to 
   372   /// the \ref concept::UGraph "UGraph" concept.
   373   /// \sa concept::UGraph.
   374   ///
   375   /// \todo Snapshot hasn't been implemented yet.
   376   ///
   377   class SmartUGraph : public ExtendedSmartUGraphBase {
   378   };
   379 
   380 
   381   class SmartBpUGraphBase {
   382   public:
   383 
   384     class NodeSetError : public LogicError {
   385       virtual const char* exceptionName() const { 
   386 	return "lemon::SmartBpUGraph::NodeSetError";
   387       }
   388     };
   389 
   390   protected:
   391 
   392     struct NodeT {
   393       int first;
   394       NodeT() {}
   395       NodeT(int _first) : first(_first) {}
   396     };
   397 
   398     struct EdgeT {
   399       int aNode, next_out;
   400       int bNode, next_in;
   401     };
   402 
   403     std::vector<NodeT> aNodes;
   404     std::vector<NodeT> bNodes;
   405 
   406     std::vector<EdgeT> edges;
   407 
   408   public:
   409   
   410     class Node {
   411       friend class SmartBpUGraphBase;
   412     protected:
   413       int id;
   414 
   415       Node(int _id) : id(_id) {}
   416     public:
   417       Node() {}
   418       Node(Invalid) { id = -1; }
   419       bool operator==(const Node i) const {return id==i.id;}
   420       bool operator!=(const Node i) const {return id!=i.id;}
   421       bool operator<(const Node i) const {return id<i.id;}
   422     };
   423 
   424     class Edge {
   425       friend class SmartBpUGraphBase;
   426     protected:
   427       int id;
   428 
   429       Edge(int _id) { id = _id;}
   430     public:
   431       Edge() {}
   432       Edge (Invalid) { id = -1; }
   433       bool operator==(const Edge i) const {return id==i.id;}
   434       bool operator!=(const Edge i) const {return id!=i.id;}
   435       bool operator<(const Edge i) const {return id<i.id;}
   436     };
   437 
   438     void firstANode(Node& node) const {
   439       node.id = 2 * aNodes.size() - 2;
   440       if (node.id < 0) node.id = -1; 
   441     }
   442     void nextANode(Node& node) const {
   443       node.id -= 2;
   444       if (node.id < 0) node.id = -1; 
   445     }
   446 
   447     void firstBNode(Node& node) const {
   448       node.id = 2 * bNodes.size() - 1;
   449     }
   450     void nextBNode(Node& node) const {
   451       node.id -= 2;
   452     }
   453 
   454     void first(Node& node) const {
   455       if (aNodes.size() > 0) {
   456 	node.id = 2 * aNodes.size() - 2;
   457       } else {
   458 	node.id = 2 * bNodes.size() - 1;
   459       }
   460     }
   461     void next(Node& node) const {
   462       node.id -= 2;
   463       if (node.id == -2) {
   464 	node.id = 2 * bNodes.size() - 1;
   465       }
   466     }
   467   
   468     void first(Edge& edge) const {
   469       edge.id = edges.size() - 1;
   470     }
   471     void next(Edge& edge) const {
   472       --edge.id;
   473     }
   474 
   475     void firstOut(Edge& edge, const Node& node) const {
   476       LEMON_ASSERT((node.id & 1) == 0, NodeSetError());
   477       edge.id = aNodes[node.id >> 1].first;
   478     }
   479     void nextOut(Edge& edge) const {
   480       edge.id = edges[edge.id].next_out;
   481     }
   482 
   483     void firstIn(Edge& edge, const Node& node) const {
   484       LEMON_ASSERT((node.id & 1) == 1, NodeSetError());
   485       edge.id = bNodes[node.id >> 1].first;
   486     }
   487     void nextIn(Edge& edge) const {
   488       edge.id = edges[edge.id].next_in;
   489     }
   490 
   491     static int id(const Node& node) {
   492       return node.id;
   493     }
   494     static Node nodeFromId(int id) {
   495       return Node(id);
   496     }
   497     int maxNodeId() const {
   498       return aNodes.size() > bNodes.size() ?
   499 	aNodes.size() * 2 - 2 : bNodes.size() * 2 - 1;
   500     }
   501   
   502     static int id(const Edge& edge) {
   503       return edge.id;
   504     }
   505     static Edge edgeFromId(int id) {
   506       return Edge(id);
   507     }
   508     int maxEdgeId() const {
   509       return edges.size();
   510     }
   511   
   512     static int aNodeId(const Node& node) {
   513       return node.id >> 1;
   514     }
   515     static Node fromANodeId(int id, Node) {
   516       return Node(id << 1);
   517     }
   518     int maxANodeId() const {
   519       return aNodes.size();
   520     }
   521 
   522     static int bNodeId(const Node& node) {
   523       return node.id >> 1;
   524     }
   525     static Node fromBNodeId(int id) {
   526       return Node((id << 1) + 1);
   527     }
   528     int maxBNodeId() const {
   529       return bNodes.size();
   530     }
   531 
   532     Node aNode(const Edge& edge) const {
   533       return Node(edges[edge.id].aNode);
   534     }
   535     Node bNode(const Edge& edge) const {
   536       return Node(edges[edge.id].bNode);
   537     }
   538 
   539     static bool aNode(const Node& node) {
   540       return (node.id & 1) == 0;
   541     }
   542 
   543     static bool bNode(const Node& node) {
   544       return (node.id & 1) == 1;
   545     }
   546 
   547     Node addANode() {
   548       NodeT nodeT;
   549       nodeT.first = -1;
   550       aNodes.push_back(nodeT);
   551       return Node(aNodes.size() * 2 - 2);
   552     }
   553 
   554     Node addBNode() {
   555       NodeT nodeT;
   556       nodeT.first = -1;
   557       bNodes.push_back(nodeT);
   558       return Node(bNodes.size() * 2 - 1);
   559     }
   560 
   561     Edge addEdge(const Node& source, const Node& target) {
   562       LEMON_ASSERT(((source.id ^ target.id) & 1) == 1, NodeSetError());
   563       EdgeT edgeT;
   564       if ((source.id & 1) == 0) {
   565 	edgeT.aNode = source.id;
   566 	edgeT.bNode = target.id;
   567       } else {
   568 	edgeT.aNode = target.id;
   569 	edgeT.bNode = source.id;
   570       }
   571       edgeT.next_out = aNodes[edgeT.aNode >> 1].first;
   572       aNodes[edgeT.aNode >> 1].first = edges.size();
   573       edgeT.next_in = bNodes[edgeT.bNode >> 1].first;
   574       bNodes[edgeT.bNode >> 1].first = edges.size();
   575       edges.push_back(edgeT);
   576       return Edge(edges.size() - 1);
   577     }
   578 
   579     void clear() {
   580       aNodes.clear();
   581       bNodes.clear();
   582       edges.clear();
   583     }
   584 
   585   };
   586 
   587 
   588   typedef ClearableBpUGraphExtender<
   589     ExtendableBpUGraphExtender<
   590     MappableBpUGraphExtender<
   591     IterableBpUGraphExtender<
   592     AlterableBpUGraphExtender<
   593     BpUGraphExtender <
   594     SmartBpUGraphBase> > > > > >
   595   ExtendedSmartBpUGraphBase;
   596 
   597   /// \ingroup graphs
   598   ///
   599   /// \brief A smart bipartite undirected graph class.
   600   ///
   601   /// This is a simple and fast bipartite undirected graph implementation.
   602   /// It is also quite memory efficient, but at the price
   603   /// that <b> it does not support node and edge deletions</b>.
   604   /// Except from this it conforms to 
   605   /// the \ref concept::BpUGraph "BpUGraph" concept.
   606   /// \sa concept::BpUGraph.
   607   ///
   608   class SmartBpUGraph : public ExtendedSmartBpUGraphBase {};
   609 
   610   
   611   /// @}  
   612 } //namespace lemon
   613 
   614 
   615 #endif //LEMON_SMART_GRAPH_H