Cod sursa(job #2373198)

Utilizator PaulTPaul Tirlisan PaulT Data 7 martie 2019 12:41:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;

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

int n, m, c;
VB v;
VVI G;

void Read();
void Dfs(int x);

int main()
{
    Read();
    for (int x = 1; x <= n; x++)
        if (!v[x])
        {
            c++;
            Dfs(x);
        }
    fout << c;

    fin.close();
    fout.close();
}

void Dfs(int x)
{
    v[x] = true;
    for (const int& y : G[x])
        if (!v[y])
            Dfs(y);
}

void Read()
{
    fin >> n >> m;
    G = VVI(n + 1);
    v = VB(n + 1);
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    fin.close();
}