Cod sursa(job #3212056)

Utilizator KarinaDKarina Dumitrescu KarinaD Data 11 martie 2024 00:13:05
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream fin ( "sortaret" );
ofstream fout ( "sortaret" );

const int N = 50000;

vector <int> g[N + 10];
stack <int> st;

int viz[N + 10];

int sort_top ( int node ) {
    
    viz[node] = 1;
    
    for ( int i = 0; i < g[node].size(); i++ )
        if ( viz[g[node][i]] == 0 ) {
            sort_top ( g[node][i] );
        }
    
    st.push ( node );
    
    return 0;
}

int main () {
    
    int n, m, x, y;
    
    fin >> n >> m;
    
    for ( int i = 0; i < m; i++ ) {
        
        fin >> x >> y;
        
        g[x].push_back (y);
    }
    
    for ( int i = 1; i <= n; i++ )
        if ( viz[i] == 0 )
            sort_top ( i );
    
    while ( st.size() != 0 ) {
        fout << st.top() << " ";
        st.pop();
    }
    
    return 0;
}