Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool cmp(vector<int>&a,vector<int>&b){
- return a[2]<b[2];
- }
- vector<int> parent, rank;
- void make_set(int x){
- parent[x] =x ;
- rank[x] = 0;
- }
- int find_set(int x){
- if(x == parent[x])return x;
- else parent[x] = find_set(parent[x]);
- }
- void union_set(int a, int b){
- a = find_set(a);
- b = find_set(b);
- if(a != b){
- if(rank[a] < rank[b]){
- parent[a] = b;
- }
- else if(rank[a]>rank[b]){
- parent[b]=a;
- }
- else{
- parent[b] =a;
- rank[a]++;
- }
- }
- }
- int spanningTree(int V, vector<vector<int>> adj[])
- {
- int cost=0;
- parent.resize(V+1);
- rank.resize(V);
- for(int i=0;i<V;i++)make_set(i);
- vector<vector<int>> edges;
- for(int i=0;i<V;i++){
- for(auto it:adj[i]){
- edges.push_back({i,it[0],it[1]});
- }
- }
- sort(edges.begin(),edges.end(),cmp);
- for(vector<int> e : edges){
- if(find_set(e[0])!=find_set(e[1])){
- cost+=e[2];
- union_set(e[0],e[1]);
- }
- }
- return cost;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement