Cod sursa(job #3154673)

Utilizator stefanrotaruRotaru Stefan-Florin stefanrotaru Data 5 octombrie 2023 16:29:35
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");

vector <int> a[100005];
bool viz[100005];
int cnt, n, m;

void dfs(int nod)
{
    viz[nod] = 1;

    for (int st = 0, dr = a[nod].size(); st < dr; ++st) {
        if (!viz[a[nod][st]]) {
            dfs(a[nod][st]);
        }
    }
}

int main()
{
    f >> n >> m;

    for (int i = 1; i <= m; ++i) {
        int x, y;
        f >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }

    for (int i = 1; i <= n; ++i) {
        if(!viz[i]) {
            cnt++;
            dfs(i);
        }
    }

    g << cnt;

    return 0;
}