Cod sursa(job #2717643)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 7 martie 2021 19:00:06
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
#define ll long long
#define nxM 200010
using namespace std;

int noduri, muchii, fr[200000], ans;
vector<int> vecini[200000];

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

void DFS(int i) {
    if (fr[i] == 0) {
        fr[i] = 1;
        for (int j = 0; j < vecini[i].size(); ++j) {
            DFS(vecini[i][j]);
            fr[vecini[i][j]] = 1;
        }
    }
}

int main() {
    fin.tie(0);
    ios::sync_with_stdio(0);
    fin >> noduri >> muchii;
    for (int i = 1; i <= muchii; ++i) {
        int x, y;
        fin >> x >> y;
        vecini[x].push_back(y);
        vecini[y].push_back(x);
    }
    for (int i = 1; i <= noduri; ++i) {
        if (fr[i] == 0) {
            ++ans;
            DFS(i);
        }
    }
    fout << ans;
    return 0;
}