法二:并查集:
# 法二,并查集的方式
import sys
def getRoot(RootDict, child):
if RootDict[child] == child:
return child
else:
result = getRoot(RootDict, RootDict[child])
RootDict[child] = result
return result
def main():
HeightDict, RootDict = dict(), dict()
for line in sys.stdin:
a, b = map(int, line.strip().split())
if a not in HeightDict:
HeightDict[a] = 1
if a not in RootDict:
RootDict[a] = a
if b not in HeightDict:
HeightDict[b] = 1
if b not in RootDict:
RootDict[b] = b
if a == b:
continue
# a != b
rootA, rootB = getRoot(RootDict,a), getRoot(RootDict,b)
if rootA == rootB:
continue
# rootA != rootB
heightA, heightB = HeightDict[rootA], HeightDict[rootB]
if heightA == heightB:
RootDict[rootB] = rootA
HeightDict[rootA] += 1
if heightA > heightB:
RootDict[rootB] = rootA
if heightA < heightB:
RootDict[rootA] = rootB
cntCC = 0 # count connected components
for child, root in RootDict.items():
if child == root:
cntCC += 1
print(cntCC)
if __name__ == "__main__":
main()
法一:通过遍历所有节点至少需要从几个根节点出发,即为几个连通分支数
# 法一,通过遍历所有节点至少需要从几个根节点出发,即为几个连通分支数
import sys
def main():
VertexSet, AdjVerDict = set(), dict()
for line in sys.stdin:
src, dst = map(int, line.strip().split())
VertexSet.update({src, dst})
if src != dst:
if src in AdjVerDict:
AdjVerDict[src].add(dst)
else:
AdjVerDict[src] = {dst}
if dst in AdjVerDict:
AdjVerDict[dst].add(src)
else:
AdjVerDict[dst] = {src}
###########################################
VertexNum = len(VertexSet)
if VertexNum == 0:
print(0)
return
elif VertexNum == 1:
print(1)
return
Visited, awaitVisited = set(), VertexSet.copy()
cntCC = 0 # Count Connected Componet
while len(awaitVisited) > 0:
queue = list()
temp = awaitVisited.pop()
awaitVisited.add(temp)
queue.append(temp)
cntCC += 1
while len(queue) > 0:
v = queue.pop()
if v in Visited:
continue
Visited.add(v)
awaitVisited.remove(v)
adjcentSet = AdjVerDict.get(v,set()) - Visited
queue.extend(list(adjcentSet))
print(cntCC)
if __name__ == "__main__":
main()