Cod sursa(job #3294496)

Utilizator silviamariaBerescu Silvia-Maria silviamaria Data 24 aprilie 2025 16:46:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

class Task {
public:
    void solve() {
        read_input();
        print_output(count_components());
    }

private:
    static constexpr int NMAX = 100000;
    int n, m;
    vector<int> adj[NMAX + 1];  // lista de adiacenta
    vector<bool> visited;

    void read_input() {
        ifstream fin("dfs.in");
        fin >> n >> m;
        visited.resize(n + 1, false);
        
        for (int i = 0; i < m; i++) {
            int x, y;
            fin >> x >> y;
            adj[x].push_back(y); 
            adj[y].push_back(x); 
        }
        fin.close();
    }

    void dfs(int node) {
        visited[node] = true;
        for (int neighbor : adj[node]) {
            if (!visited[neighbor]) {
                dfs(neighbor);
            }
        }
    }

    int count_components() {
        int components = 0; // numar de componente conexe
        for (int i = 1; i <= n; ++i) {
            if (!visited[i]) {
                dfs(i);  // dfs pe nod nevizitat
                components++;  // pentru fiecare DFS, incrementam numarul de componente
            }
        }
        return components;
    }

    void print_output(int components) {
        ofstream fout("dfs.out");
        fout << components << "\n";
        fout.close();
    }
};

int main() {
    Task task;
    task.solve();
    return 0;
}