Cod sursa(job #3227936)

Utilizator matei.buzdeaBuzdea Matei matei.buzdea Data 3 mai 2024 22:29:40
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

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

private:
    static const int NMAX = (int)1e5 + 5;

    int n, m, source;
    vector<int> adj[NMAX];

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

    int conex_components() {
        int nr = 0;
        vector<int> visited(n + 1, 0);

        for (int i = 1; i <= n; i++) {
            if (!visited[i]) {
                dfs(i, visited);
                nr++;
            }
        }

        return nr;
    }

    void dfs(int node, vector<int> &visited) {
        visited[node] = 1;

        for (auto &neighbor : adj[node]) {
            if (!visited[neighbor]) {
                dfs(neighbor, visited);
            }
        }
    }

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

int main() {
    auto* task = new (nothrow) Task();
    if (!task) {
        cerr << "Error\n";
        return -1;
    }
    task->solve();
    delete task;
    return 0;
}