-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeightedQuickUnion.java
More file actions
96 lines (95 loc) · 2.32 KB
/
WeightedQuickUnion.java
File metadata and controls
96 lines (95 loc) · 2.32 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* Created by Syed on 27-02-2018.
*/
public class WeightedQuickUnion {
protected int[] id,sz;
WeightedQuickUnion(int n)
{
id=new int[n];
sz=new int[n];
for(int i=0;i<n;i++)
{
id[i]=i;
sz[i]=1;
}
}
protected int root(int p)
{
while(p!=id[p])
{
id[p]=id[id[p]]; //path compression
p=id[p];
}
return p;
}
boolean connected(int p,int q)
{
return root(p)==root(q);
}
public void union(int p,int q)
{
if(p==q) return;
if(sz[p]<sz[q])
{
id[root(p)]=root(q);
sz[q]+=sz[p];
}
else
{
id[root(q)]=root(p);
sz[p]+=sz[q];
}
}
public void display()
{
for(int i=0;i<id.length;i++)
{
System.out.print(id[i]+" ");
}
}
public static void main(String a[]) throws IOException, InterruptedException
{
WeightedQuickUnion wqu=new WeightedQuickUnion(8);
Scanner scanner = new Scanner(System.in);
int choice;
System.out.println("1. Union\n2. Connected\n3. Display\n4. Exit");
System.out.println("Enter your choice: ");
choice=scanner.nextInt();
while(choice!=4)
{
if(choice==1)
{
int x1,x2;
System.out.println("Enter two numbers: ");
x1=scanner.nextInt();
x2=scanner.nextInt();
wqu.union(x1,x2);
}
if(choice==2)
{
int x1,x2;
System.out.println("Enter two numbers: ");
x1=scanner.nextInt();
x2=scanner.nextInt();
if(wqu.connected(x1,x2))
{
System.out.println("Connected");
}
else
{
System.out.println("Not Connected");
}
}
if(choice==3)
{
wqu.display();
}
System.out.println("Enter your choice: ");
choice=scanner.nextInt();
}
}
}