Cod sursa(job #3228825)

Utilizator bogdan_croitoru17Croitoru Constantin Bogdan bogdan_croitoru17 Data 11 mai 2024 16:15:13
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
using namespace std;

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

private:
    static constexpr int NMAX = 100005;
    int n, m;
    vector<int> adj[NMAX];

    void read_input() {
        ifstream fin("dfs.in");
        fin >> n >> m;
        for (int i = 0, x, y; i < m; i++) {
            fin >> x >> y;
            adj[x].push_back(y);
            adj[y].push_back(x); // For undirected graph, add both directions
        }
        fin.close();
    }

    void dfs(int node, vector<bool> &visited) {
        visited[node] = true;
        for (auto neighbor : adj[node]) {
            if (!visited[neighbor])
                dfs(neighbor, visited);
        }
    }

    int get_result() {
        int nr = 0;
        vector<bool> visited(n + 1, false);
        for (int i = 1; i <= n; i++) {
            if (!visited[i]) {
                dfs(i, visited);
                nr++;
            }
        }
        return nr;
    }

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

int main() {
    auto* task = new (nothrow) Task();
    if (!task) {
        cerr << "new failed: WTF are you doing? Throw your PC!\n";
        return -1;
    }
    task->solve();
    delete task;
    return 0;
}