-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickUnion.java
More file actions
82 lines (81 loc) · 2.08 KB
/
QuickUnion.java
File metadata and controls
82 lines (81 loc) · 2.08 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by Syed on 27-02-2018.
*/
public class QuickUnion {
int[] id;
public QuickUnion(int n)
{
id=new int[n];
for(int i=0;i<n;i++)
{
id[i]=i;
}
}
private int root(int p)
{
while(p!=id[p])
{
p=id[p];
}
return p;
}
public boolean connected(int p,int q)
{
return root(p)==root(q);
}
public void union(int p,int q)
{
id[root(p)]=root(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
{
QuickUnion qu=new QuickUnion(8);
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int choice;
System.out.println("1. Union\n2. Connected\n3. Display\n4. Exit");
System.out.println("Enter your choice: ");
choice=Integer.parseInt(b.readLine());
while(choice!=4)
{
if(choice==1)
{
int x1,x2;
System.out.println("Enter two numbers: ");
x1=Integer.parseInt(b.readLine());
x2=Integer.parseInt(b.readLine());
qu.union(x1,x2);
}
if(choice==2)
{
int x1,x2;
System.out.println("Enter two numbers: ");
x1=Integer.parseInt(b.readLine());
x2=Integer.parseInt(b.readLine());
if(qu.connected(x1,x2))
{
System.out.println("Connected");
}
else
{
System.out.println("Not Connected");
}
}
if(choice==3)
{
qu.display();
}
System.out.println("Enter your choice: ");
choice=Integer.parseInt(b.readLine());
}
}
}