forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.py
More file actions
40 lines (34 loc) Β· 1.18 KB
/
4.py
File metadata and controls
40 lines (34 loc) Β· 1.18 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
# νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
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
# λ
Έλμ κ°μμ κ°μ (Union μ°μ°)μ κ°μ μ
λ ₯ λ°κΈ°
v, e = map(int, input().split())
parent = [0] * (v + 1) # λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ννκΈ°
# λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for i in range(1, v + 1):
parent[i] = i
cycle = False # μ¬μ΄ν΄ λ°μ μ¬λΆ
for i in range(e):
a, b = map(int, input().split())
# μ¬μ΄ν΄μ΄ λ°μν κ²½μ° μ’
λ£
if find_parent(parent, a) == find_parent(parent, b):
cycle = True
break
# μ¬μ΄ν΄μ΄ λ°μνμ§ μμλ€λ©΄ ν©μ§ν©(Union) μ°μ° μν
else:
union_parent(parent, a, b)
if cycle:
print("μ¬μ΄ν΄μ΄ λ°μνμ΅λλ€.")
else:
print("μ¬μ΄ν΄μ΄ λ°μνμ§ μμμ΅λλ€.")