Cod sursa(job #2603013)

Utilizator sichetpaulSichet Paul sichetpaul Data 18 aprilie 2020 13:48:42
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.62 kb
#include <bits/stdc++.h>
#define Nmax 50005
using namespace std;

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

int N, M, K;
int ans[Nmax];
bool in[Nmax], vis[Nmax];
vector<int> G[Nmax];

void DFS(int node) {
    vis[node] = 1;
    for (auto it : G[node])
        if (!vis[it]) DFS(it);
    ans[++K] = node;
}
int main()
{
    f >> N >> M;
    while (M--) {
        int x, y;
        f >> x >> y;
        in[y] = 1;
        G[x].push_back(y);
    }

    for (int i = 1; i <= N; ++i)
       if (in[i] == 0) DFS(i);

    for (int i = N; i >= 1; --i)
        g << ans[i] << " ";

    return 0;
}