题解 | #连通图#
连通图
https://www.nowcoder.com/practice/569e89823a5141fe8a11ab7d4da21edf
class UnionFind:#能不能改下样例自测
def __init__(self, n):
self.pt = [i for i in range(n)]
self.h = [0 for i in range(n)]
def find(self, x):
if self.pt[x] != x:
self.pt[x] = self.find(self.pt[x])
return self.pt[x]
def union(self, x, y):
px, py = self.pt[x], self.pt[y]
if px == py: # 如果父节点一样
return
if self.h[px] > self.h[py]:
self.pt[py] = self.find(self.pt[x])
elif self.h[px] < self.h[py]:
self.pt[px] = self.find(self.pt[y])
else:
self.pt[px] = self.find(self.pt[y])
self.h[y] += 1
while True:
try:
n, m = map(int, input().split(" "))
if m == 0:
break
v = UnionFind(n)
s = "YES"
ct = 0
for i in range(m):
a, b = map(int, input().split(" "))
v.union(a - 1, b - 1)
for i in range(n):
if v.pt[i] == i:
ct += 1
if ct > 1:
s = "NO"
print(s)
except:
break
查看14道真题和解析