Cod sursa(job #2690480)

Utilizator NeoxDragos Stefan Neox Data 24 decembrie 2020 09:31:55
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");
int n, m, x, y, conex;
vector<vector<int>> vertex;
vector<bool> vis;
void dfs(int node) {
    vis[node] = 1;
    for(unsigned int i = 0; i < vertex[node].size(); i++) {
        if(!vis[vertex[node][i]]) {
            dfs(vertex[node][i]);
        }
    }
}
int main() {
    fin >> n >> m;
    vertex.reserve(n+1);
    vis.reserve(n+1);
    for(int i = 0; i < m; i++) {
        fin >> x >> y;
        vertex[x].push_back(y);
        vertex[y].push_back(x);
    }
    for(int i = 1; i <= n; i++) {
        if(!vis[i]) {
            conex++;
            dfs(i);
        }
    }
    fout << conex;
    fin.close();
    fout.close();
    return 0;
}