Cod sursa(job #2756128)

Utilizator filicriFilip Crisan filicri Data 29 mai 2021 20:40:13
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.66 kb
#include <fstream>
#include <vector>
#define N_MAX 100001
using namespace std;

bool seen[N_MAX];
int n, m;
vector<int> G[N_MAX];

void dfs(int node) {
    seen[node] = true;
    for (const auto& ne: G[node]) {
        if (!seen[ne])
            dfs(ne);
    }
}

int main() {
    ifstream f("dfs.in");
    f >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    f.close();

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

    ofstream g("dfs.out");
    g << counter;
    g.close();

    return 0;
}