๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • What would life be If we had no courage to attemp anything?
Problem Solving/BAEKJOON

[baekjoon]python #2606 ๋ฐ”์ด๋Ÿฌ์Šค

by DevIseo 2022. 5. 2.

https://www.acmicpc.net/problem/2606

 

2606๋ฒˆ: ๋ฐ”์ด๋Ÿฌ์Šค

์ฒซ์งธ ์ค„์—๋Š” ์ปดํ“จํ„ฐ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ปดํ“จํ„ฐ์˜ ์ˆ˜๋Š” 100 ์ดํ•˜์ด๊ณ  ๊ฐ ์ปดํ“จํ„ฐ์—๋Š” 1๋ฒˆ ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ๋ฒˆํ˜ธ๊ฐ€ ๋งค๊ฒจ์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ๋„คํŠธ์›Œํฌ ์ƒ์—์„œ ์ง์ ‘ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ์ปดํ“จํ„ฐ ์Œ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด

www.acmicpc.net

#boss์ฐพ๊ธฐ
def findboss(group,member):
    if group[member]!=member:
        group[member]=findboss(group,group[member])
    return group[member]

#union ์‹œํ‚ค๊ธฐ
def union(group,a,b):
    fa,fb = findboss(group,a),findboss(group,b)
    
    #์ˆซ์ž๊ฐ€ ์ž‘์€๊ฑธ ๊ธฐ์ค€์œผ๋กœ union ์‹œ์ผœ์ฃผ๊ธฐ ์œ„ํ•ด
    if fa<fb:
        group[fb] = fa
    else:
        group[fa]=fb

n = int(input())
k = int(input())
#์ž์‹ ์„ ๋ณด์Šค๋กœ ๋„ฃ์–ด์ฃผ๊ธฐ!
group = [i for i in range(n+1)]

for i in range(k):
    a,b = map(int,input().split())
    #group์„ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๊ฐ™์ด ๋„ฃ์–ด์ฃผ๊ธฐ
    union(group,a,b)
    
cnt=0
for g in range(1,len(group)):
	#boss๊ฐ€ 1๋ฒˆ ์ปดํ“จํ„ฐ์ธ๊ฑฐ ์ฐพ๊ธฐ!
    if findboss(group,g) == 1:
        cnt+=1
print(cnt-1)

 

๋Œ“๊ธ€