문제.

풀이.
유니온 파인드를 이용해서 풀면 된다.
입력이 문자열이기때문에 딕셔너리를 통해서 풀었다.
2개의 딕셔너리를 선언하고
number 딕셔너리의 루트 노드에 친구 관계의 친구관계의 수를 저장하고
매 단계 루트노드를 출력하면된다.
소스코드.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
def union(a, b): | |
a = find(a) | |
b = find(b) | |
if a != b: | |
parent[b] = a | |
number[a] += number[b] | |
def find(target): | |
if target == parent[target]: | |
return target | |
# 경로 압축 | |
parent[target] = find(parent[target]) | |
return parent[target] | |
input = sys.stdin.readline | |
sys.setrecursionlimit(10 ** 6) | |
tc = int(input()) | |
for i in range(tc): | |
f = int(input()) | |
parent = {} | |
number = {} | |
for j in range(f): | |
f1, f2 = map(str, input().split()) | |
if f1 not in parent: | |
parent[f1] = f1 | |
number[f1] = 1 | |
if f2 not in parent: | |
parent[f2] = f2 | |
number[f2] = 1 | |
union(f1, f2) | |
print(number[find(f1)]) |
'프로그래밍 > 백준' 카테고리의 다른 글
백준 9372 상근이의 여행 - 파이썬 (0) | 2021.08.04 |
---|---|
백준 20040 사이클 게임 - 파이썬 (0) | 2021.08.04 |
백준 1976 여행 가자 - 파이썬 (0) | 2021.08.03 |
백준 1717 집합의 표현 - 파이썬 (0) | 2021.08.03 |
백준 5639 이진 검색 트리 - 파이썬 (0) | 2021.08.03 |