Nu aveti permisiuni pentru a descarca fisierul grader_test36.ok
Cod sursa(job #3318417)
| Utilizator | Data | 28 octombrie 2025 12:31:00 | |
|---|---|---|---|
| Problema | Parcurgere DFS - componente conexe | Scor | 100 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 1.19 kb |
#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;
}
