Skip to content

Commit 9feee97

Browse files
authored
Merge pull request #591 from AlgorithmWithGod/LiiNi-coder
[20250801] BOJ / G5 / 집합의 표현 / 이인희
2 parents cd4cb0e + 0888aee commit 9feee97

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.Iterator;
6+
import java.util.StringTokenizer;
7+
8+
public class Main {
9+
private static class WeightedUF{
10+
int[] ids;
11+
int[] size;
12+
public WeightedUF(int v) {
13+
ids = new int[v];
14+
size = new int[v];
15+
for (int i = 0; i < ids.length; i++) {
16+
ids[i] = i;
17+
size[i] = 1;
18+
}
19+
}
20+
public int root(int a) {
21+
while(a != ids[a])
22+
a = ids[a];
23+
return a;
24+
}
25+
public void union(int a, int b) {
26+
int g, l;
27+
if(size[a] >= size[b]) {
28+
g = a;
29+
l = b;
30+
}else {
31+
l = a;
32+
g = b;
33+
}
34+
// b가 더 깊이가 짧음
35+
ids[root(b)] = root(a);
36+
}
37+
public boolean connected(int a, int b) {
38+
return root(a) == root(b);
39+
}
40+
}
41+
private static BufferedReader br;
42+
private static Main.WeightedUF uf;
43+
private static int m;
44+
private static int n;
45+
public static void main(String[] args) throws IOException {
46+
br = new BufferedReader(new InputStreamReader(System.in));
47+
StringBuilder sb = new StringBuilder();
48+
String[] temp = br.readLine().split(" ");
49+
n = Integer.parseInt(temp[0])+1;
50+
m = Integer.parseInt(temp[1]);
51+
uf = new WeightedUF(n);
52+
53+
for(int i = 0; i<m; i++) {
54+
StringTokenizer st = new StringTokenizer(br.readLine());
55+
int command = Integer.parseInt( st.nextToken());
56+
int a = Integer.parseInt(st.nextToken());
57+
int b = Integer.parseInt(st.nextToken());
58+
if(command == 0) {
59+
// 합집합
60+
uf.union(a, b);
61+
}else {
62+
// conneted()
63+
if(uf.connected(a, b))
64+
sb.append("YES\n");
65+
else
66+
sb.append("NO\n");
67+
}
68+
}
69+
System.out.println(sb.toString());
70+
br.close();
71+
}
72+
73+
74+
}
75+
```

0 commit comments

Comments
 (0)