// Initialize resultmst_weight =0// Create V single item setsfor each vertex vparent[v] = v;rank[v] =0;Sort all edges into non decreasing order by weight wforeach (u, v) taken from the sorted list Edoif FIND-SET(u) != FIND-SET(v)printedge(u,v) mst_weight += weight of edge(u, v)UNION(u, v)
Code:
#include<bits/stdc++.h>usingnamespace std;intfindPar(vector<int> &parent,int node){if (parent[node] ==-1) {return node; }parent[node] =findPar(parent,parent[node]);returnparent[node];}voiduni(vector<int> &parent,vector<int> &rank,int a,int b){int parA =findPar(parent, a);int parB =findPar(parent, b);if (parA != parB) {if (rank[parA] >rank[parB]) {parent[parB] = parA; }elseif (rank[parB] >rank[parA]) {parent[parA] = parB; }else {parent[parA] = parB;rank[parB]++; } }return;}intmain(){int n, m; cin >> n >> m; vector< pair<int, pair<int,int>>> v; vector<int>parent(n +1,-1); vector<int>rank(n +1,0);for (int k =1; k <= m; k++) {int a, b, w; cin >> a >> b >> w;v.push_back({w, {a, b}}); }sort(v.begin(),v.end());int minWeight =0;for (auto itr =v.begin(); itr !=v.end(); itr++) { pair<int,int> p =itr->second;int x =p.first;int y =p.second;int pa =findPar(parent,x);int py =findPar(parent,y);if (pa != py) {uni(parent, rank, x, y); minWeight = minWeight +itr->first; } } cout << minWeight;return0;}
Time Complexity: O(E logE) or O(E logV). Sorting of edges takes O(E Log E) time. After sorting, we iterate through all edges and apply find-union algorithm. The find and union operations can take atmost O(LogV) time. So overall complexity is O(E Log E + E Log V) time.