Cod sursa(job #3336546)

Utilizator SomethingAndrei Marian Something Data 24 ianuarie 2026 21:36:00
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

ifstream f("sortaret.in");
ofstream g("sortaret.out");

// Solutia recursiva
void DFS(vector<vector<int>>& lista, vector<int>& viz, int x)
{
    g << x << " ";
    viz[x - 1] = 1;
    for(int vecin : lista[x - 1])
        if(viz[vecin - 1] == 0)
            DFS(lista, viz, vecin);
}

// Solutia iterativa
// void DFS(vector<vector<int>>& lista, vector<int>& viz, int x)
// {
//     viz[x - 1] = 1;
//     stack<int> stiva;
//     stiva.push(x);
//     while(!stiva.empty())
//     {
//         int nod = stiva.top();
//         stiva.pop();
//         cout << nod << " ";
//         for(int vecin : lista[nod - 1])
//         {
//             if(viz[vecin - 1] == 0)
//             {
//                 viz[vecin - 1] = 1;
//                 stiva.push(vecin);
//             }
//         }
//     }
// }

int main()
{
    int n, m, x, y;
    f >> n >> m;
    vector<vector<int>> lista(n);
    for(int i = 0; i < m; i++)
    {
        f >> x >> y;
        lista[x - 1].push_back(y);
        lista[y - 1].push_back(x);
    }

    vector<int> viz(n, 0);
    int comp_conexe = 0;
    // for(int i = 0; i < n; i++)
    DFS(lista, viz, 1);

    return 0;
}