一共有几块
同样合并完之后。运行下面这段程序:
NAMES = ["阿岚", "小满", "阿泰", "南风", "北辰"]
EDGES = [("阿岚", "小满"), ("阿岚", "阿泰"),
("小满", "阿泰"), ("阿泰", "南风")]
def find(p, x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
def union(p, a, b):
ra = find(p, a)
rb = find(p, b)
if ra != rb:
p[ra] = rb
p = {}
for n in NAMES:
p[n] = n
for a, b in EDGES:
union(p, a, b)
roots = {}
for n in NAMES:
roots[find(p, n)] = True
print(len(roots))
全部评论