-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_164kruskal.java
More file actions
74 lines (73 loc) · 1.93 KB
/
_164kruskal.java
File metadata and controls
74 lines (73 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.*;
public class _164kruskal {
static class Edge implements Comparable<Edge>{
int src;
int dest;
int wt;
public Edge(int s,int d,int wt){
this.src=s ;
this.dest=d ;
this.wt=wt ;
}
@Override
public int compareTo(Edge e2){
return this.wt-e2.wt;
}
}
static void createGraph(ArrayList<Edge> edges){
edges.add(new Edge(0,1,10));
edges.add(new Edge(0,2,15));
edges.add(new Edge(0,3,30));
edges.add(new Edge(1,3,40));
edges.add(new Edge(2,3,50));
}
static int n =4;
static int par[]= new int[n];
static int rank[]= new int[n];
public static void init(){
for(int i=0;i<n;i++){
par[i]=i;
}
}
public static int find(int x){
if(par[x]==x){
return x;
}
return par[x]= find(par[x]);
}
public static void union(int a, int b){
int parA = find(a);
int parB = find(b);
if(rank[parA] == rank[parB]){
par[parB] = parA;
rank[parA]++;
} else if(rank[parA]< rank[parB]){
par[parA]=parB;
} else{
par[parB]=parA;
}
}
public static void kruskalMST(ArrayList<Edge> edges,int V){
init();
Collections.sort(edges);
int mstCost = 0;
int count = 0;
for(int i=0;count<V-1;i++){
Edge e =edges.get(i);
int parA = find(e.src); // src = a
int parB = find(e.dest); // src = b
if(parA != parB){
union(e.src, e.dest);
mstCost += e.wt;
count++;
}
}
System.out.println(mstCost);
}
public static void main(String[] args) {
int V =4;
ArrayList<Edge> edges = new ArrayList<>();
createGraph(edges);
kruskalMST(edges, V);
}
}