无根树转有根树
//输入节点数、目标树根、各边,输出各节点对应的父节点
//一 p353
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1000010;
vector <int> G[maxn];
int p[maxn], n;
void read_tree()
{
for (int i = 0; i < n - 1; i++)
{
int a, b;
scanf("%d %d", &a, &b);
G[a].push_back(b);
G[b].push_back(a); //无向图
}
}
void dfs(int u, int fa)
{
int d = G[u].size();
for (int i = 0; i < d; i++)
{
int v = G[u][i];
if (v != fa) dfs(v, p[v] = u); //判断
}
}
int main(void)
{
cin >> n; //节点数
int x;
cin >> x; //目标树根
p[x] = -1; //根节点的父节点初始化为-1
read_tree();
dfs(x, -1);
for (int i = 0; i < n; i++) //节点编号从0开始
printf("%d\n", p[i]);
return 0;
}