Cod sursa(job #2954858)

Utilizator alexandrubilaBila Alexandru-Mihai alexandrubila Data 15 decembrie 2022 17:39:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
using namespace std;
const int NMAX = 100001;

struct nod
{
    int x;
    nod *next;
};

nod *L[NMAX]; ///L[i] = lista vecinilor nodului i;
int N, M, nrCC;
bool viz[NMAX];

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

void add_nod(int x, int y) ///la lista vecinilor lui x se adauga y
{
    nod *p = new nod;
    p -> x = y;
    p -> next = L[x];
    L[x] = p;
}

void citire()
{
    int x, y;
    f >> N >> M;
    for(int i = 1 ; i <= M ; i++)
    {
        f >> x >> y;
        add_nod(x, y); //se adauga y la lista vecinilor lui x
        add_nod(y, x);
    }
}

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

void comp_conexe()
{
    nrCC = 0;
    for(int i = 1 ; i <= N; i++)
        if(viz[i] == 0)
        {
            nrCC++;
            DFS(i);
        }
}


int main()
{
    citire();
    comp_conexe();
    g << nrCC;
    f.close();
    g.close();
    return 0;
}