Cod sursa(job #3357807)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 15:08:05
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <vector>

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

bool dfs(int node) {
    visited[node] = 1;
    for (const auto &x: graph[node]) {
        if (visited[x] == 1) return false;
        if (visited[x] == 0) {
            if (!dfs(x)) return false;
        }
    }
    visited[node] = 2;
    stack.push_back(node);
    return true;
}

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, 0);
    while (m--) {
        int x, y;
        input >> x >> y;
        graph[x].push_back(y);
    }

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

    for (int i = stack.size() - 1; i >= 0; --i) {
        output << stack[i] << " ";
    }

    return 0;
}