Given a connected undirected weighted graph with N nodes and M edges. The task is to perform given queries and find the weight of the minimum spanning tree. Queries are of three types:
- query(1) -> Find the weight of the minimum spanning tree.
- query(2, x, y) -> Change the weight of the edge between the nodes x and y to 0.
- query(3, x, y) -> Restore the weight of the edge between the nodes x and y to its original weight.
query(2, 1, 2),
query(3, 1, 2),
query(2, 3, 4),
Approach: Let’s first compute MST of the initial graph before performing any queries and let T be this MST. The crucial observation is that at any point while handling the queries, the weight of the MST of the current graph can be computed by running Kruskal’s algorithm on edges with zero weight at this point and edges of T. So, keep edges with weight zero in a data structure and after query of type 2 and type 3 compute weight of minimum spanning tree.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.