#include <iostream> #include <cstring> using namespace std; const int MAXN = 100000; int graph[MAXN][10]; bool visited[MAXN]; int dfs(int v, int max_id) { visited[v] = true; max_id = max(max_id, v); for (int i = 0; i < 10; i++) { int w = graph[v][i]; if (w == -1) break; if (!visited[w]) { max_id = max(max_id, dfs(w, max_id)); } } return max_id; } int main() { int n, m; cin >> n >> m; // 初始化邻接表 memset(graph, -1, sizeof(graph)); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; graph[u-1][i%10] = v-1; } // 对每个点进行DFS for (int i = 0; i < n; i++) { memset(visited, false, sizeof(visited)); int max_id = dfs(i, i); cout << max_id+1 << ' '; } return 0; }这个代码的输出答案全错误,为什么
时间: 2024-01-13 20:04:59 浏览: 84
使用include <iostream>时一定要加using namespace std
这段代码的问题在于,每次对一个节点进行DFS时,都会重置visited数组为false,这导致之前已经访问过的节点又被重新访问了,从而导致输出的结果不正确。应该在整个程序的开始就对visited数组进行初始化,而不是在每次DFS之前都进行初始化。修改方式如下:
```
int main() {
int n, m;
cin >> n >> m;
// 初始化邻接表
memset(graph, -1, sizeof(graph));
// 对每个节点进行遍历
memset(visited, false, sizeof(visited));
for (int i = 0; i < n; i++) {
int max_id = dfs(i, i);
cout << max_id+1 << ' ';
}
return 0;
}
```
阅读全文