Cod sursa(job #2665393)

Utilizator andreizZenoveiov Andrei andreiz Data 30 octombrie 2020 17:57:10
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include<bits/stdc++.h>

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

int n, m, nrConexe;
bool viz[100005];


struct nod{
    int inf;
    nod *leg;
};

typedef nod* pnod;
pnod v[100005];

void add(pnod &vf, int x)
{
    pnod p;
    p = new nod;
    p->inf = x;
    vf = p;
}

void dfs(int x)
{
    pnod p;
    viz[x] = true;
    for(p = v[x]; !p; p = p->leg)
        if(!viz[p->inf])
            dfs(p->inf);
}

int main()
{
f >> n >> m;
for(int i = 0; i < m; ++i)
    {
    int x, y;
    f >> x >> y;
    add(v[x],y);
    add(v[y],x);
    }

for(int i = 1; i < n; ++i)
    if(!viz[i])
    {
        nrConexe++;
        dfs(i);
    }
g << nrConexe;
return 0;
}