forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2.py
More file actions
35 lines (30 loc) ยท 1.04 KB
/
2.py
File metadata and controls
35 lines (30 loc) ยท 1.04 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
# ํน์ ์์๊ฐ ์ํ ์งํฉ์ ์ฐพ๊ธฐ
def find_parent(parent, x):
# ๋ฃจํธ ๋
ธ๋๊ฐ ์๋๋ผ๋ฉด, ๋ฃจํธ ๋
ธ๋๋ฅผ ์ฐพ์ ๋๊น์ง ์ฌ๊ท์ ์ผ๋ก ํธ์ถ
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# ๋ ์์๊ฐ ์ํ ์งํฉ์ ํฉ์น๊ธฐ
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
# ํ์น๊ตฌ์ ๊ฐ์ ์
๋ ฅ๋ฐ๊ธฐ
g = int(input())
# ๋นํ๊ธฐ์ ๊ฐ์ ์
๋ ฅ๋ฐ๊ธฐ
p = int(input())
parent = [0] * (g + 1) # ๋ถ๋ชจ ํ
์ด๋ธ ์ด๊ธฐํ
# ๋ถ๋ชจ ํ
์ด๋ธ์์์, ๋ถ๋ชจ๋ฅผ ์๊ธฐ ์์ ์ผ๋ก ์ด๊ธฐํ
for i in range(1, g + 1):
parent[i] = i
result = 0
for _ in range(p):
data = find_parent(parent, int(input())) # ํ์ฌ ๋นํ๊ธฐ์ ํ์น๊ตฌ์ ๋ฃจํธ ํ์ธ
if data == 0: # ํ์ฌ ๋ฃจํธ๊ฐ 0์ด๋ผ๋ฉด, ์ข
๋ฃ
break
union_parent(parent, data, data - 1) # ๊ทธ๋ ์ง ์๋ค๋ฉด ๋ฐ๋ก ์ผ์ชฝ์ ์งํฉ๊ณผ ํฉ์น๊ธฐ
result += 1
print(result)