VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-weight-of-the-minimum-spanning-tree/

⇱ Find the weight of the minimum spanning tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the weight of the minimum spanning tree

Last Updated : 11 Jul, 2025

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: 

  1. query(1) -> Find the weight of the minimum spanning tree.
  2. query(2, x, y) -> Change the weight of the edge between the nodes x and y to 0.
  3. query(3, x, y) -> Restore the weight of the edge between the nodes x and y to its original weight.


Examples:

Input:

👁 Image


query(2, 1, 2), 
query(1), 
query(3, 1, 2), 
query(1) 
Output:

3
Input:

👁 Image


query(1), 
query(2, 3, 4), 
query(1) 
Output :




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:


Output
2
3

Time Complexity: O(N) per query, where N is the total number of nodes in the graph.
Auxiliary Space: O(N) 

Comment