Pagini recente » Cod sursa (job #3309311) | Cod sursa (job #3357823) | Cod sursa (job #3316861) | Cod sursa (job #3232781) | Cod sursa (job #3318417)
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
// Deschidere fișiere conform cerinței
ifstream fin("dfs.in");
ofstream fout("dfs.out");
if (!fin) return 0; // fallback simplu
int N, M;
fin >> N >> M;
vector<vector<int>> g(N + 1);
g.reserve(N + 1);
for (int i = 0; i < M; ++i) {
int x, y;
fin >> x >> y;
if (x >= 1 && x <= N && y >= 1 && y <= N) {
g[x].push_back(y);
g[y].push_back(x); // neorientat
}
}
vector<char> vis(N + 1, 0);
int comp = 0;
// DFS iterativ cu stivă
for (int start = 1; start <= N; ++start) {
if (vis[start]) continue;
++comp;
stack<int> st;
st.push(start);
vis[start] = 1;
while (!st.empty()) {
int u = st.top(); st.pop();
for (int v : g[u]) {
if (!vis[v]) {
vis[v] = 1;
st.push(v);
}
}
}
}
fout << comp << "\n";
return 0;
}