题解
2023-07-06 13:54:03
发布于:上海
104阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> v[105];
int f[110], vis[110];
void bfs(int st) {
queue<int> q;
q.push(st);
vis[st] = 1;
while (!q.empty()) {
int cp = q.front();
q.pop();
for (int i = 0; i < v[cp].size(); i++) {
int np = v[cp][i];
if (!vis[np]) {
vis[np] = 1;
q.push(np);
f[np] = cp;
}
}
}
}
int main() {
cin >> n ;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
bfs(1);
for (int i = 2; i <= n; i++)
cout << f[i] << " ";
return 0;
}
这里空空如也
有帮助,赞一个