Cod sursa(job #3271377)

Utilizator andu9andu nita andu9 Data 25 ianuarie 2025 21:02:28
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>
#include <bitset>

const int nMax = 5e4;

void DFS(std::vector<std::vector<int>>& graph, std::bitset<nMax>& vis,
         std::vector<int>& topSort, int currNode, int& currSize) {
    vis[currNode] = true;
    for (int& next : graph[currNode]) {
        if (vis[next] == false) {
            DFS(graph, vis, topSort, next, currSize);
        }
    }
    topSort[currSize] = currNode, currSize += 1;
}

int main() {
    std::ifstream fin("sortaret.in");
    std::ofstream fout("sortaret.out");

    int n, m; fin >> n >> m;
    std::vector<std::vector<int>> graph(n, std::vector<int>());
    for (int i = 0; i < m; i += 1) {
        int u, v; fin >> u >> v; u -= 1, v -= 1;
        graph[u].emplace_back(v);
    }

    std::bitset<nMax> vis;
    std::vector<int> topSort(n, -1);
    int Size = 0;
    for (int i = 0; i < n; i += 1) {
        if (vis[i] == false) {
            DFS(graph, vis, topSort, i, Size);
        }
    }

    for (auto it = topSort.rbegin(); it != topSort.rend(); ++it) {
        fout << *it + 1 << ' ';
    }

    graph.clear(), topSort.clear();
    fin.close(), fout.close();
    return 0;
}