Cod sursa(job #447408)

Utilizator alexandru92alexandru alexandru92 Data 28 aprilie 2010 17:17:02
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on April 28, 2010, 5:09 PM
 */
#include <stack>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iterator>
#define Nmax 50011

/*
 * 
 */
using namespace std;
int uz[Nmax];
stack< int > S;
vector< int > v;
vector< int > G[Nmax];
vector< int >::const_iterator it, iend;
inline void dfs( int x )
{
    while( true )
    {
        for( it=G[x].begin()+uz[x], iend=G[x].end(); it < iend; ++it )
            if( !uz[*it] )
                break;
        uz[x]=it-G[x].begin()+1;
        if( it >= iend )
        {
            v.push_back(x);
            break;
        }
        S.push(x);
        x=*it;
    }
}
int main(int argc, char** argv)
{
    int N, M, x, y;
    ifstream in( "sortaret.in" );
    for( in>>N>>M; M; --M )
    {
        in>>x>>y;
        G[x].push_back(y);
    }
    for( x=1; x <= N; ++x )
        if( !uz[x] )
        {
            y=x;
            while( true )
            {
                dfs(y);
                if( S.empty() )
                    break;
                y=S.top(); S.pop();
                //v.push_back(y);
            }
        }
    ofstream out( "sortaret.out" );
    copy( v.rbegin(), v.rend(), ostream_iterator<int>( out, " " ) );
    out<<'\n';
    return (EXIT_SUCCESS);
}