Cod sursa(job #2152177)

Utilizator CammieCamelia Lazar Cammie Data 5 martie 2018 12:18:07
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
#include <vector>

#define MAXN 50005

using namespace std;

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

int n, m, viz[MAXN], postordine[MAXN], nn;
vector <int> graph[MAXN];

inline void Read() {
    int x, y;

    fin >> n >> m;

    for (int i = 1; i <= m; i++) {
        fin >> x >> y;

        graph[x].push_back(y);
    }
}

inline void DFS(int node) {
    viz[node] = 1;

    for (auto x : graph[node]) {
        if (!viz[x])
            DFS(x);
    }

    postordine[++nn] = node;
}

inline void Solve() {
    for (int i = 1; i <= n; i++) {
        if (!viz[i])
            DFS(i);
    }

    for (int i = nn; i; i--)
        fout << postordine[i] << " ";
}

int main () {
    Read();
    Solve();

    fin.close(); fout.close(); return 0;
}