Cod sursa(job #2529455)

Utilizator georgecristian2002Raducanu George-Cristian georgecristian2002 Data 23 ianuarie 2020 15:39:29
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>

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

const int dim = 100005, n_max = 50005;

int vf[dim],urm[dim],lst[dim],nr,n,m,predecesor[n_max],st[n_max],dr = -1,viz[n_max];

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

void dfs(int nod)
{

    viz[nod] = 1;
    for (int p=lst[nod]; p!=0; p = urm[p])
    {
        int y = vf[p];
        if (!viz[y])
        {
           dfs(y);
        }
    }
    st[++dr] = nod;
}

int main()
{
    int x,y;
    fin >> n >> m;
    for (int i=1; i<=m; i++)
    {
         fin >> x >> y;
         adauga(x,y);
    }
    for (int i=1; i<=n; i++)
    {
        if (!viz[i])
        {
          dfs(i);
        }
    }
    while (dr >= 0)
    {
        fout << st[dr--] << " ";
    }
    fin.close();
    fout.close();
    return 0;
}