Cod sursa(job #3366701)

Utilizator robert_dumitruDumitru Robert Ionut robert_dumitru Data 3 octombrie 2026 15:59:55
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.67 kb
#include <fstream>
#include <iostream>
#include <vector>

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

int n, m, components;
int c[100005];
std::vector<int> L[100005];

void dfs(int k) {
    c[k] = components;
    for (int w : L[k]) {
        if (c[w] == 0) {
            dfs(w);
        }
    }
}

int main() {
    int x, y;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    for (int i = 1; i <= n; i++) {
        if (c[i] == 0) {
            components++;
            dfs(i);
        }
    }

    fout << components << "\n";
    fout.close();
}