Cod sursa(job #2529440)

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

using namespace std;

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

const int dim = 100005;
const int n_max = 50005;
int vf[dim],urm[dim],lst[dim],nr,n,m,predecesor[n_max],coada[n_max],st,dr = -1;

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

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