Cod sursa(job #3040464)

Utilizator AleXutzZuDavid Alex Robert AleXutzZu Data 29 martie 2023 21:47:01
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <iostream>
#include <fstream>
#include <vector>

std::vector<std::vector<int>> graph;
std::vector<bool> visited;
std::vector<int> stack;


void dfs(int node) {
    for (const auto &x: graph[node]) {
        if (!visited[x]) {
            visited[x] = true;
            dfs(x);
        }
    }
    stack.push_back(node);
}

int main() {
    std::ifstream input("sortaret.in");
    std::ofstream output("sortaret.out");

    int n, m;
    input >> n >> m;

    graph.resize(n + 1);
    visited.resize(n + 1, false);
    while (m--) {
        int x, y;
        input >> x >> y;
        graph[x].push_back(y);
    }

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

    while (!stack.empty()) {
        output << stack.back() << " ";
        stack.pop_back();
    }

    return 0;
}