Cod sursa(job #2024860)

Utilizator S4lexandruAlexandru Stefanica S4lexandru Data 21 septembrie 2017 13:14:03
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include <array>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iterator>


constexpr int MAX_VERTEX=50011;


std::vector<int> order;
std::vector<int> G[MAX_VERTEX];
std::array<bool, MAX_VERTEX> was;

void dfs(int x) {
    was[x] = true;

    for (auto y: G[x]) {
        if (!was[y]) {
            dfs(y);
        }
    }

    order.push_back(x);
}

int main() {
    int N, M;
    std::ifstream in{"sortaret.in"};
    std::ofstream out{"sortaret.out"};

    for (in >> N >> M; M; --M) {
        int x, y;
        in >> x >> y;
        G[x].push_back(y);
    }

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

    std::copy(order.rbegin(), order.rend(), std::ostream_iterator<int>{out, " "});

    return 0;
}