Cod sursa(job #3322058)

Utilizator AlexN_04Nedelcu Alex AlexN_04 Data 12 noiembrie 2025 15:28:55
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

vector<vector<int>> gr;
vector<int> viz;
stack<int> rez;

void dfsTop(int x) {

    viz[x] = 1;
    for (int y : gr[x]) {
        if (viz[y] == 0) {
            dfsTop(y);
        }
    }
    rez.push(x);
}
int main() {

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

    int N, M;
    fin >> N >> M;

    viz.assign(N+1, 0);
    gr.resize(N+1);

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


    for (int i = 1; i <= N; i++) {
        if (viz[i] == 0) {
            dfsTop(i);
        }
    }

    while(!rez.empty()) {
        fout << rez.top() << " ";
        rez.pop();
    }

    fin.close();
    fout.close();

    return 0;
}