Mai intai trebuie sa te autentifici.
Cod sursa(job #2205923)
| Utilizator | Data | 20 mai 2018 16:48:19 | |
|---|---|---|---|
| Problema | Parcurgere DFS - componente conexe | Scor | 15 |
| Compilator | cpp | Status | done |
| Runda | Arhiva educationala | Marime | 1.02 kb |
#include <fstream>
#include <stack>
#include <vector>
int main() {
std::ifstream in("dfs.in");
std::ofstream out("dfs.out");
int n, m;
in >> n >> m;
std::vector<std::vector<int>> graph;
std::vector<bool> visited;
graph.reserve(n);
visited.reserve(n);
for (int i = 0; i < n; i++) {
graph.push_back(std::vector<int>());
visited.push_back(false);
}
for (int i = 0; i < m; i++) {
int from, to;
in >> from >> to;
graph[from - 1].push_back(to);
}
int numComponents = 0;
for (int i = 1; i <= n; i++) {
if (!visited[i - 1]) {
numComponents++;
std::stack<int> s;
s.push(i);
while (!s.empty()) {
int u = s.top();
bool hasAnyNeighbors = false;
for (int v : graph[u - 1]) {
if (!visited[v - 1]) {
visited[v - 1] = true;
s.push(v);
hasAnyNeighbors = true;
break;
}
}
if (!hasAnyNeighbors) s.pop();
}
}
}
out << numComponents;
return 0;
}
