Pagini recente » Cod sursa (job #2273525) | Cod sursa (job #2214719) | Profil BlackNesta | Cod sursa (job #960488) | Cod sursa (job #2531579)
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
const int NMAX = 100505;
vector<int> graph[NMAX];
int N, M;
bool visited[NMAX];
void read() {
cin >> N >> M;
int x, y;
for (int edgeIdx = 0; edgeIdx < M; edgeIdx++) {
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
}
void dfs(int node) {
visited[node] = true;
for (auto x : graph[node]) {
if (!visited[x]) {
dfs(x);
}
}
}
void solve() {
int countComponents = 0;
for (int node = 1; node <= N; node++) {
if (!visited[node]) {
countComponents++;
dfs(node);
}
}
cout << countComponents << "\n";
}
int main() {
freopen("dfs.in", "r", stdin);
freopen("dfs.out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
read();
solve();
return 0;
}