xxxxxxxxxx
//User function Template for Java
/**
* ith value in adj vector contains information between the node connected to it and weight between them.
* Example. for a value 2 3 1, Node 2 and Node 3 has weight 1. adj[2] = {3,1} and adj[3] = {2,1}.
* n -> number of nodes
* m -> total number of edges
* return the mst value
*/
class DSU
{
//Function to find the minimum spanning tree value using Kruskal.
static int[] parents;
static int[] ranks;
static long kruskalDSU(ArrayList<Edge> adj, int n, int m)
{
ArrayList<EdgeSort> list=new ArrayList<>();
parents=new int[n+1];
ranks=new int[n+1];
for(Edge e : adj)
list.add(new EdgeSort(e));
Collections.sort(list);
for(int i=1;i<=n;i++){
parents[i]=i;
ranks[i]=0;
}
int res=0;
int s=0;
for(int i=0;i<list.size() && s<m;i++){
EdgeSort es=list.get(i);
int xRep=find(es.a);
int yRep=find(es.b);
if(xRep!=yRep){
res+=es.w;
union(xRep,yRep);
s++;
}
}
return res;
}
private static int find(int a){
if(parents[a]==a)
return a;
parents[a]=find(parents[a]);
return parents[a];
}
private static void union(int a,int b){
int aRep=find(a);
int bRep=find(b);
if(aRep==bRep)
return;
if(ranks[aRep]<ranks[bRep])
parents[aRep]=bRep;
else if(ranks[aRep]>ranks[bRep])
parents[bRep]=aRep;
else{
parents[bRep]=aRep;
ranks[aRep]++;
}
}
public static class EdgeSort implements Comparable<EdgeSort>{
int a;
int b;
int w;
EdgeSort(Edge e){
a=e.src;
b=e.des;
w=e.wt;
}
public int compareTo(EdgeSort e){
return w-e.w;
}
}
}
xxxxxxxxxx
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// DSU data structure
// path compression + rank by union
class DSU {
int* parent;
int* rank;
public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = -1;
rank[i] = 1;
}
}
// Find function
int find(int i)
{
if (parent[i] == -1)
return i;
return parent[i] = find(parent[i]);
}
// Union function
void unite(int x, int y)
{
int s1 = find(x);
int s2 = find(y);
if (s1 != s2) {
if (rank[s1] < rank[s2]) {
parent[s1] = s2;
}
else if (rank[s1] > rank[s2]) {
parent[s2] = s1;
}
else {
parent[s2] = s1;
rank[s1] += 1;
}
}
}
};
class Graph {
vector<vector<int> > edgelist;
int V;
public:
Graph(int V) { this->V = V; }
// Function to add edge in a graph
void addEdge(int x, int y, int w)
{
edgelist.push_back({ w, x, y });
}
void kruskals_mst()
{
// Sort all edges
sort(edgelist.begin(), edgelist.end());
// Initialize the DSU
DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl;
for (auto edge : edgelist) {
int w = edge[0];
int x = edge[1];
int y = edge[2];
// Take this edge in MST if it does
// not forms a cycle
if (s.find(x) != s.find(y)) {
s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}
}
cout << "Minimum Cost Spanning Tree: " << ans;
}
};
// Driver code
int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);
// Function call
g.kruskals_mst();
return 0;
}