-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathkruskal_disjoint.java
77 lines (64 loc) · 1.33 KB
/
kruskal_disjoint.java
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
75
76
77
import java.util.*;
class kruskal_disjoint{
static int[] P,R;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
pn("Enter vertices and edges ");
int v=sc.nextInt();
int e=sc.nextInt();
create_set(v);
ArrayList<pair> al=new ArrayList<>();
for(int i=0;i<e;++i){
al.add(new pair(sc.nextInt(),sc.nextInt(),sc.nextInt())); //enter wt,x,y
}
Collections.sort(al);
pn(al);
int mstWt=0;
ArrayList<pair> mstSet=new ArrayList<>();
for(pair p:al){
if(find_set(p.x)!=find_set(p.y)){
union(p.x,p.y);
mstSet.add(p);
mstWt+=p.wt;
}
}
pn(mstWt);
pn(mstSet);
}
static void pn(Object o){
System.out.println(o);
}
static void create_set(int v){
P=new int[v+1];
R=new int[v+1];
for(int i=0;i<P.length;++i) P[i]=i;
}
static int find_set(int x){
if(x!=P[x])
P[x]=find_set(P[x]);
return P[x];
}
static void union(int x,int y){
int px=find_set(x);
int py=find_set(y);
if(R[px]>R[py]) P[py]=px;
else P[px]=py;
if(R[px]==R[py]) R[py]=R[py]+1;
}
} class pair implements Comparable<pair>{
int wt,x,y;
pair(int wt,int x,int y)
{
this.wt=wt;
this.x=x;
this.y=y;
}
public int compareTo(pair p)
{
return this.wt-p.wt;
}
public String toString()
{
return wt+" "+x+" "+y;
}
}