Cod sursa(job #3338705)

Utilizator Luca_ManguciManguci Luca-George Luca_Manguci Data 4 februarie 2026 16:21:39
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>

using namespace std;

const int NMAX = 100001;

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

int n;
nod *L[NMAX];
bool viz[NMAX];

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

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

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

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

int main()
{
    int nrCC = 0;
    citire();
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0)
        {
            nrCC++;
            DFS(i);
        }
    g << nrCC;
    f.close();
    g.close();
    return 0;
}