-5

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?

Bob Billy
  • 285
  • 1
  • 6
  • To whomever is downvoting all of my questions: Why? – Bob Billy Apr 02 '16 at 21:09
  • 3
    Stop copy/paste the problems someone asked you to solve, try to answer them, and if you can't show us where you failed. It's SO, not "We do your work". – FiReTiTi Apr 02 '16 at 21:21
  • I believe I have showed you where I failed. I said I used BFS and DFS, but they were too slow. I just want to know what the most efficient way of doing this is. – Bob Billy Apr 03 '16 at 19:35

1 Answers1

0

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.

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75