Cod sursa(job #2670542)

Utilizator As932Stanciu Andreea As932 Data 10 noiembrie 2020 09:55:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>

using namespace std;

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

const int nMax = 1e5 + 5;

int n, m, ans;
bool viz[nMax];

typedef struct nod
{
    int vf;
    nod *next;
} *pNod;
pNod v[nMax];

void add(pNod &dest, int vf1){
    pNod p;
    p = new nod;
    p -> vf = vf1;
    p -> next = dest;
    dest = p;
}

void read(){
    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        int x, y;

        fin >> x >> y;

        add(v[x], y);
        add(v[y], x);
    }
}

void dfs(int nod){
    pNod p;
    viz[nod] = 1;

    for(p = v[nod]; p != NULL; p = p ->next)
        if(!viz[p -> vf])
            dfs(p -> vf);
}

int main()
{
    read();


    for(int i = 1; i <= n; i++)
        if(!viz[i]){
            ans++;
            dfs(i);
        }

    fout << ans;

    return 0;
}