Cod sursa(job #3153292)

Utilizator trifangrobertRobert Trifan trifangrobert Data 29 septembrie 2023 00:49:59
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

vector <vector <int>> graph;
vector <bool> vis;
vector <int> topo;

void dfs(int node) {
    vis[node] = true;
    for (auto& x : graph[node]) {
        if (!vis[x]) {
            dfs(x);
        }
    }
    topo.push_back(node);
}

int main() {
    ifstream fin("sortaret.in");
    ofstream fout("sortaret.out");
    int N, M;
    fin >> N >> M;
    graph = vector <vector <int>>(N, vector <int>());
    vis = vector <bool>(N, false);
    for (int i = 0;i < M;++i) {
        int u, v;
        fin >> u >> v;
        --u; --v;
        graph[u].push_back(v);
    }
    for (int i = 0;i < N;++i) {
        if (vis[i] == false) {
            dfs(i);
        }
    }
    reverse(topo.begin(), topo.end());
    for (auto& x : topo) {
        fout << x + 1 << " ";
    }
    fin.close();
    fout.close();
    return 0;
}