jayati

Minimum Spanning Tree

Oct 27th, 2023
831
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution
  7. {
  8.     public:
  9.     //Function to find sum of weights of edges of the Minimum Spanning Tree.
  10.     int spanningTree(int V, vector<vector<int>> adj[])
  11.     {
  12.         priority_queue<pair<int, int>,vector<pair<int, int> >, greater<pair<int, int>>> pq;
  13.  
  14.         vector<int> vis(V, 0);
  15.         // {wt, node}
  16.         pq.push({0, 0});
  17.         int sum = 0;
  18.         while (!pq.empty()) {
  19.             auto it = pq.top();
  20.             pq.pop();
  21.             int node = it.second;
  22.             int wt = it.first;
  23.  
  24.             if (vis[node] == 1) continue;
  25.             // add it to the mst
  26.             vis[node] = 1;
  27.             sum += wt;
  28.             for (auto it : adj[node]) {
  29.                 int adjNode = it[0];
  30.                 int edW = it[1];
  31.                 if (!vis[adjNode]) {
  32.                     pq.push({edW, adjNode});
  33.                 }
  34.             }
  35.         }
  36.         return sum;
  37.     }
  38. };
  39.  
  40. //{ Driver Code Starts.
  41.  
  42.  
  43. int main()
  44. {
  45.     int t;
  46.     cin >> t;
  47.     while (t--) {
  48.         int V, E;
  49.         cin >> V >> E;
  50.         vector<vector<int>> adj[V];
  51.         int i=0;
  52.         while (i++<E) {
  53.             int u, v, w;
  54.             cin >> u >> v >> w;
  55.             vector<int> t1,t2;
  56.             t1.push_back(v);
  57.             t1.push_back(w);
  58.             adj[u].push_back(t1);
  59.             t2.push_back(u);
  60.             t2.push_back(w);
  61.             adj[v].push_back(t2);
  62.         }
  63.        
  64.         Solution obj;
  65.         cout << obj.spanningTree(V, adj) << "\n";
  66.     }
  67.  
  68.     return 0;
  69. }
  70.  
  71.  
  72. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment