Cod sursa(job #2618782)

Utilizator Tudor_PascaTudor Pasca Tudor_Pasca Data 26 mai 2020 00:03:36
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

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

int n, m;
bool fr[50100];
vector<vector<int>> v;
stack<int> ans;

void topSort(int start)
{
    fr[start] = 1;

    int nLen = v[start].size();

    /*cout << start << '\n';

    for(int i = 0; i < nLen; i++)
        cout << v[start][i] << ' ';

    cout << "\n\n";*/

    for(int i = 0; i < nLen; i++)
        if(fr[v[start][i]] == 0)
            topSort(v[start][i]);

    ans.push(start);
}

int main()
{
    in >> n >> m;
    v.resize(n + 5);

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

        v[x].push_back(y);
    }

    for(int i = 1; i <= n; i++)
        if(fr[i] == 0)
            topSort(i);

    while(!ans.empty())
    {
        out << ans.top() << ' ';

        ans.pop();
    }

    return 0;
}