Cod sursa(job #1637726)

Utilizator cautionPopescu Teodor caution Data 7 martie 2016 18:57:02
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>
#include <vector>

constexpr int kMaxN = 50000;

int n, m;
std::vector<int> edges[kMaxN+1];
bool visited[kMaxN+1];
std::vector<int> reversed_topological_order;

void dfs(int x) {
    for(int y : edges[x]) {
        if(!visited[y]) {
            visited[y] = true;
            dfs(y);
        }
    }
    reversed_topological_order.push_back(x);
}

int main()
{
    std::ifstream in("sortaret.in");
    std::ofstream out("sortaret.out");
    in>>n>>m;
    for(int x, y, i = 1; i <= n; ++i) {
        in>>x>>y;
        edges[x].push_back(y);
    }
    for(int i = 1; i <= n; ++i) {
        if(!visited[i]) dfs(i);
    }
    for(auto it = reversed_topological_order.rbegin(); it != reversed_topological_order.rend(); ++it) {
        out<<*it<<' ';
    }
    return 0;
}