Skip to content

Commit 3795c2d

Browse files
authored
Merge pull request #731 from AlgorithmWithGod/lkhyun
[20250824] BOJ / G5 / 소셜 네트워킹 어플리케이션 / 이강현
2 parents 89dba1a + 467977b commit 3795c2d

File tree

1 file changed

+60
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)