https://www.acmicpc.net/problem/4195
import sys
from collections import defaultdict
def find(x):
if parents[x] == x:
return x
parents[x] = find(parents[x])
return parents[x]
def union(x, y):
x = find(x)
y = find(y)
if x == y:
return
if x < y:
parents[y] = x
count[x] += count[y]
else:
parents[x] = y
count[y] += count[x]
def find_root(x, y):
if x < y:
return x, y
else:
return y, x
t = int(sys.stdin.readline())
parents = defaultdict(int)
for _ in range(t):
n = int(sys.stdin.readline())
parents = defaultdict(int)
count = defaultdict(int)
for i in range(1, n + 1):
a, b = map(str, sys.stdin.readline().split())
answer = 0
if not parents[a]:
parents[a] = a
count[a] = 1
if not parents[b]:
parents[b] = b
count[b] = 1
if find(a) != find(b):
union(a, b)
print(count[find(a)])
ㅎ..