Cod sursa(job #2640847)

Utilizator PushkinPetolea Cosmin Pushkin Data 8 august 2020 16:48:00
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.63 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, 0);
    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 res=0;
    for(int x=1;x<=n;x++)
        if(!viz[x])
    {
        DFS(x);
        res++;
    }
    g<<res;

    f.close();
    g.close();
    return 0;
}