DevYoon

[๋ฐฑ์ค€] 1717. ์ง‘ํ•ฉ์˜ ํ‘œํ˜„ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 1717. ์ง‘ํ•ฉ์˜ ํ‘œํ˜„ (Python)

gimewn 2022. 10. 28. 17:15

link ๐Ÿ”— https://www.acmicpc.net/problem/1717

 

1717๋ฒˆ: ์ง‘ํ•ฉ์˜ ํ‘œํ˜„

์ฒซ์งธ ์ค„์— n(1 ≤ n ≤ 1,000,000), m(1 ≤ m ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. m์€ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ์—ฐ์‚ฐ์˜ ๊ฐœ์ˆ˜์ด๋‹ค. ๋‹ค์Œ m๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ๊ฐ์˜ ์—ฐ์‚ฐ์ด ์ฃผ์–ด์ง„๋‹ค. ํ•ฉ์ง‘ํ•ฉ์€ 0 a b์˜ ํ˜•ํƒœ๋กœ ์ž…๋ ฅ์ด ์ฃผ์–ด์ง„๋‹ค. ์ด๋Š”

www.acmicpc.net

 

๐Ÿ’ฌ ์œ ๋‹ˆ์˜จ ํŒŒ์ธ๋“œ ๋ฌธ์ œ!

๐Ÿ’ฌ ์œ ๋‹ˆ์˜จ ํŒŒ์ธ๋“œ๋ฅผ ์˜ค๋žœ๋งŒ์— ํ’€์–ด์„œ, ๊ฐœ๋…๋ถ€ํ„ฐ ๋‹ค์‹œ ๋ด์•ผ ํ–ˆ๋‹คใ… ใ… 

๐Ÿ’ฌ type์ด 1์ผ ๊ฒฝ์šฐ union ํ•จ์ˆ˜ ๋‚ด์—์„œ YES ํ˜น์€ NO๋ฅผ ๊ตฌ๋ถ„ํ•œ๋‹ค.

 

import sys
input = sys.stdin.readline

def find(n):
    if parents[n] == n:
        return n
    parents[n] = find(parents[n])
    return parents[n]

def union(type, n1, n2):
    fn1 = find(n1)
    fn2 = find(n2)
    if type == 1:
        if fn1 == fn2:
            print("YES")
        else:
            print("NO")
    else:
        parents[fn2] = fn1

N, M = map(int, input().split())

parents = [num for num in range(N+1)]

for _ in range(M):
    type, num1, num2 = map(int, input().split())
    union(type, num1, num2)