Cod sursa(job #3215061)

Utilizator addanciuAdriana Danciu addanciu Data 14 martie 2024 17:42:26
Problema Parcurgere DFS - componente conexe Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.59 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax = 100000;

int n;
bool viz[nmax + 1];
vector<int>v[nmax + 1];

void dfs(int x){
    viz[x] = 1;
    for(auto y : v[x]){      
        if(!viz[y]){
            dfs(y);
        }
    }
}

int main(){
    int a, b, nrc = 0;
    in >> n;
    while(in >> a >> b){
        v[a].push_back(b);
        v[b].push_back(a);
    }
    for(int i = 1; i <= n; i++){
        if(!viz[i]){
            nrc++;
            dfs(i);
        }
    }
    out << nrc;
    return 0;
}