Search code examples
algorithmgraphgraph-theoryminimum-spanning-tree

how to find MST after add new node?


How we find MST (Minimum Spanning Tree) after add new node or change distance of ways?

I need help to solve this. Can anybody help me?

Thanks.


Solution

  • When adding new edges:

    You will need to perform a graph traversal, the easiest is DFS for this, from one of the sides of the modified/new edge. If you can back to a node you were to before, you have a cycle.

    In that cycle, you will need to remove the largest edge. You will get a tree again, and it is the minimal spanning one.

    If you are changing edge weights, you will need to:

    • Disconnect the graph into 2 components, A and B, by temporarily removing the new edge.
    • If the new edge has a smaller weight than before, you can put it back in. Otherwise:
    • Iterate through edges that you have processed before, and check if they join A to B.
    • Pick the smallest edge from those, and connect the components using that edge.

    Again, you get a new minimal spanning tree.

    Overall, this is O(V+E), times a small factor of inverse Ackermann.