Cod sursa(job #2758839)

Utilizator lucidanescu28Danescu Lucian lucidanescu28 Data 13 iunie 2021 12:59:01
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.65 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

const int DIM = 1e5 + 1;

vector <int> adj[DIM], top_sort;
bool visited[DIM];

void DFS(int node) {
    visited[node] = true;

    for (auto neigh : adj[node]) {
        if (!visited[neigh]) DFS(neigh);
    }

    top_sort.push_back(node);
}

int main() {
    int N, M;

    fin >> N >> M;
    while (M--) {
        int x, y;
        fin >> x >> y;
        adj[x].push_back(y);
    }

    for (int i = 1; i <= N; i++) {
        if (!visited[i]) DFS(i);
    }

    for (int i = top_sort.size() - 1; i >= 0; i--) fout << top_sort[i] << " ";

    return 0;
}