백준 7511 : 소셜 네트워킹 어플리케이션 (Python)

김현준·2022년 12월 27일

백준

목록 보기
108/214

본문 링크

import sys
input=sys.stdin.readline

def Find(x):
    if x!=disjoint[x]:
        disjoint[x]=Find(disjoint[x])
    return disjoint[x]

def Union(a,b):

    a=Find(a)
    b=Find(b)

    if a>b:
        disjoint[a]=b
    else:
        disjoint[b]=a

T=int(input())

for i in range(T):

    N=int(input())

    disjoint=[0]*(N+1)

    for j in range(1,N+1):
        disjoint[j]=j

    K=int(input())

    for j in range(K):
        a,b=map(int,input().split())
        Union(a,b)

    M=int(input())

    print("Scenario %d:"%(i+1))
    for j in range(M):
        u,v=map(int,input().split())
        if Find(u)==Find(v):
            print(1)
        else:
            print(0)
    print()

📌 어떻게 접근할 것인가?

유니온 파인드 기초문제입니다. Find(A)==Find(B) 를 통해서 두 노드가 같은 집합인지 찾으면 됩니다.

유니온 파인드를 알고 있으면 문제에서 주어지는 그대로 구현하시면 됩니다.

마지막에 줄바꿈 문자를 위해 print() 를 넣어야합니다.

profile
울산대학교 IT융합학부

0개의 댓글