Cod sursa(job #2678217)

Utilizator CalinusCalin Navadaru Calinus Data 28 noiembrie 2020 11:14:14
Problema Sortare topologica Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
#define Nmax 50001
using namespace std;

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

vector<int> graf[Nmax];
stack<int> sol;
int d_interior[Nmax];
int viz[Nmax];
int n;
int m;

void citire()
{
    int x, y;
    fin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        fin >> x >> y;
        d_interior[y]++;
        graf[x].push_back(y);
    }
}

void DFS(int i)
{
    for(unsigned int j = 0; j < graf[i].size(); j++)
    {
        if(!viz[graf[i][j]])
        {
            viz[graf[i][j]] = 1;
            DFS(graf[i][j]);
            sol.push(graf[i][j]);
        }
    }
}

void afisare()
{
    while(!sol.empty())
    {
        fout << sol.top() << ' ';
        sol.pop();
    }
}

void rezolvare()
{
    for(int i = 1; i <= n; i++)
    {
        if(d_interior[i] == 0)
        {
            viz[i] = 1;
            DFS(i);
            sol.push(i);
            afisare();
        }
    }
}



int main()
{
    citire();
    rezolvare();
    return 0;
}