Cod sursa(job #3248547)

Utilizator devilexeHosu George-Bogdan devilexe Data 12 octombrie 2024 10:31:09
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.61 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAXN = 1e5;
int N, M;
vector<int> G[MAXN + 1];
int viz[MAXN + 1];

void dfs(int n)
{
    viz[n] = 1;
    for (const int &x : G[n])
    {
        if (!viz[x])
            dfs(x);
    }
}

int main()
{
    fin >> N >> M;
    int a, b;
    while (M--)
    {
        fin >> a >> b;
        G[a].push_back(b);
        G[b].push_back(a);
    }
    int nrc = 0;
    for (int i = 1; i <= N; ++i)
    {
        if (!viz[i])
        {
            ++nrc;
            dfs(i);
        }
    }
    fout << nrc;
    return 0;
}