Cod sursa(job #3152342)

Utilizator AlbertPavPavalache Albert AlbertPav Data 24 septembrie 2023 17:21:31
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <fstream>
using namespace std;
const int NMAX = 100001;

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

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

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

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

void citire()
{
    int x, y, m;
    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;
    return 0;
}