Cod sursa(job #1589915)

Utilizator AnesthesicChereches Sergiu Alexandru Anesthesic Data 4 februarie 2016 16:03:41
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <stack>
#define nmax 50005
using namespace std;

void read_data (int &n, vector <int> v[nmax]){
    ifstream fin ("sortaret.in");
    int m;
    fin >> n >> m;
    for (int i = 1; i <= m; i++){
        int x, y;
        fin >> x >> y;
        v[x].push_back (y);
    }
}

void dfs (int x, int n, bool seen[nmax], vector <int> v[nmax], stack <int> &s){
    seen[x] = true;
    for (auto neigh : v[x])
        if (!seen[neigh])
            dfs (neigh, n, seen, v, s);
        s.push(x);
}

void solve (bool seen[nmax], int n, vector <int> v[nmax]){
    ofstream fout ("sortaret.out");
    stack <int> s;
    for (int i = 1; i <= n; i++)    seen[i] = 0;
    for (int i = 1; i <= n; i++)
        if (!seen[i])
            dfs (i, n, seen, v, s);
    while (!s.empty ()){
        fout << s.top () << " ";
        s.pop ();
    }
}

int main(){
    vector <int> v[nmax];
    stack <int> s;
    int n;
    bool seen[nmax];
    read_data (n, v);
    solve (seen, n, v);
    return 0;
}