Skip to content

Commit ab6df58

Browse files
authored
Merge pull request #670 from AlgorithmWithGod/lkhyun
[20250815] BOJ / G5 / 집합의 표현 / 이강현
2 parents 655836c + 4823219 commit ab6df58

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static int N,M;
7+
static int[] root;
8+
9+
public static void main(String[] args) throws IOException {
10+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
12+
StringTokenizer st = new StringTokenizer(br.readLine());
13+
N = Integer.parseInt(st.nextToken());
14+
M = Integer.parseInt(st.nextToken());
15+
root = new int[N+1];
16+
17+
for (int i = 0; i <= N; i++) {
18+
root[i] = i;
19+
}
20+
21+
for (int i = 0; i < M; i++) {
22+
st = new StringTokenizer(br.readLine());
23+
24+
int cmd = Integer.parseInt(st.nextToken());
25+
int a = Integer.parseInt(st.nextToken());
26+
int b = Integer.parseInt(st.nextToken());
27+
28+
if(cmd == 0){ //
29+
union(a,b);
30+
}else if(cmd == 1){ //같이 있나?
31+
if(find(a) == find(b)){
32+
bw.write("yes\n");
33+
}else{
34+
bw.write("no\n");
35+
}
36+
}
37+
}
38+
39+
bw.close();
40+
}
41+
42+
static int find(int cur){
43+
if(cur == root[cur]) return cur;
44+
else{
45+
return root[cur] = find(root[cur]);
46+
}
47+
}
48+
static void union(int a, int b){
49+
int rootA = find(a);
50+
int rootB = find(b);
51+
52+
if(rootA < rootB){
53+
root[rootB] = rootA;
54+
}else{
55+
root[rootA] = rootB;
56+
}
57+
}
58+
}
59+
```

0 commit comments

Comments
 (0)