3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_SMART_GRAPH_H
20 #define LEMON_SMART_GRAPH_H
24 ///\brief SmartDigraph and SmartGraph classes.
28 #include <lemon/bits/invalid.h>
30 #include <lemon/bits/base_extender.h>
31 #include <lemon/bits/graph_extender.h>
33 #include <lemon/bits/utility.h>
34 #include <lemon/error.h>
36 #include <lemon/bits/graph_extender.h>
41 ///Base of SmartDigraph
43 ///Base of SmartDigraph
45 class SmartDigraphBase {
50 int first_in, first_out;
55 int target, source, next_in, next_out;
59 std::vector<NodeT> nodes;
60 std::vector<ArcT> arcs;
64 typedef SmartDigraphBase Graph;
71 SmartDigraphBase() : nodes(), arcs() { }
72 SmartDigraphBase(const SmartDigraphBase &_g)
73 : nodes(_g.nodes), arcs(_g.arcs) { }
75 typedef True NodeNumTag;
76 typedef True EdgeNumTag;
78 int nodeNum() const { return nodes.size(); }
79 int arcNum() const { return arcs.size(); }
81 int maxNodeId() const { return nodes.size()-1; }
82 int maxArcId() const { return arcs.size()-1; }
86 nodes.push_back(NodeT());
87 nodes[n].first_in = -1;
88 nodes[n].first_out = -1;
92 Arc addArc(Node u, Node v) {
94 arcs.push_back(ArcT());
95 arcs[n].source = u._id;
96 arcs[n].target = v._id;
97 arcs[n].next_out = nodes[u._id].first_out;
98 arcs[n].next_in = nodes[v._id].first_in;
99 nodes[u._id].first_out = nodes[v._id].first_in = n;
109 Node source(Arc a) const { return Node(arcs[a._id].source); }
110 Node target(Arc a) const { return Node(arcs[a._id].target); }
112 static int id(Node v) { return v._id; }
113 static int id(Arc a) { return a._id; }
115 static Node nodeFromId(int id) { return Node(id);}
116 static Arc arcFromId(int id) { return Arc(id);}
118 bool valid(Node n) const {
119 return n._id >= 0 && n._id < static_cast<int>(nodes.size());
121 bool valid(Arc a) const {
122 return a._id >= 0 && a._id < static_cast<int>(arcs.size());
126 friend class SmartDigraphBase;
127 friend class SmartDigraph;
131 explicit Node(int id) : _id(id) {}
134 Node (Invalid) : _id(-1) {}
135 bool operator==(const Node i) const {return _id == i._id;}
136 bool operator!=(const Node i) const {return _id != i._id;}
137 bool operator<(const Node i) const {return _id < i._id;}
142 friend class SmartDigraphBase;
143 friend class SmartDigraph;
147 explicit Arc(int id) : _id(id) {}
150 Arc (Invalid) : _id(-1) {}
151 bool operator==(const Arc i) const {return _id == i._id;}
152 bool operator!=(const Arc i) const {return _id != i._id;}
153 bool operator<(const Arc i) const {return _id < i._id;}
156 void first(Node& node) const {
157 node._id = nodes.size() - 1;
160 static void next(Node& node) {
164 void first(Arc& arc) const {
165 arc._id = arcs.size() - 1;
168 static void next(Arc& arc) {
172 void firstOut(Arc& arc, const Node& node) const {
173 arc._id = nodes[node._id].first_out;
176 void nextOut(Arc& arc) const {
177 arc._id = arcs[arc._id].next_out;
180 void firstIn(Arc& arc, const Node& node) const {
181 arc._id = nodes[node._id].first_in;
184 void nextIn(Arc& arc) const {
185 arc._id = arcs[arc._id].next_in;
190 typedef DigraphExtender<SmartDigraphBase> ExtendedSmartDigraphBase;
194 ///\brief A smart directed graph class.
196 ///This is a simple and fast digraph implementation.
197 ///It is also quite memory efficient, but at the price
198 ///that <b> it does support only limited (only stack-like)
199 ///node and arc deletions</b>.
200 ///It conforms to the \ref concepts::Digraph "Digraph concept" with
201 ///an important extra feature that its maps are real \ref
202 ///concepts::ReferenceMap "reference map"s.
204 ///\sa concepts::Digraph.
206 ///\author Alpar Juttner
207 class SmartDigraph : public ExtendedSmartDigraphBase {
210 typedef ExtendedSmartDigraphBase Parent;
214 ///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead.
216 ///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead.
218 SmartDigraph(const SmartDigraph &) : ExtendedSmartDigraphBase() {};
219 ///\brief Assignment of SmartDigraph to another one is \e not allowed.
220 ///Use DigraphCopy() instead.
222 ///Assignment of SmartDigraph to another one is \e not allowed.
223 ///Use DigraphCopy() instead.
224 void operator=(const SmartDigraph &) {}
234 ///Add a new node to the digraph.
236 /// \return the new node.
238 Node addNode() { return Parent::addNode(); }
240 ///Add a new arc to the digraph.
242 ///Add a new arc to the digraph with source node \c s
243 ///and target node \c t.
244 ///\return the new arc.
245 Arc addArc(const Node& s, const Node& t) {
246 return Parent::addArc(s, t);
249 /// \brief Using this it is possible to avoid the superfluous memory
252 /// Using this it is possible to avoid the superfluous memory
253 /// allocation: if you know that the digraph you want to build will
254 /// be very large (e.g. it will contain millions of nodes and/or arcs)
255 /// then it is worth reserving space for this amount before starting
256 /// to build the digraph.
258 void reserveNode(int n) { nodes.reserve(n); };
260 /// \brief Using this it is possible to avoid the superfluous memory
263 /// Using this it is possible to avoid the superfluous memory
264 /// allocation: if you know that the digraph you want to build will
265 /// be very large (e.g. it will contain millions of nodes and/or arcs)
266 /// then it is worth reserving space for this amount before starting
267 /// to build the digraph.
269 void reserveArc(int m) { arcs.reserve(m); };
271 /// \brief Node validity check
273 /// This function gives back true if the given node is valid,
274 /// ie. it is a real node of the graph.
276 /// \warning A removed node (using Snapshot) could become valid again
277 /// when new nodes are added to the graph.
278 bool valid(Node n) const { return Parent::valid(n); }
280 /// \brief Arc validity check
282 /// This function gives back true if the given arc is valid,
283 /// ie. it is a real arc of the graph.
285 /// \warning A removed arc (using Snapshot) could become valid again
286 /// when new arcs are added to the graph.
287 bool valid(Arc a) const { return Parent::valid(a); }
289 ///Clear the digraph.
291 ///Erase all the nodes and arcs from the digraph.
299 ///This function splits a node. First a new node is added to the digraph,
300 ///then the source of each outgoing arc of \c n is moved to this new node.
301 ///If \c connect is \c true (this is the default value), then a new arc
302 ///from \c n to the newly created node is also added.
303 ///\return The newly created node.
305 ///\note The <tt>Arc</tt>s
306 ///referencing a moved arc remain
307 ///valid. However <tt>InArc</tt>'s and <tt>OutArc</tt>'s
308 ///may be invalidated.
309 ///\warning This functionality cannot be used together with the Snapshot
311 ///\todo It could be implemented in a bit faster way.
312 Node split(Node n, bool connect = true)
315 nodes[b._id].first_out=nodes[n._id].first_out;
316 nodes[n._id].first_out=-1;
317 for(int i=nodes[b._id].first_out;i!=-1;i++) arcs[i].source=b._id;
318 if(connect) addArc(n,b);
328 void restoreSnapshot(const Snapshot &s)
330 while(s.arc_num<arcs.size()) {
331 Arc arc = arcFromId(arcs.size()-1);
332 Parent::notifier(Arc()).erase(arc);
333 nodes[arcs.back().source].first_out=arcs.back().next_out;
334 nodes[arcs.back().target].first_in=arcs.back().next_in;
337 while(s.node_num<nodes.size()) {
338 Node node = nodeFromId(nodes.size()-1);
339 Parent::notifier(Node()).erase(node);
346 ///Class to make a snapshot of the digraph and to restrore to it later.
348 ///Class to make a snapshot of the digraph and to restrore to it later.
350 ///The newly added nodes and arcs can be removed using the
351 ///restore() function.
352 ///\note After you restore a state, you cannot restore
353 ///a later state, in other word you cannot add again the arcs deleted
354 ///by restore() using another one Snapshot instance.
356 ///\warning If you do not use correctly the snapshot that can cause
357 ///either broken program, invalid state of the digraph, valid but
358 ///not the restored digraph or no change. Because the runtime performance
359 ///the validity of the snapshot is not stored.
362 SmartDigraph *_graph;
364 friend class SmartDigraph;
365 unsigned int node_num;
366 unsigned int arc_num;
368 ///Default constructor.
370 ///Default constructor.
371 ///To actually make a snapshot you must call save().
373 Snapshot() : _graph(0) {}
374 ///Constructor that immediately makes a snapshot
376 ///This constructor immediately makes a snapshot of the digraph.
377 ///\param _g The digraph we make a snapshot of.
378 Snapshot(SmartDigraph &graph) : _graph(&graph) {
379 node_num=_graph->nodes.size();
380 arc_num=_graph->arcs.size();
385 ///Make a snapshot of the digraph.
387 ///This function can be called more than once. In case of a repeated
388 ///call, the previous snapshot gets lost.
389 ///\param _g The digraph we make the snapshot of.
390 void save(SmartDigraph &graph)
393 node_num=_graph->nodes.size();
394 arc_num=_graph->arcs.size();
397 ///Undo the changes until a snapshot.
399 ///Undo the changes until a snapshot created by save().
401 ///\note After you restored a state, you cannot restore
402 ///a later state, in other word you cannot add again the arcs deleted
406 _graph->restoreSnapshot(*this);
412 class SmartGraphBase {
425 std::vector<NodeT> nodes;
426 std::vector<ArcT> arcs;
432 typedef SmartGraphBase Digraph;
439 friend class SmartGraphBase;
443 explicit Node(int id) { _id = id;}
447 Node (Invalid) { _id = -1; }
448 bool operator==(const Node& node) const {return _id == node._id;}
449 bool operator!=(const Node& node) const {return _id != node._id;}
450 bool operator<(const Node& node) const {return _id < node._id;}
454 friend class SmartGraphBase;
458 explicit Edge(int id) { _id = id;}
462 Edge (Invalid) { _id = -1; }
463 bool operator==(const Edge& arc) const {return _id == arc._id;}
464 bool operator!=(const Edge& arc) const {return _id != arc._id;}
465 bool operator<(const Edge& arc) const {return _id < arc._id;}
469 friend class SmartGraphBase;
473 explicit Arc(int id) { _id = id;}
476 operator Edge() const { return edgeFromId(_id / 2); }
479 Arc (Invalid) { _id = -1; }
480 bool operator==(const Arc& arc) const {return _id == arc._id;}
481 bool operator!=(const Arc& arc) const {return _id != arc._id;}
482 bool operator<(const Arc& arc) const {return _id < arc._id;}
491 int maxNodeId() const { return nodes.size()-1; }
492 int maxEdgeId() const { return arcs.size() / 2 - 1; }
493 int maxArcId() const { return arcs.size()-1; }
495 Node source(Arc e) const { return Node(arcs[e._id ^ 1].target); }
496 Node target(Arc e) const { return Node(arcs[e._id].target); }
498 Node u(Edge e) const { return Node(arcs[2 * e._id].target); }
499 Node v(Edge e) const { return Node(arcs[2 * e._id + 1].target); }
501 static bool direction(Arc e) {
502 return (e._id & 1) == 1;
505 static Arc direct(Edge e, bool d) {
506 return Arc(e._id * 2 + (d ? 1 : 0));
509 void first(Node& node) const {
510 node._id = nodes.size() - 1;
513 void next(Node& node) const {
517 void first(Arc& arc) const {
518 arc._id = arcs.size() - 1;
521 void next(Arc& arc) const {
525 void first(Edge& arc) const {
526 arc._id = arcs.size() / 2 - 1;
529 void next(Edge& arc) const {
533 void firstOut(Arc &arc, const Node& v) const {
534 arc._id = nodes[v._id].first_out;
536 void nextOut(Arc &arc) const {
537 arc._id = arcs[arc._id].next_out;
540 void firstIn(Arc &arc, const Node& v) const {
541 arc._id = ((nodes[v._id].first_out) ^ 1);
542 if (arc._id == -2) arc._id = -1;
544 void nextIn(Arc &arc) const {
545 arc._id = ((arcs[arc._id ^ 1].next_out) ^ 1);
546 if (arc._id == -2) arc._id = -1;
549 void firstInc(Edge &arc, bool& d, const Node& v) const {
550 int de = nodes[v._id].first_out;
559 void nextInc(Edge &arc, bool& d) const {
560 int de = (arcs[(arc._id * 2) | (d ? 1 : 0)].next_out);
570 static int id(Node v) { return v._id; }
571 static int id(Arc e) { return e._id; }
572 static int id(Edge e) { return e._id; }
574 static Node nodeFromId(int id) { return Node(id);}
575 static Arc arcFromId(int id) { return Arc(id);}
576 static Edge edgeFromId(int id) { return Edge(id);}
578 bool valid(Node n) const {
579 return n._id >= 0 && n._id < static_cast<int>(nodes.size());
581 bool valid(Arc a) const {
582 return a._id >= 0 && a._id < static_cast<int>(arcs.size());
584 bool valid(Edge e) const {
585 return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size());
589 int n = nodes.size();
590 nodes.push_back(NodeT());
591 nodes[n].first_out = -1;
596 Edge addEdge(Node u, Node v) {
598 arcs.push_back(ArcT());
599 arcs.push_back(ArcT());
601 arcs[n].target = u._id;
602 arcs[n | 1].target = v._id;
604 arcs[n].next_out = nodes[v._id].first_out;
605 nodes[v._id].first_out = n;
607 arcs[n | 1].next_out = nodes[u._id].first_out;
608 nodes[u._id].first_out = (n | 1);
620 typedef GraphExtender<SmartGraphBase> ExtendedSmartGraphBase;
624 /// \brief A smart undirected graph class.
626 /// This is a simple and fast graph implementation.
627 /// It is also quite memory efficient, but at the price
628 /// that <b> it does support only limited (only stack-like)
629 /// node and arc deletions</b>.
630 /// Except from this it conforms to
631 /// the \ref concepts::Graph "Graph concept".
634 /// important extra feature that
635 /// its maps are real \ref concepts::ReferenceMap "reference map"s.
637 /// \sa concepts::Graph.
639 class SmartGraph : public ExtendedSmartGraphBase {
642 ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
644 ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
646 SmartGraph(const SmartGraph &) : ExtendedSmartGraphBase() {};
648 ///\brief Assignment of SmartGraph to another one is \e not allowed.
649 ///Use GraphCopy() instead.
651 ///Assignment of SmartGraph to another one is \e not allowed.
652 ///Use GraphCopy() instead.
653 void operator=(const SmartGraph &) {}
657 typedef ExtendedSmartGraphBase Parent;
665 ///Add a new node to the graph.
667 /// \return the new node.
669 Node addNode() { return Parent::addNode(); }
671 ///Add a new edge to the graph.
673 ///Add a new edge to the graph with node \c s
675 ///\return the new edge.
676 Edge addEdge(const Node& s, const Node& t) {
677 return Parent::addEdge(s, t);
680 /// \brief Node validity check
682 /// This function gives back true if the given node is valid,
683 /// ie. it is a real node of the graph.
685 /// \warning A removed node (using Snapshot) could become valid again
686 /// when new nodes are added to the graph.
687 bool valid(Node n) const { return Parent::valid(n); }
689 /// \brief Arc validity check
691 /// This function gives back true if the given arc is valid,
692 /// ie. it is a real arc of the graph.
694 /// \warning A removed arc (using Snapshot) could become valid again
695 /// when new edges are added to the graph.
696 bool valid(Arc a) const { return Parent::valid(a); }
698 /// \brief Edge validity check
700 /// This function gives back true if the given edge is valid,
701 /// ie. it is a real edge of the graph.
703 /// \warning A removed edge (using Snapshot) could become valid again
704 /// when new edges are added to the graph.
705 bool valid(Edge e) const { return Parent::valid(e); }
709 ///Erase all the nodes and edges from the graph.
721 void saveSnapshot(Snapshot &s)
724 s.node_num = nodes.size();
725 s.arc_num = arcs.size();
728 void restoreSnapshot(const Snapshot &s)
730 while(s.arc_num<arcs.size()) {
732 Edge arc=edgeFromId(n/2);
733 Parent::notifier(Edge()).erase(arc);
734 std::vector<Arc> dir;
735 dir.push_back(arcFromId(n));
736 dir.push_back(arcFromId(n-1));
737 Parent::notifier(Arc()).erase(dir);
738 nodes[arcs[n].target].first_out=arcs[n].next_out;
739 nodes[arcs[n-1].target].first_out=arcs[n-1].next_out;
743 while(s.node_num<nodes.size()) {
744 int n=nodes.size()-1;
745 Node node = nodeFromId(n);
746 Parent::notifier(Node()).erase(node);
753 ///Class to make a snapshot of the digraph and to restrore to it later.
755 ///Class to make a snapshot of the digraph and to restrore to it later.
757 ///The newly added nodes and arcs can be removed using the
758 ///restore() function.
760 ///\note After you restore a state, you cannot restore
761 ///a later state, in other word you cannot add again the arcs deleted
762 ///by restore() using another one Snapshot instance.
764 ///\warning If you do not use correctly the snapshot that can cause
765 ///either broken program, invalid state of the digraph, valid but
766 ///not the restored digraph or no change. Because the runtime performance
767 ///the validity of the snapshot is not stored.
772 friend class SmartGraph;
773 unsigned int node_num;
774 unsigned int arc_num;
776 ///Default constructor.
778 ///Default constructor.
779 ///To actually make a snapshot you must call save().
781 Snapshot() : _graph(0) {}
782 ///Constructor that immediately makes a snapshot
784 ///This constructor immediately makes a snapshot of the digraph.
785 ///\param g The digraph we make a snapshot of.
786 Snapshot(SmartGraph &graph) {
787 graph.saveSnapshot(*this);
792 ///Make a snapshot of the graph.
794 ///This function can be called more than once. In case of a repeated
795 ///call, the previous snapshot gets lost.
796 ///\param g The digraph we make the snapshot of.
797 void save(SmartGraph &graph)
799 graph.saveSnapshot(*this);
802 ///Undo the changes until a snapshot.
804 ///Undo the changes until a snapshot created by save().
806 ///\note After you restored a state, you cannot restore
807 ///a later state, in other word you cannot add again the arcs deleted
811 _graph->restoreSnapshot(*this);
819 #endif //LEMON_SMART_GRAPH_H