Cod sursa(job #3368056)

Utilizator David_3983098710Dav Abc David_3983098710 Data 13 octombrie 2026 10:24:57
Problema Parcurgere DFS - componente conexe Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 1.34 kb
# https://infoarena.ro/problema/dfs

def find_exista(componente_conexe: list[set[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[set[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].update(componente_conexe.pop(index2))
        elif index1 is not None:
            componente_conexe[index1].add(muchie2)
        elif index2 is not None:
            componente_conexe[index2].add(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()