forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1.cpp
62 lines (52 loc) Β· 1.63 KB
/
1.cpp
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
#include <bits/stdc++.h>
using namespace std;
// μ¬νμ§μ κ°μμ μ¬ν κ³νμ μν μ¬νμ§μ κ°μ
int n, m;
int parent[501]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
int findParent(int x) {
// λ£¨νΈ λ
Έλκ° μλλΌλ©΄, λ£¨νΈ λ
Έλλ₯Ό μ°Ύμ λκΉμ§ μ¬κ·μ μΌλ‘ νΈμΆ
if (x == parent[x]) return x;
return parent[x] = findParent(parent[x]);
}
// λ μμκ° μν μ§ν©μ ν©μΉκΈ°
void unionParent(int a, int b) {
a = findParent(a);
b = findParent(b);
if (a < b) parent[b] = a;
else parent[a] = b;
}
int main(void) {
cin >> n >> m;
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
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;
cin >> x;
if (x == 1) { // μ°κ²°λ κ²½μ° ν©μ§ν©(Union) μ°μ° μν
unionParent(i + 1, j + 1);
}
}
}
// μ¬ν κ³ν μ
λ ₯λ°κΈ°
vector<int> plan;
for (int i = 0; i < m; i++) {
int x;
cin >> x;
plan.push_back(x);
}
bool result = true;
// μ¬ν κ³νμ μνλ λͺ¨λ λ
Έλμ 루νΈκ° λμΌνμ§ νμΈ
for (int i = 0; i < m - 1; i++) {
if (findParent(plan[i]) != findParent(plan[i + 1])) {
result = false;
}
}
// μ¬ν κ³νμ μνλ λͺ¨λ λ
Έλκ° μλ‘ μ°κ²°λμ΄ μλμ§(루νΈκ° λμΌνμ§) νμΈ
if (result) cout << "YES" << '\n';
else cout << "NO" << '\n';
}