Cod sursa(job #3316834)

Utilizator code_blocksSpiridon Mihnea-Andrei code_blocks Data 21 octombrie 2025 12:43:17
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.63 kb
#include <fstream>
#include <vector>

using namespace std;

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

bool v[100001];
vector<int> A[100001];
int n, m;

void dfs(int x)
{
    v[x] = true;
    for(const auto& y : A[x])
        if(!v[y])
            dfs(y);
}

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

    int k = 0;
    for(int i = 1; i <= n; i++)
    {
        if(!v[i])
        {
            k++;
            dfs(i);
        }
    }

    fout << k;

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

    return 0;
}