Cod sursa(job #2975722)

Utilizator Apyxabcdefghij Apyx Data 7 februarie 2023 11:47:58
Problema Sortare topologica Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 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, 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;
}