Cod sursa(job #2475780)

Utilizator tomitza.1604Sacuiu TomaAndrei tomitza.1604 Data 17 octombrie 2019 16:14:17
Problema Parcurgere DFS - componente conexe Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int VM = 100001;
int vf[VM], lst[VM], urm[VM], nr, ct;
bool viz[VM];

void adauga(int x, int y){
    vf[++nr] = y;
    urm[nr] = lst[x];
    lst[x] = nr;
}

void dfs(int x){
    viz[x] = true;
    int y;
    for( int p=lst[x]; p!=0; p=urm[p]){
        y = vf[p];
        if( !viz[y]){
            dfs(y);
        }
    }
}

int main()
{
    int n, m;
    in >> n;
    for(int i = 0; i < m; i++){
        int x, y;
        in >> x >> y;
        adauga(x, y);
        adauga(y, x);
    }
    for(int i = 1; i <= n; i++){
        if(!viz[i]){
            ct++;
            dfs(i);
        }
    }
    out << ct;
    return 0;
}