Cod sursa(job #3228578)

Utilizator FredyLup Lucia Fredy Data 8 mai 2024 23:04:01
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
// Problem statement: https://www.infoarena.ro/problema/dfs

#include <fstream>
#include <vector>

using namespace std;

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

#define maxN 100001

int n, m;
vector <int> G[maxN];
bool visited[maxN];

void dfs(int node) {
    visited[node] = true;
    for(auto it : G[node]) {
        if(!visited[it]) {
            dfs(it);
        }
    }
}

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

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

    fout<<nrComponents;

    fin.close();
    return 0;
}