Cod sursa(job #2241782)

Utilizator cosmin.pascaruPascaru Cosmin cosmin.pascaru Data 16 septembrie 2018 22:53:36
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <algorithm>
#include <vector>
#include <stack>
#include <assert.h>

using LL = long long;
using ULL = int long long;

const std::string _problemName = "sortaret";

namespace std {
std::ifstream fin(_problemName + ".in"); 
std::ofstream fout(_problemName + ".out"); 
}

#define cin fin
#define cout fout

std::vector< std::vector<int> > g;
std::vector<bool> visited;

void dfs(std::stack<int>& topologicalSort, int node) {
    visited[node] = true;

    for (auto neighbour : g[node]) {
        if (!visited[neighbour]) {
            dfs(topologicalSort, neighbour);
        }
    }

    topologicalSort.push(node);
}

int main() {

    int n, m;
    std::cin >> n >> m;

    g.resize(n);
    visited.resize(n, false);

    for (int i = 0; i < m; ++i) {
        int x, y;
        std::cin >> x >> y;

        --x; --y;
        g[x].push_back(y);
    }

    std::stack<int> topologicalSort;
    for (int node = 0; node < n; ++node) {
        if (!visited[node]) {
            dfs(topologicalSort, node);
        }
    }

    while (!topologicalSort.empty()) {
        std::cout << topologicalSort.top() + 1 << ' ';
        topologicalSort.pop();
    }
    std::cout << '\n';

    return 0;
}