Cod sursa(job #1819262)

Utilizator Tiberiu02Tiberiu Musat Tiberiu02 Data 30 noiembrie 2016 14:09:55
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
# include <fstream>
# include <vector>
# include <algorithm>

using namespace std;

# define MAX_N 150000
vector<int> v[1 + MAX_N];

unsigned char mark[1 + MAX_N];
# define UNMARKED 0
# define TEMPORARILY_MARKED 1
# define PERMANENTLY_MARKED 2

vector<int> sol;

void DFS( int n, ofstream &fout )
{
    if ( mark[n] != UNMARKED )
        return;

    mark[n] = TEMPORARILY_MARKED;

    for ( int i : v[n] )
        DFS( i, fout );

    mark[n] = PERMANENTLY_MARKED;

    sol.push_back( n );
}

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

    ios::sync_with_stdio( false );

    int n, m, i, a, b;

    fin >> n >> m;

    for ( i = 0; i < m; i ++ ) {
        fin >> a >> b;
        v[a].push_back( b );
    }

    for ( i = 1; i <= n; i ++ )
        DFS( i, fout );

    reverse( sol.begin(), sol.end() );
    for ( int i : sol )
        fout << i << ' ';
    fout << endl;

    fin.close();
    fout.close();

    return 0;
}