Cod sursa(job #2666026)

Utilizator andreizZenoveiov Andrei andreiz Data 31 octombrie 2020 18:06:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 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;
    p->leg = vf;
    vf = p;
}

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

int main()
{
int x, y, i;
f >> n >> m;
for(i = 1; i <= m; ++i)
    {
    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;
}