forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1.java
64 lines (53 loc) Β· 2.01 KB
/
1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.*;
public class Main {
// μ¬νμ§μ κ°μμ μ¬ν κ³νμ μν μ¬νμ§μ κ°μ
public static int n, m;
public static int[] parent = new int[501]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
public static int findParent(int x) {
// λ£¨νΈ λ
Έλκ° μλλΌλ©΄, λ£¨νΈ λ
Έλλ₯Ό μ°Ύμ λκΉμ§ μ¬κ·μ μΌλ‘ νΈμΆ
if (x == parent[x]) return x;
return parent[x] = findParent(parent[x]);
}
// λ μμκ° μν μ§ν©μ ν©μΉκΈ°
public static void unionParent(int a, int b) {
a = findParent(a);
b = findParent(b);
if (a < b) parent[b] = a;
else parent[a] = b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
// Union μ°μ°μ κ°κ° μν
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int x = sc.nextInt();
if (x == 1) { // μ°κ²°λ κ²½μ° ν©μ§ν©(Union) μ°μ° μν
unionParent(i + 1, j + 1);
}
}
}
// μ¬ν κ³ν μ
λ ₯λ°κΈ°
ArrayList<Integer> plan = new ArrayList<>();
for (int i = 0; i < m; i++) {
int x = sc.nextInt();
plan.add(x);
}
boolean result = true;
// μ¬ν κ³νμ μνλ λͺ¨λ λ
Έλμ 루νΈκ° λμΌνμ§ νμΈ
for (int i = 0; i < m - 1; i++) {
if (findParent(plan.get(i)) != findParent(plan.get(i + 1))) {
result = false;
}
}
// μ¬ν κ³νμ μνλ λͺ¨λ λ
Έλκ° μλ‘ μ°κ²°λμ΄ μλμ§(루νΈκ° λμΌνμ§) νμΈ
if (result) System.out.println("YES");
else System.out.println("NO");
}
}