Cod sursa(job #1575664)

Utilizator tudormaximTudor Maxim tudormaxim Data 21 ianuarie 2016 18:20:06
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int nmax = 50005;
vector <int> g[nmax], sol;
bool viz[nmax];

void dfs(int dad)
{
    int i, son;
    viz[dad]=true;
    for(i=0; i<g[dad].size(); i++)
    {
        son=g[dad][i];
        if(!viz[son]) dfs(son);
    }
    sol.push_back(dad);

}

int main()
{
    ifstream fin ("sortaret.in");
    ofstream fout ("sortaret.out");
    ios_base::sync_with_stdio(false);
    int n, m, i, x, y;
    fin >> n >> m;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y;
        g[x].push_back(y);
    }
    for(i=1; i<=n; i++)
        if(viz[i]==false) dfs(i);

    for(i=sol.size()-1; i>=0; i--)
        fout << sol[i] << " ";
    fin.close();
    fout.close();
    return 0;
}