Cod sursa(job #1826541)

Utilizator doroftei1999Doroftei Andrei doroftei1999 Data 10 decembrie 2016 16:20:15
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>

using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");
int n, m, cnt;
bool viz[100005];
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 citire() {
    in >> n >> m;
    int i, x, y;
    for (i = 1; i <= m; i++) {
        in >> x >> y;
        add(v[x], y);
        add(v[y], x);
    }
}
 
void DFS(int nod) {
    pNod p;
    viz[nod] = true;
    for (p = v[nod]; p != NULL; p = p -> a) 
        if (!viz[p -> x]) 
            DFS(p -> x);
}   
 
int main() {
    citire();
    int i;
    for (i = 1; i <= n; i++) 
    if (!viz[i]) { 
        cnt++; 
        DFS(i);
    }
    out << cnt;
    return 0;
}