Cod sursa(job #3352636)

Utilizator TonyyAntonie Danoiu Tonyy Data 29 aprilie 2026 19:52:38
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
using namespace std;

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

const int nMax = 1e5 + 1;
int n, m;
vector<int> List[nMax];
bool visited[nMax];

void dfs(int node) {
    visited[node] = 1;
    for (const int& i : List[node]) {
        if (!visited[i]) {
            dfs(i);
        }
    }
}

int main() {
    ios::sync_with_stdio(false);

    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        List[x].push_back(y);
    }
    int ans = 0;
    for (int node = 1; node <= n; node++) {
        if (!visited[node]) {
            dfs(node);
            ans++;
        }
    }
    fout << ans;

    fin.close();
    fout.close();
    return 0;
}