Cod sursa(job #3166367)

Utilizator AlexInfoIordachioaiei Alex AlexInfo Data 8 noiembrie 2023 17:31:21
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

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

typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
#define fi first
#define se second

#define NMAX 100005
#define MOD 1999999973
#define INF 0x3f3f3f3f

int n, m;
bool visited[NMAX];
vector<vector<int>> graf(NMAX);
vector<int> top;

void read()
{
    int x, y;
    in >> n >> m;
    for (int i = 1; i <= m; i++)
        in >> x >> y, graf[x].push_back(y);
}

void DFS(int node)
{
    if (visited[node])
        return;

    visited[node] = 1;
    for (auto e : graf[node])
        DFS(e);

    top.push_back(node);
}

void solve()
{
    for (int i = 1; i <= n; i++)
        if (!visited[i])
            DFS(i);

    reverse(top.begin(), top.end());
    for (auto e : top)
        out << e << ' ';
}

int main()
{
    read();
    solve();
    return 0;
}