Cod sursa(job #2975783)

Utilizator Apyxabcdefghij Apyx Data 7 februarie 2023 16:07:21
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<int> v[100005];
vector<bool> viz;
vector<int> ans;

void dfs(int nod) {
    viz[nod] = true;
    for(auto x : v[nod]) {
        if(!viz[x]) {
            dfs(x);
        }
    }
    ans.emplace_back(nod);
}

void sorttop(int n) {
    viz.assign(n+1, false);
    ans.clear();
    for(int i = 1; i <= n; i++) {
        if(!viz[i]) {
            dfs(i);
        }
    }
    reverse(ans.begin(), ans.end());
}

int main() {
    int n, m; fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y; fin >> x >> y;
        v[x].emplace_back(y);
    }
    sorttop(n);
    for(auto x : ans) {
        fout << x << " ";
    }
    return 0;
}