Cod sursa(job #2720355)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 10 martie 2021 19:14:17
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

vector<int> edges[100010];
stack<int> topological_order;
bool visited[50010];

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

void dfs(int x) {
    if (visited[x] == false) {
        visited[x] = true;
        for (int i = 0; i < edges[x].size(); ++i) {
            dfs(edges[x][i]);
            topological_order.push(edges[x][i]);
        }
    }
}

int main() {
    fin.tie(0);
    ios::sync_with_stdio(0);
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        edges[x].push_back(y);
    }
    for (int i = 1; i <= n; ++i) {
        if (visited[i] == false) {
            dfs(i);
            topological_order.push(i);
        }
    }
    while(!topological_order.empty()) {
        fout << topological_order.top() << " ";
        topological_order.pop();
    }
    return 0;
}