# https://infoarena.ro/problema/dfs
def find_exista(componente_conexe: list[list[int]], muchie: int) -> int | None:
for i, componenta_conexa in enumerate(componente_conexe):
if muchie in componenta_conexa:
return i
return None
def main():
with open("dfs.in", "r") as f:
content = [[int(x) for x in lines.split()] for lines in f.read().splitlines()]
[noduri, _muchii] = content.pop(0)
componente_conexe: list[list[int]] = []
nr_componente_conexe = noduri
for [muchie1, muchie2] in content:
index1 = find_exista(componente_conexe, muchie1)
index2 = find_exista(componente_conexe, muchie2)
if index1 is not None and index2 is not None:
if index1 == index2:
continue
if index2 < index1:
index1, index2 = index2, index1
componente_conexe[index1] += componente_conexe.pop(index2)
elif index1 is not None:
componente_conexe[index1].append(muchie2)
elif index2 is not None:
componente_conexe[index2].append(muchie1)
else:
componente_conexe.append([muchie1, muchie2])
nr_componente_conexe -= 1
with open("dfs.out", "w+") as f:
f.write(str(nr_componente_conexe))
if __name__ == "__main__":
main()