Cod sursa(job #2837082)

Utilizator Stefan_GhinescuGhinescu Stefan-George Stefan_Ghinescu Data 21 ianuarie 2022 18:20:09
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>
#include <vector>

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

const int NMAX = 100000;

std::vector <int>G[NMAX + 5];
int viz[NMAX + 5];

void dfs(int x, int cc)
{
    viz[x] = cc;
    std::vector <int>::iterator it, b = G[x].begin(), e = G[x].end();
    for (it = b; it != e; ++it)
    {
        if (viz[*it] != cc)
        {
            dfs(*it, cc);
        }
    }
}

int main()
{
    int n, m, x, y, cc = 0;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i)
    {
        if (!viz[i])
        {
            dfs(i, ++cc);
        }
    }
    fout << cc;
    return 0;
}