Cod sursa(job #3233808)

Utilizator MariuselMarius-Ionut Buzoi Mariusel Data 4 iunie 2024 23:39:03
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <vector>

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

void write_output(int result) {
    std::ofstream fout;
    fout.open("dfs.out");
    fout << result;
    fout.close();
}

void dfs_rec(int node, int n, std::vector<std::vector<int>> adj, std::vector<int> &parents) {
    for (int neigh : adj[node]) {
        if (parents[neigh] == -1) {
            parents[neigh] = node;
            dfs_rec(neigh, n, adj, parents);
        }
    }
}

void dfs(int n, std::vector<std::vector<int>> adj) {
    std::vector<int> parents(n + 1, -1);
    int conex_components = 0;
    for (int i = 1; i <= n; i++) {
        if (parents[i] == -1) {
            conex_components++;
            dfs_rec(i, n, adj, parents);
        }
    }
    write_output(conex_components);
}


int main() {
    int n, m;
    std::vector<std::vector<int>> adj;
    read_input(n, m, adj);
    dfs(n, adj);
    return 0;
}