Cod sursa(job #2725855)

Utilizator preda.andreiPreda Andrei preda.andrei Data 19 martie 2021 19:16:38
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>

using namespace std;

using Graph = vector<vector<int>>;

void Dfs(const Graph& graph, vector<bool>& used, int node, vector<int>& order) {
    used[node] = true;
    for (const auto& other : graph[node]) {
        if (!used[other]) {
            Dfs(graph, used, other, order);
        }
    }
    order.push_back(node);
}

vector<int> Sort(const Graph& graph) {
    vector<bool> used(graph.size(), false);
    vector<int> order;
    order.reserve(graph.size());

    for (size_t i = 0; i < graph.size(); i += 1) {
        if (!used[i]) {
            Dfs(graph, used, i, order);
        }
    }
    return order;
}

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

    int nodes, edges;
    fin >> nodes >> edges;

    Graph graph(nodes);
    for (auto i = 0; i < edges; i += 1) {
        int a, b;
        fin >> a >> b;
        graph[b - 1].push_back(a - 1);
    }

    auto order = Sort(graph);
    for (const auto& node : order) {
        fout << node + 1 << " ";
    }
    fout << "\n";

    return 0;
};