Cod sursa(job #3039303)

Utilizator ioana3317ioanapopescu ioana3317 Data 28 martie 2023 13:14:48
Problema Sortare topologica Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#include <stack>

using namespace std;

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

const int N =50000 + 2;
struct element{
    int vf, urm;
};

element v[N];
stack <int> stiv;
int n, m, nr, lst[N];
bool viz[N];

void adg(int x, int y){
    nr ++;
    v[nr].vf = y;
    v[nr].urm =  lst[x];
    lst[x]= nr;
}

void dfs(int nd){
    viz[nd] = 1;

    for(int i = lst[nd]; i !=0; i = v[i].urm ){
        int x= v[i].vf;
        if( viz[x] == 0){
            dfs(x);
        }
    }
    stiv.push(nd);
}

int main()
{
    in >> n >> m;
    for(int i=1; i<=m; i++){
        int x, y;
        in >> x >> y;
        adg(x, y);
    }

    for(int i=1; i<=n; i++){
        if( viz[i] == 0){
            dfs(i);
        }
    }

    while( !stiv.empty() ){
        int x=stiv.top();
        out << x << " ";
        stiv.pop();
    }

    return 0;
}