forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3.cpp
53 lines (44 loc) Β· 1.3 KB
/
3.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
#include <bits/stdc++.h>
using namespace std;
// λ
Έλμ κ°μ(V)μ κ°μ (Union μ°μ°)μ κ°μ(E)
// λ
Έλμ κ°μλ μ΅λ 100,000κ°λΌκ³ κ°μ
int v, e;
int parent[100001]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
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 >> v >> e;
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for (int i = 1; i <= v; i++) {
parent[i] = i;
}
// Union μ°μ°μ κ°κ° μν
for (int i = 0; i < e; i++) {
int a, b;
cin >> a >> b;
unionParent(a, b);
}
// κ° μμκ° μν μ§ν© μΆλ ₯νκΈ°
cout << "κ° μμκ° μν μ§ν©: ";
for (int i = 1; i <= v; i++) {
cout << findParent(i) << ' ';
}
cout << '\n';
// λΆλͺ¨ ν
μ΄λΈ λ΄μ© μΆλ ₯νκΈ°
cout << "λΆλͺ¨ ν
μ΄λΈ: ";
for (int i = 1; i <= v; i++) {
cout << parent[i] << ' ';
}
cout << '\n';
}