Cod sursa(job #3350288)

Utilizator petre_antonioPetre Antonio Bogdan petre_antonio Data 6 aprilie 2026 22:28:17
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
using namespace std;

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

int n, m, viz[100005], cnt;

struct nod
{
    int x;
    nod *a;
};
typedef nod* pNod;

pNod v[100005];

void add(pNod &dest, int val)
{
    pNod p = new nod;
    p->x = val;
    p->a = dest;
    dest = p;
}

void citire()
{
    int x, y;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y;
        add(v[x], y);
        add(v[y], x); // graf neorientat
    }
}

void DFS(int nod)
{
    viz[nod] = 1;
    for(pNod p = v[nod]; p != NULL; p = p->a)
        if(!viz[p->x])
            DFS(p->x);
}

int main()
{
    citire();
    for(int i = 1; i <= n; i++)
        if(!viz[i])
        {
            cnt++;
            DFS(i);
        }
    g << cnt;
    return 0;
}