Cod sursa(job #2187452)

Utilizator Andrei17Andrei Pascu Andrei17 Data 26 martie 2018 15:29:08
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int N = 50002;

int n, m;
vector <int> a[N], q;
bool viz[N];

void citire() {
    in >> n >> m;

    int x, y;
    for (int i = 0; i < m; i++) {
        in >> x >> y;
        a[x].push_back(y);
    }

    in.close();
}

void dfs(int x) {
    viz[x] = true;

    for (int i = 0; i < a[x].size(); i++) {
        int y = a[x][i];
        if (!viz[y]) dfs(y);
    }

    q.push_back(x);
}

int main()
{
    citire();

    for (int i = 1; i <= n; i++) {
        if (!viz[i]) dfs(i);
    }

    for (int i = q.size() - 1; i >= 0; i--) out << q[i] << ' ';

    out.close();
}