Skip to content

Commit 60bc40a

Browse files
committed
update Disjoin Set Union
1 parent 65f1aba commit 60bc40a

File tree

1 file changed

+28
-30
lines changed

1 file changed

+28
-30
lines changed

Algorithms/DSU.java

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class A{
1616
private InputStream inputStream ;
1717
private OutputStream outputStream ;
1818
private FastReader in ;
19-
private PrintWriter out ;
19+
private PrintWriter out ;
2020
/*
2121
Overhead [Additional Temporary Strorage] but provides memory reusibility for multiple test cases.
2222
@@ -47,12 +47,12 @@ public A(boolean stdIO)throws FileNotFoundException{
4747

4848
}
4949

50-
void run()throws Exception{
50+
void run()throws Exception{
5151

5252
// int tests = i();
5353
// once();
54-
// for(int t = 1 ; t<= tests ; t++){
5554
int n = i(); int m = i();
55+
// for(int t = 1 ; t<= tests ; t++){
5656
init(n);
5757
for(int q = 1 ; q <= m ; q++){
5858
int type = i();
@@ -61,7 +61,6 @@ void run()throws Exception{
6161
int a = i(); int b = i();
6262
join(a,b);
6363

64-
6564
}else{
6665
int u = i();
6766
out.write("root of "+u+"is :"+root(u)+"\n");
@@ -75,39 +74,38 @@ void once(){
7574

7675
}
7776

78-
int f[] = new int[200005];
79-
int h[] = new int[200005];
77+
int f[] = new int[200005];
78+
int h[] = new int[200005];
8079

8180
void init(int n){
82-
for(int i = 1 ; i <= n ; i++){
83-
f[i] = i;
84-
h[i] = 0;
85-
}
81+
for(int i = 1 ; i <= n ; i++){
82+
f[i] = i;
83+
h[i] = 0;
84+
}
8685
}
86+
8787
int root(int i){
88-
89-
if (f[i] != i)
90-
f[i] = root(f[i]);
91-
92-
return f[i];
88+
if(f[i] != i)
89+
f[i] = root(f[i]);
90+
return f[i];
9391
}
92+
9493
void join(int x, int y){
95-
int xroot = root(x);
96-
int yroot = root(y);
97-
if (h[xroot] < h[yroot])
98-
f[xroot] = yroot;
99-
else if (h[xroot] > h[yroot])
100-
f[yroot] = xroot;
101-
else {
102-
f[yroot] = xroot;
103-
h[xroot]++;
104-
}
105-
}
106-
107-
//****************************** My Utilities ***********************//
94+
int xroot = root(x);
95+
int yroot = root(y);
96+
if(h[xroot] < h[yroot])
97+
f[xroot] = yroot;
98+
else if (h[xroot] > h[yroot])
99+
f[yroot] = xroot;
100+
else{
101+
f[yroot] = xroot;
102+
h[xroot]++;
103+
}
104+
}
105+
108106
void print_r(Object...o){
109-
out.write("\n"+Arrays.deepToString(o)+"\n");
110-
out.flush();
107+
out.write("\n"+Arrays.deepToString(o)+"\n");
108+
out.flush();
111109
}
112110

113111
int hash(String s){

0 commit comments

Comments
 (0)