Cod sursa(job #2453868)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 6 septembrie 2019 12:50:16
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <unordered_map>

using namespace std;

using Graph = vector<vector<int>>;

void dfs(Graph &graph, int node, vector<bool> &visited, vector<int> &topsort){
    visited[node] = true;

    for (int x: graph[node]){
        if (!visited[x]){
            dfs(graph, x, visited, topsort);
        }
    }

    topsort.push_back(node);
}

int main() {
    ios_base::sync_with_stdio(false);

    ifstream in("sortaret.in");
    ofstream out("sortaret.out");

    int n, m;
    in >> n >> m;

    Graph graph;
    graph.resize(n);

    while (m--){
        int a, b;
        in >> a >> b;
        a--; b--;

        graph[a].push_back(b);
    }

    vector<bool> visited(n, false);
    vector<int> topsort;

    for (int i = 0; i < n; i++){
        if (!visited[i]){
            dfs(graph, i, visited, topsort);
        }
    }

    reverse(begin(topsort), end(topsort));

    for_each(begin(topsort), end(topsort), [&](auto x){
        out << x + 1 << " ";
    });

    return 0;
}