Minimum Spanning Tree | Practice | GeeksforGeeks

Given a weighted, undirected and connected graph of V vertices and E edges. The task is to find the sum of weights of the edges of the Minimum Spanning Tree.
 
Example 1:
Input:

Output:
4
Explanation:

The Spanning Tree resulting in a weight
of 4 is shown above.

Example 2:
Input:

Output:
5
Explanation:
Only one Spanning Tree is possible
which has a weight of 5.

 
Your task:
Since this is a functional problem you don't have to worry about input, you just have to complete the function  spanningTree() which takes number of vertices V and an adjacency matrix adj as input parameters and returns an integer denoting the sum of weights of the edges of the Minimum Spanning Tree. Here adj[i] contains a list of lists containing two integers where the first integer a[i][0] denotes that there is an edge between i and a[i][0] and second integer a[i][1] denotes that the distance between edge i and a[i][0] is a[i][1].
Expected Time Complexity: O(ElogV).
Expected Auxiliary Space: O(V2).
 
Constraints:
2  ≤  V ≤  1000
V-1 ≤  E  ≤  (V*(V-1))/2
1  ≤  w  ≤  1000
Graph is connected and doesn't contain self loops & multiple edges.
0
amishasahu3285 days ago
struct node
{
    public:
    int u, v, wt;
    node(int first, int second, int weight){
        u = first;
        v = second;
        wt = weight;
    }
};
class Solution
{
int findPar(int u, vector<int> &parent) {
        if(u == parent[u]) return u; 
        // path compression
        return parent[u] = findPar(parent[u], parent); 
    }
    
    void unionn(int u, int v, vector<int> &parent, vector<int> &rank) {
        u = findPar(u, parent);
        v = findPar(v, parent);
        if(rank[u] < rank[v]) {
        	parent[u] = v;
        }
        else if(rank[v] < rank[u]) {
        	parent[v] = u; 
        }
        else { // attach any to any and just inc the rank of node to which attached
        	parent[v] = u;
        	rank[u]++; 
        }
    }
    static bool cmp(node &a, node &b){
        return a.wt < b.wt;
    }
    public:
    int spanningTree(int V, vector<vector<int>> adj[])
    {
        int cost = 0;
        vector<int> rank(V, 0);
        vector<int> parent(V);
        vector<pair<int,int>> mstSet;
        for(int i = 0; i < V; i++)
            parent[i] = i;
            
            
        vector<node> edges;
        for(int i = 0; i < V; i++){
            for(auto vec: adj[i]){
                edges.push_back(node(i, vec[0], vec[1]));
            }
        }
    
            
        sort(edges.begin(), edges.end(), cmp);
      
        for(auto it: edges){
            if(findPar(it.u,parent) != findPar(it.v,parent)){
                mstSet.push_back(make_pair(it.u,it.v));
                unionn(it.u, it.v, parent, rank);
                cost += it.wt;
            }
        }
        return cost;
    }
};
0
amishasahu3281 week ago
int spanningTree(int V, vector<vector<int>> adj[])
    {
        // code here
        vector<int> parent(V, -1);
        vector<bool> mst(V, false);
        vector<int> key(V, INT_MAX);
        
        key[0] = 0;
        parent[0] = -1;
        
        priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int, int>>> pq;
        pq.push({0,0}); // node 0 and its key value -> 0
        
     
        while(!pq.empty())
        {
            int u = pq.top().second;
            pq.pop();
            
            mst[u] = true;
            for(auto it: adj[u])
            {
                int v = it[0];
                int wt = it[1];
                if(mst[v] == false && wt < key[v])
                {
                    key[v] = wt;
                    parent[v] = u;
                    pq.push({key[v], v});
                }
            }
        }
        
        int sum = accumulate(key.begin(), key.end(), 0LL);
        return sum;
    }
