Cod sursa(job #2338224)

Utilizator TaveehOctavian Custura Taveeh Data 7 februarie 2019 10:47:47
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
#include <iostream>
#define Jesus 100005

std::ifstream fin ("dfs.in");
std::ofstream fout("dfs.out");

int n, m, viz[Jesus], nr;

typedef struct nod
{
    int x;
    nod *a;
} *pNod;
pNod v[100005];

void add(pNod &dest, int val)
{
    pNod p;
    p = new nod;
    p -> x = val;
    p -> a = dest;
    dest = p;
}
void dfs(int k) {
    pNod p;
    viz[k] = 1;
    for (p = v[k]; p != NULL; p = p -> a) {
        if (!viz[p ->x]) {
            dfs(p->x);
        }
    }
}

int main(int argc, const char * argv[]) {
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        add(v[x], y);
        add(v[y], x);
    }
    for (int i = 1; i <=n; ++i) {
        if (!viz[i]) {
            dfs(i);
            nr++;
        }
    }
    fout << nr;
    return 0;
}