简体   繁体   中英

Graph theory puzzle about connectivity?

You have a graph of n nodes (numbered 1-n) and m edges. You remove all the nodes one by one, and at each step you check if the graph is fully connected or not (by printing "connected" or not). The order of the nodes to be removed is given.

For example,

n = 4 and m = 3 The edges given are: 1 - 2, 2 - 3, 3 - 4. The removal order is: 3, 4, 1, 2

The nodes are numbered 1-n, so the nodes in this case are 1, 2, 3, 4.

Initially, the graph is connected, so you print out:

Connected

You first remove node 3. Now the graph is disconnected because node 4 is alone.

Disconnected

Then you remove node 4. Now the graph is composed of only nodes 1 and 2, which are connected.

Connected

Then you remove node 1. The graph is still considered connected; there is only one node.

Connected

Then you remove node 2. There is nothing left.

Sample code would be helpful, preferably java or c++. I tried using BFS and DFS, but they were too slow. What is the most efficient way to do this?

Try working in reverse order.

Add the edges one by one and use a disjoint set data structure to find when the set becomes connected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM