ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 0๋ถ€ํ„ฐ N๊นŒ์ง€ ์ง‘ํ•ฉ์„ ์ด๋ฃฐ ๋•Œ, ํ•ฉ์ง‘ํ•ฉ ์—ฐ์‚ฐ๊ณผ ๋‘ ์›์†Œ๊ฐ€ ๊ฐ™์€ ์ง‘ํ•ฉ์— ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€๋ฅผ ํ™•์ธํ•˜๊ณ  ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๋Š” `Union-Find`๋ฅผ ์ดํ•ดํ•˜๊ณ  ๊ตฌํ˜„ํ•˜๋ฉด ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฆ‰, ํ•ด๋‹น ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๊ทธ๋Œ€๋กœ ๊ตฌํ˜„ํ•˜๋ฉด ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin


def find(target):
    if target == parent[target]:
        return target
    return find(parent[target])


def union(root_a, root_b):
    if root_a < root_b:
        parent[root_b] = root_a
    else:
        parent[root_a] = root_b


if __name__ == '__main__':
    n, m = map(int, stdin.readline().split())
    parent = [i for i in range(n + 1)]

    for _ in range(m):
        op, a, b = map(int, input().split())
        find_a, find_b = find(a), find(b)

        if op:
            print('YES' if find_a == find_b else 'NO')
        else:
            union(find_a, find_b)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€