Pagini recente » Cod sursa (job #2177791) | Cod sursa (job #1934095) | Cod sursa (job #2262647) | Cod sursa (job #373091) | Cod sursa (job #3124843)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int main() {
int n, m, x, y;
fin >> n >> m;
vector<int> adj[n + 1];
vector<int> visited(n + 1, 0);
for (int i = 1; i <= m; i++) {
fin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
int nr_of_components = 0;
stack<int> s;
for (int i = 1; i <= n; i++) {
if (visited[i]) continue;
s.push(i);
nr_of_components++;
while (!s.empty()) {
int node = s.top();
s.pop();
visited[node] = 1;
for (int neigh: adj[node]) {
if (visited[neigh]) continue;
s.push(neigh);
}
}
}
fout << nr_of_components;
return 0;
}