Cod sursa(job #2683061)

Utilizator mihai002016Zaharia Teodor Mihai mihai002016 Data 10 decembrie 2020 12:52:06
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <iostream>

using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int N, M,x,y,ok,conex=1,c[100100], n;
bool viz[100100];
struct nod {
    nod* urm;
    int val;
};
void DFS(nod**l,int sf)
{
    nod* x;
    x = l[c[--sf]];
        while (x != nullptr) {
            if (viz[x->val] == 0)
            {
                c[++sf] = x->val;
                viz[x->val] = 1;
                DFS(l, sf+1);
                x = x->urm;
            }
            else
                x = x->urm;
        }
}
int main()
{
    nod** l;
    fin >> N>>M;
    l = new nod*[N];
    for (int i = 1; i <= N; i++)
        l[i] = nullptr;
    while (M)
    {
        ok = 0;
        nod* model;
        fin >> x >> y;
        model = new nod;
        model->urm = l[x];
        l[x] = model;
        l[x]->val = y;
        nod* model1;
        model1 = new nod;
        model1->urm = l[y];
        l[y] = model1;
        l[y]->val =x;
        M--;
    }
    for (int i = 1; i <= N; i++) 
    if(viz[i]==0){
        c[1]= i;
        viz[i] = 1;
        DFS(l, 2);
        conex++;
    }
    fout << conex-1;
    return 0;
}