第一题通讯录合并
通过并查集合并拥有相同电话号码的用户,并输出合并后的用户姓名和电话号码列表
num = int(input())
data = [list(input().split()) for _ in range(num)]
phone_to_id = {}
for i in range(num):
for phone in data[i][1:]:
if phone in phone_to_id:
phone_to_id[phone].append(i)
else:
phone_to_id[phone] = [i]
fa = [i for i in range(num)]
def find(x):
if fa[x]!=x:
fa[x]=find(fa[x])
return fa[x]
def merge(x,y):
x = find(x)
y = find(y)
if x !=y:
fa[x]=y
for phone in phone_to_id:
first_id = phone_to_id[phone][0]
for i in range(1,len(phone_to_id[phone])):
merge(first_id,phone_to_id[phone][i])
root_to_name = {}
root_to_phone =
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



