Cod sursa(job #2572629)

Utilizator nTropicManescu Bogdan Constantin nTropic Data 5 martie 2020 13:37:21
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda OJI 2020 Marime 0.75 kb
#include <bits/stdc++.h>

using namespace std;

const int len = 100005;
int n, m, x, y;
vector<int> g[len], sol;
bool checked[len];

void dfs(int node) {
    checked[node] = true;
    for (auto it : g[node])
        if (!checked[it])
            dfs(it);
    sol.push_back(node);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    freopen("sortaret.in", "r", stdin);
    freopen("sortaret.out", "w", stdout);

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        cin >> x >> y;
        g[x].push_back(y);
    }

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

    reverse(sol.begin(), sol.end());
    for (auto it : sol)
        cout << it << " ";
}