Assume that we have a set of n disjoint nodes {node1,node1,…,noden}
What is the fastest data structure and algorithm for the following 3 operations:
-
Union(x,y): add an un-directed edge between nodex and nodey, there can be at most one edge between two nodes.
-
IsConnected(x,y): returns true if nodex and nodey are connected directly or indirectly, i.e nodex and nodey are in the the same connected component.
-
Un-union(x,y): remove the edge between nodex and nodey if it exists.
Disjoint-set is a perfect data structure for the first two operations, but it cannot support the 3rd operation directly. What is the alternative?
If we simulate the process, the first and 3rd operations can be implemented in O(1) but 2nd operation is O(n), so I would like to see if it is possible to make all three operations run in O(logn) time or less.
Link/cut tree may perform these 3 operations in O(log N) time.
You can read about Link/cut tree and related data structures in this book: “Handbook of Data Structures and Applications” (Chapter 35).
Link/cut tree does not allow adding an edge between nodes, that are already (indirectly) connected. If you need “Union(x,y)” operation to support this, the problem becomes more complicated, and you can solve it as dynamic connectivity problem in undirected graphs. (See chapter 36.4 in the same book or this pdf). In this case insertion/deletion complexity increases to O(log2 N).