Cod sursa(job #3354002)

Utilizator cont_superscoalaSuperScoala cont_superscoala Data 13 mai 2026 13:00:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
/*
https://infoarena.ro/problema/dfs
*/
#include <fstream>
#include <vector>

using namespace std;

void dfs_rec(vector <vector <int>> &lst, int x, vector <bool> &viz)
{
    viz[x] = true;
    /// aici nu sunt necesare alte prelucrari
    for (auto y: lst[x])
    {
        if (!viz[y])
        {
            dfs_rec(lst, y, viz);
        }
    }
}

int main()
{
    ifstream in("dfs.in");
    ofstream out("dfs.out");
    int n, m;
    in >> n >> m;
    vector < vector <int>> lst(n + 1);
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        lst[x].push_back(y);
        lst[y].push_back(x);
    }
    vector <bool> viz(n + 1, false);
    int nr_cc = 0;
    for (int x = 1; x <= n; x++)
    {
        if (!viz[x])
        {
            nr_cc++;
            dfs_rec(lst, x, viz);
        }
    }
    out << nr_cc << "\n";
    in.close();
    out.close();
    return 0;
}