Cod sursa(job #2640848)

Utilizator HermioneMatei Hermina-Maria Hermione Data 8 august 2020 16:48:46
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.64 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<vector<int>> G;
vector<bool> viz;
int n;

void read()
{
    int x, y;
    f>>n>>x;
    G.resize(n+1);
    viz.resize(n+1);
    while(f>>x>>y)
    {
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

void dfs(int x)
{
    viz[x]=1;
    for(auto a:G[x])
        if(!viz[a])
            dfs(a);
}

int main()
{
    read();
    int nr=0;
    for(int i=1; i<=n; i++)
        if(!viz[i])
        {
            nr++;
            dfs(i);
        }
    g<<nr;
    f.close();
    g.close();
    return 0;
}