Cod sursa(job #2953914)

Utilizator Ion.AAlexandru Ion Ion.A Data 12 decembrie 2022 17:05:51
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 100000;
vector <int> g[NMAX + 1];
bool viz[NMAX + 1];
int cnt = 0;

void dfs(int x)
{
    viz[x] = true;
    ///out << "nodul " << x << " poate merge in ";
    for (int y: g[x])
    {
        if (!viz[y])
        {
            ///out << y;
            ///out << "\n ";
            viz[y] = true;
            cnt++;
            dfs(y);
        }
    }
    ///out << ";";
}

int main()
{
    int n, m;
    ///citire
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    ///dfs;
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs(i);
        }
    }
    ///afisare
    out << cnt;
    return 0;
}