Cod sursa(job #2138443)

Utilizator danyvsDan Castan danyvs Data 21 februarie 2018 17:29:23
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 50005;

int n, m;
vector<int> G[NMAX];
stack<int> stck;
vector<bool> seen(NMAX, false);

void read() {
    fin >> n >> m;
    for (int i = 1; i <= m; ++ i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
}

void dfs(int node) {
    seen[node] = true;
    for (auto it : G[node])
        if (!seen[it])
            dfs(it);
    stck.push(node);
}

void topologicalSort() {
    for (int i = 1; i <= n; ++ i)
        if (!seen[i])
            dfs(i);
    while (!stck.empty()) {
        fout << stck.top() << " ";
        stck.pop();
    }
}

int main() {
    read();
    fin.close();
    topologicalSort();
    fout.close();
    return 0;
}