forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path7.cpp
More file actions
50 lines (43 loc) ยท 1.23 KB
/
7.cpp
File metadata and controls
50 lines (43 loc) ยท 1.23 KB
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
#include <bits/stdc++.h>
using namespace std;
// ๋
ธ๋์ ๊ฐ์(N)์ ์ฐ์ฐ์ ๊ฐ์(M)
int n, m;
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 >> n >> m;
// ๋ถ๋ชจ ํ
์ด๋ธ์์์, ๋ถ๋ชจ๋ฅผ ์๊ธฐ ์์ ์ผ๋ก ์ด๊ธฐํ
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
// ๊ฐ ์ฐ์ฐ์ ํ๋์ฉ ํ์ธ
for (int i = 0; i < m; i++) {
int oper, a, b;
cin >> oper >> a >> b;
// ํฉ์งํฉ(Union) ์ฐ์ฐ์ธ ๊ฒฝ์ฐ
if (oper == 0) {
unionParent(a, b);
}
// ์ฐพ๊ธฐ(Find) ์ฐ์ฐ์ธ ๊ฒฝ์ฐ
else if (oper == 1) {
if (findParent(a) == findParent(b)) {
cout << "YES" << '\n';
}
else {
cout << "NO" << '\n';
}
}
}
}