0
itsmemritu1 week ago
    int spanningTree(int V, vector<vector<int>> adj[])   {       // code here       int ans=0;       priority_queue<pii,vector<pii>,greater<pii>>pq;       vector<bool>visited(V,false);       pq.push({0,0});       while(!pq.empty()){          int k=pq.top().second;          int t=pq.top().first;          pq.pop();          if(visited[k]){              continue;          }          ans+=t;          visited[k]=true;          for(auto it:adj[k]){              int weight=it[1];              int v=it[0];              if(!visited[v]){                  pq.push({weight,v});              }          }       }       return ans;   }
0
sunboykenneth1 week ago
class Solution
{
	public:
	//Function to find sum of weights of edges of the Minimum Spanning Tree.
    int spanningTree(int V, vector<vector<int>> adj[])
    {
        if (V < 2) {
            return 0;
        }
        
        vector<int> spanningTreeDistances(V, INT_MAX);
        vector<int> inSpanningTree(V, false);
        spanningTreeDistances[0] = 0;
        int minSpanningTreeWeight = 0;
        
        while (true) {
            // Find the node which is not in MST yet and with minimum distance to MST
            int minDist = INT_MAX, minNode = -1;
            for (int i = 0; i < V; i++) {
                if (inSpanningTree[i]) {
                    continue;
                }
                
                if (spanningTreeDistances[i] < minDist) {
                    minDist = spanningTreeDistances[i];
                    minNode = i;
                }
            }
            
            if (minNode == -1) {
                break;
            }
            
            minSpanningTreeWeight += minDist;
            inSpanningTree[minNode] = true;
            
            // Update adjNodes
            vector<vector<int>> &adjNodes = adj[minNode];
            for (auto i = adjNodes.begin(); i != adjNodes.end(); i++) {
                vector<int> &curAdjNode = *i;
                int adjNode = curAdjNode[0];
                int weight = curAdjNode[1];
                
                if (inSpanningTree[adjNode]) {
                    continue;
                }
                
                if (weight < spanningTreeDistances[adjNode]) {
                    spanningTreeDistances[adjNode] = weight;
                }
            }
        }
        
        return minSpanningTreeWeight;
    }
};
+1
mayank963k2 weeks ago
class Solution
{
	public:
    int spanningTree(int V, vector<vector<int>> adj[])
    {   
        vector<int> dist(V, INT_MAX);
        vector<bool> mstSet(V, false);
        vector<int> parent(V, -1);
        
        dist[0] = 0;
        
        priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
        pq.push({0, 0});  //DIst, Src;
        
        while(!pq.empty())
        {
            int u = pq.top().second;
            pq.pop();
            
            if(mstSet[u] == true) continue;
            mstSet[u] = true;
            
            for(auto x:adj[u])
            {
                int v = x[0];
                int weight = x[1];
                
                if(mstSet[v] == false && weight < dist[v])
                {   
                    dist[v] = weight;
                    parent[v] = u;
                    pq.push({dist[v], v});
                }
            }
        }
        
        return accumulate(dist.begin(), dist.end(), 0);
        
    }
};
0
19bcs13143 weeks ago
class Pair implements Comparable<Pair>{
    int res;
    int v;
    Pair(int i,int res){
        this.v=i;
        this.res=res;
    }
    public int compareTo(Pair obj){
        return this.res-obj.res;
    }
}


class Solution
{
    //Function to find sum of weights of edges of the Minimum Spanning Tree.
    static int spanningTree(int v, ArrayList<ArrayList<ArrayList<Integer>>> adj) 
    {
        // Add your code here
        boolean[] visit=new boolean[v];
        PriorityQueue<Pair> q=new PriorityQueue<>();
        q.add(new Pair(0,0));
        int ans=0;
        while(q.size()!=0){
            Pair temp=q.remove();
            
            int u=temp.v;
            if(visit[u]==true){
                continue;
            }
            ans+=temp.res;
            visit[u]=true;
            
            ArrayList<ArrayList<Integer>> l=adj.get(u);
            
            for(ArrayList<Integer> list:l){
                int vertex=list.get(0);
                int wt=list.get(1);
                if(visit[vertex]==false){
                    q.add(new Pair(vertex,wt));
                }
            }
        }
        return ans;
    }
}
0
ar44429883 weeks ago
// { Driver Code Starts#include<bits/stdc++.h>using namespace std;
// } Driver Code Ends
class Solution{public:int findpar(int u,vector<int> &parent){    if(u==parent[u])    {        return u;    }    return parent[u]=findpar(parent[u],parent);}void unite(int u,int v,vector<int> &parent,vector<int> &rank){    u=findpar(u,parent);    v=findpar(v,parent);    parent[v]=u;}//Function to find sum of weights of edges of the Minimum Spanning Tree.   int spanningTree(int V, vector<vector<int>> adj[])   {       int cost=0;       priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> minh;              vector<int> parent(V);       vector<int> rank(V);       for(int i=0;i<V;i++)       {           parent[i]=i;           rank[i]=0;       }       for(int i=0;i<V;i++)       {           for(auto it:adj[i])           {               minh.push({it[1],{i,it[0]}});           }       }       while(!minh.empty())       {           int wt=minh.top().first;           int u=minh.top().second.first;           int v=minh.top().second.second;           minh.pop();           if(findpar(u,parent)!=findpar(v,parent))           {               unite(u,v,parent,rank);               cost+=wt;           }       }       return cost;   }};
// { Driver Code Starts.
int main(){   int t;   cin >> t;   while (t--) {       int V, E;       cin >> V >> E;       vector<vector<int>> adj[V];       int i=0;       while (i++<E) {           int u, v, w;           cin >> u >> v >> w;           vector<int> t1,t2;           t1.push_back(v);           t1.push_back(w);           adj[u].push_back(t1);           t2.push_back(u);           t2.push_back(w);           adj[v].push_back(t2);       }              Solution obj;    cout << obj.spanningTree(V, adj) << "\n";   }
   return 0;}
 // } Driver Code Ends
+1
rohitshinde1803011 month ago
class Solution{   int* parent;   int* rank;
public:void DSU(int n){       parent = new int[n];       rank = new int[n];       for (int i = 0; i < n; i++) {           parent[i] = -1;           rank[i] = 1;       }   }      int find(int i){       if (parent[i] == -1)           return i;       return parent[i] = find(parent[i]);   }       void unite(int x, int y, int s1, int s2){       if (rank[s1] < rank[s2]) {           parent[s1] = s2;           rank[s2] += rank[s1];       }       else{           parent[s2] = s1;           rank[s1] += rank[s2];       }   }
   //Function to find sum of weights of edges of the Minimum Spanning Tree.   int spanningTree(int V, vector<vector<int>> adj[])   {       // code here       vector<vector<int>> edgelist;       for(int i=0;i<V;i++){           for(auto j:adj[i]){              edgelist.push_back({j[1],i,j[0]});           }       }       sort(edgelist.begin(), edgelist.end());       DSU (V);       int ans=0;       for (auto edge : edgelist) {           int w = edge[0];           int x = edge[1];           int y = edge[2];           int s1 = find(x);           int s2 = find(y);           if (s1 != s2){               unite(x,y,s1,s2);               ans += w;           }       }       return ans;   }};
 
0
nehamittal8561 month ago
static int findMin(int weight[],boolean[] mstSet){       int min = Integer.MAX_VALUE;       int min_index=-1;       for(int i=0;i<mstSet.length;i++){           if(!mstSet[i] && min>weight[i]){               min = weight[i];               min_index = i;           }       }       return min_index;   }   //Function to find sum of weights of edges of the Minimum Spanning Tree.   static int spanningTree(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj)    {      int[] weight = new int[V];      boolean[] mstSet = new boolean[V];      int[] parent = new int[V];            Arrays.fill(mstSet,false);            for(int i=1;i<V;i++){          weight[i] = Integer.MAX_VALUE;      }      weight[0] = 0;      parent[0] = -1;            for(int i=0;i<V;i++){          int u= findMin(weight,mstSet);          mstSet[u] = true;         for(ArrayList<Integer> x: adj.get(u)){             if(!mstSet[x.get(0)]){                  if(x.get(1)<weight[x.get(0)]){                 weight[x.get(0)] = x.get(1);                 parent[x.get(0)] = u;              }             }                                 }      }      int total_weight = 0;      for(int i=0;i<V;i++){          total_weight+=weight[i];      }            return total_weight;         }
0
aaishuagarwal1 month ago
int spanningTree(int v, vector<vector<int>> adj[])   {       // code here       vector<int>key(v,INT_MAX);       vector<bool>mst(v,false);       priority_queue<pii,vector<pii>,greater<pii>>pq;       pq.push({0,0});       mst[0]=true;       key[0]=0;       while(!pq.empty())       {           int u=pq.top().second;           pq.pop();           mst[u]=true;           for(auto p:adj[u])           {               int w=p[1];               int v=p[0];               if(!mst[v])               {                   if(key[v]>w)                   {                       key[v]=w;                       pq.push({key[v],v});                   }               }           }       }       int w=0;       for(auto x:key)       {           w+=x;       }       return w;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.