Cod sursa(job #3270781)

Utilizator Alex_567Toma Alex Alex_567 Data 24 ianuarie 2025 13:56:36
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
#include <queue>
using namespace std;
const int NMAX = 100001;

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

int n;
nod *L[NMAX];
bool viz[NMAX];
queue <int> Q;
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;
}