Mai intai trebuie sa te autentifici.
Cod sursa(job #2954377)
| Utilizator | Data | 14 decembrie 2022 08:47:33 | |
|---|---|---|---|
| Problema | Parcurgere DFS - componente conexe | Scor | 100 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 0.75 kb |
#include <iostream>
#include <fstream>
#include <vector>
std::vector<bool> visited;
std::vector<std::vector<int>> graph;
void dfs(int node) {
visited[node] = true;
for (const auto &x: graph[node]) {
if (!visited[x]) dfs(x);
}
}
int main() {
std::ifstream input("dfs.in");
std::ofstream output("dfs.out");
int n, m;
input >> n >> m;
graph.resize(n + 1);
for (int i = 0; i < m; ++i) {
int x, y;
input >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
visited.resize(n + 1, false);
int components = 0;
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
components++;
dfs(i);
}
}
output << components;
return 0;
}
