Cod sursa(job #2929195)

Utilizator vali2wdAdrian Valentin Nafornita vali2wd Data 25 octombrie 2022 01:52:41
Problema Componente tare conexe Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 1.27 kb
file = open("ctc.in")
line = file.readline().split()
noNodes = int(line[0])
noEdges = int(line[1])

graph, graphT = {c:[] for c in range(noNodes+1)}, {c:[] for c in range(noNodes+1)}

for line in file:
    line = line.split()
    x = int(line[0])
    y = int(line[1])

    graph[x].append(y)
    graphT[y].append(x)


myStack = []
myVisited = []

def DFS(node):
    myVisited.append(node)
    myStack.append(node)
    for neighbor in graph[node]:
        if neighbor not in myVisited:
            DFS(neighbor)

lis = []
def DFSt(node):
    # print(node, end = "")
    global lis
    lis += [node]
    myVisited.append(node)
    for neighbor in graphT[node]:
        if neighbor not in myVisited:
            DFSt(neighbor)

for x in graph.keys():
    if x not in myVisited:
        DFS(x)

myVisited.clear()
output = []
noCT = 0
for x in list(graphT.keys())[1:]:
    if x not in myVisited:
        DFSt(x)
        noCT += 1
        x = lis.copy()
        output.append(x)
        lis.clear()

endResult = open("ctc.out",'w')
buf = str
buf = f"{noCT}"
for x in output:
    buf = buf + '\n' + str(x)
buf = buf.replace('[','')
buf = buf.replace(']','')
buf = buf.replace(',','')
endResult.write(buf)
# print(noCT, *output, sep='\n', end="")