无根树转有根树

 1 #include <bits/stdc++.h>
 2 #include <iostream>
 3 #include <queue>
 4 #include <stdio.h>
 5 #include <string.h>
 6 #include <algorithm>
 7 #include <string>
 8 #include <math.h>
 9 #include <set>
10 #include <map>
11 #define MAXN 1000000+10
12 #define INF 1000000000
13 #define eps 10e-6
14 #define ll long long
15 using namespace std;
16 
17 bool cmp(int a, int b)
18 {
19     return a > b;
20 }
21 
22 //*******无根树转为指定节点为根的有根树并输出每个节点的父亲节点***************************
23 
24 vector<int> mp[MAXN];         //*****邻接表存储图
25 int pre[MAXN];               //*****存储每个节点的父亲节点
26 
27 void dfs(int u, int fa)  //***形参分别表示当前节点和其父亲节点
28 {
29     int len=mp[u].size();  //*****当前节点的儿子节点的个数
30     for(int i=0; i<len; i++)
31     {
32         int v=mp[u][i];   //****选中当前节点的一个儿子节点作为下一个节点
33         if(v!=fa)            //****如果父亲节点的儿子不是是自己,则其不为叶子节点,继续搜索
34         {
35             dfs(v, pre[v]=u);
36         }
37     }
38 }
39 
40 int main(void)
41 {
42     std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
43     int n;
44     cin >> n;
45     for(int i=0; i<n-1; i++)
46     {
47         int x, y;
48         cin >> x >> y;
49         mp[x].push_back(y);
50         mp[y].push_back(x);
51     }
52     int root;
53     cin >> root;    //****输入目标根节点
54     pre[root]=-1;   //****根节点没有父亲节点
55     dfs(root, -1);
56     for(int i=0; i<n; i++)
57     {
58         if(pre[i]!=-1)
59         {
60             cout << pre[i] << " ";
61         }
62     }
63     cout << endl;
64     return 0;
65 }
66 
67 /***************************
68 输入样例:
69 8
70 0 1
71 0 2
72 0 3
73 1 4
74 1 5
75 5 6
76 5 7
77 1
78 //*****************
79 输出样例:
80 1 0 0 1 1 5 5
81 //*****************
82 即0节点的父亲节点为1;
83 2,3节点的父亲节点为0;
84 4,5节点的父亲节点为1;
85 7,8节点的父亲节点为5;
86 *******************************/
//******刘汝佳算法竞赛入门经典p197**
原文地址:https://www.cnblogs.com/geloutingyu/p/5913338.html