Cod sursa(job #3295050)

Utilizator DrugeaCasiandrugea DrugeaCasian Data 1 mai 2025 22:51:57
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

const int MAXN = 50005;

vector<int> adj[MAXN];
bool visited[MAXN];
stack<int> result;
int N, M;

void dfs(int node) {
    visited[node] = true;
    for (int neighbour : adj[node]) {
        if (!visited[neighbour]) {
            dfs(neighbour);
        }
    }
    result.push(node);
}

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

    fin >> N >> M;
    for (int i = 0; i < M; ++i) {
        int x, y;
        fin >> x >> y;
        adj[x].push_back(y);
    }

    for (int i = 1; i <= N; ++i) {
        if (!visited[i]) {
            dfs(i);
        }
    }

    while (!result.empty()) {
        fout << result.top() << ' ';
        result.pop();
    }

    return 0;
}