Cod sursa(job #3308573)

Utilizator tudorvoieVoie Tudor tudorvoie Data 26 august 2025 12:20:28
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;
vector<int> v[50001];
vector<int> topo;
int viz[50001];

void dfs(int x) {
    if(!viz[x]) {
        viz[x] = 1;
        for(auto i : v[x]) {
            dfs(i);
        }
        topo.push_back(x);
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
    }

    for(int i = 1; i <= n; i++) {
        if(!viz[i]) {
            dfs(i);
        }
    }

    reverse(topo.begin(), topo.end());
    for(auto i : topo) {
        fout << i << " ";
    }
    return 0;
}