Cod sursa(job #3308576)

Utilizator tudorvoieVoie Tudor tudorvoie Data 26 august 2025 12:22:40
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;
vector<int> v[50001];
vector<int> topo;
int viz[50001];

void dfs(int x) {
    if(!viz[x]) {
        viz[x] = 1;
        for(auto i : v[x]) {
            dfs(i);
        }

        // doar aici adaug in lista cu noduri in ordine sortata
        topo.push_back(x);
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
    }

    // verificam sa nu fie componente conexe
    for(int i = 1; i <= n; i++) {
        if(!viz[i]) {
            dfs(i);
        }
    }

    // aici musai se da reverse
    // deoarece inainte am recursia
    // bfs(i) si dupa doar bag nodu curent in lista
    reverse(topo.begin(), topo.end());
    for(auto i : topo) {
        fout << i << " ";
    }
    return 0;
}