forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2.cpp
43 lines (35 loc) ยท 1.12 KB
/
2.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
#include <bits/stdc++.h>
using namespace std;
// ํ์น๊ตฌ์ ๊ฐ์์ ๋นํ๊ธฐ์ ๊ฐ์
int g, p;
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 >> g >> p;
// ๋ถ๋ชจ ํ
์ด๋ธ์์์, ๋ถ๋ชจ๋ฅผ ์๊ธฐ ์์ ์ผ๋ก ์ด๊ธฐํ
for (int i = 1; i <= g; i++) {
parent[i] = i;
}
int result = 0;
for (int i = 0; i < p; i++) {
int x;
cin >> x;
int root = findParent(x); // ํ์ฌ ๋นํ๊ธฐ์ ํ์น๊ตฌ์ ๋ฃจํธ ํ์ธ
if (root == 0) break; // ํ์ฌ ๋ฃจํธ๊ฐ 0์ด๋ผ๋ฉด, ์ข
๋ฃ
unionParent(root, root - 1); // ๊ทธ๋ ์ง ์๋ค๋ฉด ๋ฐ๋ก ์ผ์ชฝ์ ์งํฉ๊ณผ ํฉ์น๊ธฐ
result += 1;
}
cout << result << '\n';
}