Cod sursa(job #3248603)

Utilizator ioanabaduIoana Badu ioanabadu Data 12 octombrie 2024 11:05:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

int nodes, edges;
vector <int> graph[100005];
bool viz[100005];

void dfs(int x){
    if (viz[x])
        return;
    viz[x] = true;

    for (auto idx:graph[x])
        dfs(idx);
}

int main (){
    int x, y;
    in >> nodes >> edges;

    for (int i=1; i<=edges; ++i){
        in >> x >> y;

        graph[x].push_back(y);
        graph[y].push_back(x);
    }

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

    out << ans;

    return 0;
}