COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/smart_graph.h @ 2132:783b1d583be3

Last change on this file since 2132:783b1d583be3 was 2132:783b1d583be3, checked in by Alpar Juttner, 13 years ago

(Hopefully) finish privatizing the copy constr. and operator= in
the graph concept, ListGraph? and SmartGraph?.

File size: 17.0 KB
Line 
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
38namespace 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      virtual const char* exceptionName() const {
435        return "lemon::SmartBpUGraph::NodeSetError";
436      }
437    };
438
439  protected:
440
441    struct NodeT {
442      int first;
443      NodeT() {}
444      NodeT(int _first) : first(_first) {}
445    };
446
447    struct UEdgeT {
448      int aNode, next_out;
449      int bNode, next_in;
450    };
451
452    std::vector<NodeT> aNodes;
453    std::vector<NodeT> bNodes;
454
455    std::vector<UEdgeT> edges;
456
457  public:
458 
459    class Node {
460      friend class SmartBpUGraphBase;
461    protected:
462      int id;
463
464      Node(int _id) : id(_id) {}
465    public:
466      Node() {}
467      Node(Invalid) { id = -1; }
468      bool operator==(const Node i) const {return id==i.id;}
469      bool operator!=(const Node i) const {return id!=i.id;}
470      bool operator<(const Node i) const {return id<i.id;}
471    };
472
473    class UEdge {
474      friend class SmartBpUGraphBase;
475    protected:
476      int id;
477
478      UEdge(int _id) { id = _id;}
479    public:
480      UEdge() {}
481      UEdge (Invalid) { id = -1; }
482      bool operator==(const UEdge i) const {return id==i.id;}
483      bool operator!=(const UEdge i) const {return id!=i.id;}
484      bool operator<(const UEdge i) const {return id<i.id;}
485    };
486
487    void firstANode(Node& node) const {
488      node.id = 2 * aNodes.size() - 2;
489      if (node.id < 0) node.id = -1;
490    }
491    void nextANode(Node& node) const {
492      node.id -= 2;
493      if (node.id < 0) node.id = -1;
494    }
495
496    void firstBNode(Node& node) const {
497      node.id = 2 * bNodes.size() - 1;
498    }
499    void nextBNode(Node& node) const {
500      node.id -= 2;
501    }
502
503    void first(Node& node) const {
504      if (aNodes.size() > 0) {
505        node.id = 2 * aNodes.size() - 2;
506      } else {
507        node.id = 2 * bNodes.size() - 1;
508      }
509    }
510    void next(Node& node) const {
511      node.id -= 2;
512      if (node.id == -2) {
513        node.id = 2 * bNodes.size() - 1;
514      }
515    }
516 
517    void first(UEdge& edge) const {
518      edge.id = edges.size() - 1;
519    }
520    void next(UEdge& edge) const {
521      --edge.id;
522    }
523
524    void firstFromANode(UEdge& edge, const Node& node) const {
525      LEMON_ASSERT((node.id & 1) == 0, NodeSetError());
526      edge.id = aNodes[node.id >> 1].first;
527    }
528    void nextFromANode(UEdge& edge) const {
529      edge.id = edges[edge.id].next_out;
530    }
531
532    void firstFromBNode(UEdge& edge, const Node& node) const {
533      LEMON_ASSERT((node.id & 1) == 1, NodeSetError());
534      edge.id = bNodes[node.id >> 1].first;
535    }
536    void nextFromBNode(UEdge& edge) const {
537      edge.id = edges[edge.id].next_in;
538    }
539
540    static int id(const Node& node) {
541      return node.id;
542    }
543    static Node nodeFromId(int id) {
544      return Node(id);
545    }
546    int maxNodeId() const {
547      return aNodes.size() > bNodes.size() ?
548        aNodes.size() * 2 - 2 : bNodes.size() * 2 - 1;
549    }
550 
551    static int id(const UEdge& edge) {
552      return edge.id;
553    }
554    static UEdge uEdgeFromId(int id) {
555      return UEdge(id);
556    }
557    int maxUEdgeId() const {
558      return edges.size();
559    }
560 
561    static int aNodeId(const Node& node) {
562      return node.id >> 1;
563    }
564    static Node fromANodeId(int id) {
565      return Node(id << 1);
566    }
567    int maxANodeId() const {
568      return aNodes.size();
569    }
570
571    static int bNodeId(const Node& node) {
572      return node.id >> 1;
573    }
574    static Node fromBNodeId(int id) {
575      return Node((id << 1) + 1);
576    }
577    int maxBNodeId() const {
578      return bNodes.size();
579    }
580
581    Node aNode(const UEdge& edge) const {
582      return Node(edges[edge.id].aNode);
583    }
584    Node bNode(const UEdge& edge) const {
585      return Node(edges[edge.id].bNode);
586    }
587
588    static bool aNode(const Node& node) {
589      return (node.id & 1) == 0;
590    }
591
592    static bool bNode(const Node& node) {
593      return (node.id & 1) == 1;
594    }
595
596    Node addANode() {
597      NodeT nodeT;
598      nodeT.first = -1;
599      aNodes.push_back(nodeT);
600      return Node(aNodes.size() * 2 - 2);
601    }
602
603    Node addBNode() {
604      NodeT nodeT;
605      nodeT.first = -1;
606      bNodes.push_back(nodeT);
607      return Node(bNodes.size() * 2 - 1);
608    }
609
610    UEdge addEdge(const Node& source, const Node& target) {
611      LEMON_ASSERT(((source.id ^ target.id) & 1) == 1, NodeSetError());
612      UEdgeT edgeT;
613      if ((source.id & 1) == 0) {
614        edgeT.aNode = source.id;
615        edgeT.bNode = target.id;
616      } else {
617        edgeT.aNode = target.id;
618        edgeT.bNode = source.id;
619      }
620      edgeT.next_out = aNodes[edgeT.aNode >> 1].first;
621      aNodes[edgeT.aNode >> 1].first = edges.size();
622      edgeT.next_in = bNodes[edgeT.bNode >> 1].first;
623      bNodes[edgeT.bNode >> 1].first = edges.size();
624      edges.push_back(edgeT);
625      return UEdge(edges.size() - 1);
626    }
627
628    void clear() {
629      aNodes.clear();
630      bNodes.clear();
631      edges.clear();
632    }
633
634    typedef True NodeNumTag;
635    int nodeNum() const { return aNodes.size() + bNodes.size(); }
636    int aNodeNum() const { return aNodes.size(); }
637    int bNodeNum() const { return bNodes.size(); }
638
639    typedef True EdgeNumTag;
640    int uEdgeNum() const { return edges.size(); }
641
642  };
643
644
645  typedef BpUGraphExtender<SmartBpUGraphBase> ExtendedSmartBpUGraphBase;
646
647  /// \ingroup graphs
648  ///
649  /// \brief A smart bipartite undirected graph class.
650  ///
651  /// This is a simple and fast bipartite undirected graph implementation.
652  /// It is also quite memory efficient, but at the price
653  /// that <b> it does not support node and edge deletions</b>.
654  /// Except from this it conforms to
655  /// the \ref concept::BpUGraph "BpUGraph concept".
656  /// \sa concept::BpUGraph.
657  ///
658  class SmartBpUGraph : public ExtendedSmartBpUGraphBase {};
659
660 
661  /// @} 
662} //namespace lemon
663
664
665#endif //LEMON_SMART_GRAPH_H
Note: See TracBrowser for help on using the repository browser.