Cod sursa(job #2721667)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 12 martie 2021 08:12:02
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
using namespace std;

int n, m;
bool visited[100100];
vector<int> edges[100100];
stack<int> s;

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]);
        }
        s.push(x);
    }
}

int main() {
    fin.tie(0);
    ios::sync_with_stdio(0);
    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);
        }
    }
    while(!s.empty()) {
        fout << s.top() << " ";
        s.pop();
    }

}