Cod sursa(job #2539948)

Utilizator cip_ionescuCiprian Ionescu cip_ionescu Data 6 februarie 2020 15:57:59
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>

#define MAX_N 50000

using std::cin;
using std::cout;

std::vector<int> g[1 + MAX_N];
bool v[1 + MAX_N];
std::stack<int> s;

void top_sort(int x) {
    v[x] = true;
    for (const auto& it : g[x])
        if (!v[it]) top_sort(it);

    s.push(x);
}

int main(int argc, char const *argv[])
{
    std::ifstream fin("sortaret.in");
    std::ofstream fout("sortaret.out");

    int n, m, x, y;

    fin >> n >> m;
    for (int i = 1 ; i <= m ; i++) {
        fin >> x >> y;
        g[x].push_back(y);
    }

    for (int i = 1 ; i <= n ; i++)
        if (!v[i]) top_sort(i);
    
    while (!s.empty()) {
        fout << s.top() << ' ';
        s.pop();
    }
    return 0;
}