Cod sursa(job #2540134)

Utilizator i.uniodCaramida Iustina-Andreea i.uniod Data 6 februarie 2020 19:34:39
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

const int NMAX = 5e4 + 5;
int N, M;
bool visited[NMAX];
vector <int> G[NMAX];
stack <int> st;

void DFS(int start)
{
    visited[start] = true;

    for(auto it : G[start])
        if( !visited[it] )
            DFS(it);

    st.push(start);
}

int main ()
{
    fin >> N >> M;
    int x, y;
    for(int i = 1; i <= M; ++ i) {
        fin >> x >> y;
        G[x].push_back(y);
    }

    for(int i = 1; i <= N; ++ i)
        if( !visited[i] )
            DFS(i);

    while( !st.empty() ) {
        fout << st.top() << ' ';
        st.pop();
    }
    return 0;
}