ac助手直接吐了个完整代码给我...
2024-09-21 22:41:38
发布于:上海
11阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 105;
vector<int> adj[MAXN]; // 邻接表表示树
int parent[MAXN]; // 存储每个节点的父节点
// 广度优先搜索找到所有节点的父节点
void bfs(int root) {
queue<int> q;
q.push(root);
parent[root] = -1; // 根节点没有父节点
while (!q.empty()) {
int current = q.front();
q.pop();
for (int neighbor : adj[current]) {
if (parent[neighbor] == -1) { // 确保邻居节点尚未被访问
parent[neighbor] = current;
q.push(neighbor);
}
}
}
}
int main() {
int n;
cin >> n;
// 构建邻接表
for (int i = 0; i < n - 1; ++i) {
int x, y;
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
// 初始化所有节点的父节点为-1
fill_n(parent, n + 1, -1);
bfs(1); // 从根节点开始进行BFS
// 输出结果
for (int i = 2; i <= n; ++i) {
cout << parent[i] << (i == n ? '\n' : ' ');
}
return 0;
}
这里空空如也
有帮助,赞一个