Cod sursa(job #2253221)

Utilizator Ioana_AndreeaCristescu Ioana Ioana_Andreea Data 3 octombrie 2018 19:41:34
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
const int NMax = 50000;
vector <int> G[NMax + 5];
int N,M;
bool Use[NMax + 5];
int Tsort[NMax + 5];

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

void DFS(int Nod)
{
    Use[Nod] = 1;
    for (int i = 0; i<(int)G[Nod].size(); i++)
    {
        int Vecin = G[Nod][i];

        if (Use[Vecin] == 0)
            DFS(Vecin);
    }
    Tsort[++Tsort[0]] = Nod;
}

void Print()
{
    reverse (Tsort + 1, Tsort + 1 + Tsort[0]);
    for (int i =1; i<=Tsort[0]; i++)
        fout<<Tsort[i]<<" ";
    fout<<"\n";
}

int main()
{
    Read();
    for (int i = 1; i<=N; i++)
        if (Use[i] == 0)
            DFS(i);
    Print();
    return 0;
}