本文主要是介绍day_54,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
107. 寻找存在的路径
def find(father, node):if father[node] != node:father[node] = find(father, father[node])return father[node]def union(father, n1, n2):root1 = find(father, n1)root2 = find(father, n2)if root1 != root2:father[root2] = root1def main():n, m = map(int, input().split())father = [i for i in range(n + 1)]for _ in range(m):s, t = map(int, input().split())union(father, s, t)source, dest = map(int, input().split())if find(father, source) == find(father, dest):print(1)else:print(0)if __name__ == '__main__':main()
下面是一样的,只不过少写了一个函数。
def find(father, n):if father[n] != n:father[n] = find(father, father[n])return father[n]def main():n, m = map(int, input().split())father = [i for i in range(n + 1)]for _ in range(m):s, t = map(int, input().split())fs = find(father, s) ft = find(father, t)if fs != ft:father[fs] = ftsource, dest = map(int, input().split())if find(father, source) == find(father, dest):print(1)else:print(0)if __name__ == '__main__':main()
这篇关于day_54的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!