我正在尝试实施竞争性编程1书中描述的以下DFS代码:
#include <cstdio>
#include <vector>
using namespace std;
#define MAX 10
#define DFS_BLACK 1
#define DFS_WHITE -1
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
vi dfs_num;
vector<vii> adj(MAX);
void dfs(int u) {
dfs_num[u] = DFS_BLACK;
for (int i = 0; i < (int)adj[i].size(); i++) {
ii v = adj[u][i];
if (dfs_num[v.first] == DFS_WHITE)
dfs(v.first);
}
printf(" %d", u);
}
int main() {
int v, e, x, y;
scanf("%d %d", &v, &e);
for (int i = 0; i < e; i++) {
scanf("%d %d", &x, &y);
adj[x].push_back(ii(y, 1));
adj[y].push_back(ii(x, 1));
}
int numCC = 0;
dfs_num.assign(v, DFS_WHITE);
for (int i = 0; i < v; i++)
if (dfs_num[i] == DFS_WHITE)
printf("Component %d:", ++numCC), dfs(i), printf("\n");
printf("There are %d connected components\n", numCC);
}
我想要的是:
Input: Output:
9 7 Component 1: 0 1 2 3 4
0 1 Component 2: 5
1 2 Component 3: 6 7 8
1 3 There are 3 connected components
2 3
3 4
6 7
6 8
如下图:
但是我得到“组件1:3 2 1”然后它崩溃了。我做错了什么?
感谢任何帮助。
答案 0 :(得分:2)
for (int i = 0; i < (int)adj[i].size(); i++) {
成:
for (int i = 0; i < (int)adj[u].size(); i++) {
// ^ u, not i
答案 1 :(得分:1)
整体逻辑似乎没问题,但我在细节中看到了一些奇怪的东西:
我注意到的其他事情: