Cod sursa(job #2449060)

Utilizator voyagerSachelarie Bogdan voyager Data 18 august 2019 00:24:23
Problema Sortare topologica Scor 80
Compilator py Status done
Runda Arhiva educationala Marime 0.58 kb
#!/usr/bin/env python3

import sys

sys.stdout = open('sortaret.out', 'w')

with open('sortaret.in', 'r') as fin:
    readInts = lambda: tuple(map(int, fin.readline().split()))
    N, M = readInts()
    edges = [[] for _ in range(N + 1)]
    visited = [False] * (N + 1)
    for _ in range(M):
        s, t = readInts()
        edges[s].append(t)

    order = []
    def visit(x):
        if visited[x]: return
        visited[x] = True

        for t in edges[x]:
            visit(t)
        order.append(str(x))
    for n in range(1, N + 1):
        visit(n)

    print(' '.join(reversed(order)))