Cod sursa(job #2886750)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 8 aprilie 2022 11:53:11
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const string filename = "sortaret";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int maxN = 50005;
int n, m;
bool used[maxN];
vector <int> G[maxN], ans;

void dfs(int nod)
{
    used[nod] = 1;
    for(int vecin : G[nod])
        if(!used[vecin])
            dfs(vecin);
    ans.push_back(nod);
}

int main()
{
    fin >> n >> m;
    for(int x, y, i = 1; i <= m; i++)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
    for(int i = 1; i <= n; i++)
        if(!used[i])
            dfs(i);
    reverse(ans.begin(), ans.end());
    for(int nod : ans)
        fout << nod << ' ';
    return 0;
}