Cod sursa(job #3338703)

Utilizator mihaela20Tanasescu Mihaela mihaela20 Data 4 februarie 2026 16:10:50
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
using namespace std;

struct nod
{
    int vec;
    nod *urm;
};

nod *L[100001];
int viz[100001];
int n, m;

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

void add(int x, int y)
{
    nod *p = new nod;
    p->vec = y;
    p->urm = L[x];
    L[x] = p;
}

void citire()
{
    int x, y;
    f >> n >> m;
    while(m--)
    {
        f >> x >> y;
        add(x, y);
        add(y, x);
    }
}

void DFS(int x)
{
    viz[x] = 1;
    for(nod *p = L[x]; p != NULL; p = p->urm)
        if(viz[p->vec] == 0)
            DFS(p->vec);
}

int main()
{
    citire();
    int nr = 0;

    for(int i = 1; i <= n; i++)
        if(viz[i] == 0)
        {
            nr++;
            DFS(i);
        }

    g << nr;
    return 0;
}