Cod sursa(job #2205487)

Utilizator brainwashed20Alexandru Gherghe brainwashed20 Data 19 mai 2018 12:16:50
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#define Nmax 100001

std::vector<int> G[Nmax];
std::vector<bool> viz;
int N, M, sol;

void DFS(int node)
{
    viz[node] = 1;
    for (auto it = G[node].begin(); it != G[node].end(); ++it)
    {
        if (!viz[*it])
        {
            DFS(*it);
        }
    }
}

int main()
{
    std::ifstream f("dfs.in");

    int x, y;

    f >> N >> M;
    while (M--)
    {
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    f.close();

    viz.resize(N + 1);
    std::fill(viz.begin(), viz.end(), false);
    sol = 0;

    for (int i = 1; i <= N; ++i)
    {
        if (!viz[i])
        {
            DFS(i);
            sol++;
        }
    }

    std::ofstream g("dfs.out");
    g << sol << "\n";
    g.close();

    return 0;
}