Pagini recente » Cod sursa (job #172703) | Cod sursa (job #2385159) | Cod sursa (job #763382) | Cod sursa (job #719228) | Cod sursa (job #2954377)
#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;
}