Cod sursa(job #2284909)

Utilizator AlexPop28Pop Alex-Nicolae AlexPop28 Data 17 noiembrie 2018 19:01:42
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
#define all(cont) cont.begin(), cont.end()
#define pb push_back
#define fi first
#define se second
#define DEBUG(x) cerr << (#x) << ": " << (x) << '\n'

using namespace std;

typedef pair <int, int> pii;
typedef vector <int> vi;
typedef long long ll;
typedef unsigned long long ull;

ifstream f ("sortaret.in");
ofstream g ("sortaret.out");

const int NMAX = 5e4 + 5;

int n, m;
bool vis[NMAX];
vi adj[NMAX];
vi ans;

void dfs (int node) {
    vis[node] = 1;
    for (int &x : adj[node]) {
        if (!vis[x]) {
            dfs (x);
        }
    }
    ans.pb (node);
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
#ifdef LOCAL_DEFINE
    freopen (".in", "r", stdin);
#endif
    f >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        f >> x >> y;
        adj[x].pb (y);
    }

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

    for (int i = n - 1; i >= 0; --i) {
        g << ans[i] << ' ';
    }

    f.close();
    g.close();
    return 0;
}