Cod sursa(job #2581112)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 14 martie 2020 15:59:47
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <bits/stdc++.h>
#define MAX 100000

using namespace std;

vector<int>graph[MAX + 5];
bool vizitat[MAX + 5];

void dfs(int nod)
{
    vizitat[nod] = 1;

    for(auto x : graph[nod])
        if(!vizitat[x])
            dfs(x);
}

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

    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    srand(time(NULL));

    int n, m;

    fin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int a, b;

        fin >> a >> b;

        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    int cnt = 0;
    for(int i = 1; i <= n; i++)
    {
        if(!vizitat[i])
        {
            cnt++;

            dfs(i);
        }
    }

    fout << cnt;

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

    return 0;
}