• Home
  • About
    • JOOS photo

      JOOS

      Joos's blog

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

[백준] 1717번 : 집합의 표현 with python3

28 Jun 2020

Reading time ~1 minute

문제 : https://www.acmicpc.net/problem/1717

유니온 파인드로 푸는 문제

import sys
input = sys.stdin.readline

def find(u):
    if u not in x \
        or x[u] == u:
        # 처음 초기화를 자신의 값으로 한다.
        #  or
        # 자기 자신이 되는 순간이 root
        return u # 자기 자신이 되는 순간 그것이 root이니 그것을 return 하는 것이다.
    x[u] = find(x[u])
    return x[u]

def union(u, v):
    x[find(u)] = find(v)
    # v의 제일 상위의 parent를 u의 가장 상위 것을 잇는다.

n, m = map(int, input().split())
x = {}
for _ in range(m):
    t, a, b = map(int, input().split())

    if t:
        print('yes' if find(a) == find(b) else 'no')
    else:
        union(a, b)


algorithm백준python Share Tweet +1