Skip to content

Commit 8c3eb9a

Browse files
authored
Merge pull request #504 from AlgorithmWithGod/Seol-JY
[20250719] BOJ / G4 / 여행 가자 / 설진영
2 parents ada008e + c79a0c8 commit 8c3eb9a

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
```java
2+
import java.util.*;
3+
4+
public class Main {
5+
static int[] parent;
6+
7+
public static void main(String[] args) {
8+
Scanner sc = new Scanner(System.in);
9+
int N = sc.nextInt();
10+
int M = sc.nextInt();
11+
12+
parent = new int[N + 1];
13+
for (int i = 1; i <= N; i++) {
14+
parent[i] = i;
15+
}
16+
for (int i = 1; i <= N; i++) {
17+
for (int j = 1; j <= N; j++) {
18+
int connected = sc.nextInt();
19+
if (connected == 1) {
20+
union(i, j);
21+
}
22+
}
23+
}
24+
25+
int[] plan = new int[M];
26+
for (int i = 0; i < M; i++) {
27+
plan[i] = sc.nextInt();
28+
}
29+
30+
int root = find(plan[0]);
31+
boolean possible = true;
32+
for (int i = 1; i < M; i++) {
33+
if (find(plan[i]) != root) {
34+
possible = false;
35+
break;
36+
}
37+
}
38+
39+
System.out.println(possible ? "YES" : "NO");
40+
}
41+
42+
static int find(int x) {
43+
if (x != parent[x]) {
44+
parent[x] = find(parent[x]);
45+
}
46+
return parent[x];
47+
}
48+
49+
static void union(int a, int b) {
50+
int rootA = find(a);
51+
int rootB = find(b);
52+
if (rootA != rootB) {
53+
parent[rootB] = rootA;
54+
}
55+
}
56+
}
57+
58+
```

0 commit comments

Comments
 (0)