Pagini recente » Cod sursa (job #987845) | Cod sursa (job #876515) | Cod sursa (job #1653309) | Cod sursa (job #3318237) | Cod sursa (job #3307571)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
// Space complexity: O(m) + O(n) + O(n) = O(m + n),
// given by the adjacency lists, the visited vector
// and the recursion stack - at most n stack frames
// at a time, where n = the number of nodes of the graph.
// Time complexity: O(n + m), given by the DFS calls and by reading
// the input.
vector<vector<int>> adj;
vector<bool> visited;
void dfs(int u) {
visited[u] = true;
for (int v : adj[u])
if (!visited[v]) dfs(v);
}
int main() {
int n, m, x, y;
fin >> n >> m;
adj.resize(n + 1);
visited.assign(n + 1, false);
for (int i = 1; i <= m; i++) {
fin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
int count = 0;
for (int v = 1; v <= n; v++)
if (!visited[v]) {
dfs(v);
count++;
}
fout << count;
return 0;
}