Cod sursa(job #3148537)

Utilizator andrei1807Andrei andrei1807 Data 2 septembrie 2023 14:42:25
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 50003;

vector<int> g[NMAX];
bool vis[NMAX];
int d[NMAX];
stack<int> res;

void dfs(int nod) {
    vis[nod] = true;

    for (auto v : g[nod]) {
        if (!vis[v]) {
            dfs(v);
        }
    }

    res.push(nod);
}

int main() {

    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;

        g[x].push_back(y);
        d[y]++;
    }

    for (int nod = 1; nod <= n; nod++) {
        if (d[nod] == 0)
            dfs(nod);
    }

    while (!res.empty()) {
        int x = res.top();
        res.pop();

        fout << x << ' ';
    }


    return 0;
}