-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRooted_Tree.cpp
More file actions
101 lines (90 loc) · 2.28 KB
/
Rooted_Tree.cpp
File metadata and controls
101 lines (90 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <bits/stdc++.h>
using namespace std;
typedef long long llong;
#define MAX 200000
#define NIL -1
struct Node {int parent, left, right;};
Node T[MAX];
int n, Depth[MAX];
// 再帰的に深さを求める
void rec(int node,int parent){
Depth[node] = parent;
if(T[node].right != NIL){
// 右の兄弟に同じ深さを設定
rec(T[node].right,parent);
}
if(T[node].left != NIL){
// 最も左の子に自分の深さ+1を設定
rec(T[node].left,parent + 1);
}
}
void Print(int node){
cout << "node " << node << ": ";
cout << "parent = " << T[node].parent << ", ";
cout << "depth = " << Depth[node] << ", ";
if(T[node].parent == NIL) cout << "root, ";
else if(T[node].left == NIL)cout << "leaf, ";
else cout << "internal node, ";
cout << "[";
for(int i = 0,left = T[node].left;left != NIL;++i,left = T[left].right){
if(i) cout << ", ";
cout << left;
}
cout << "]" << endl;
}
int main() {
// 節点の個数
int n = 0;
// 次数
int iDeg = 0;
int iNodeIdx = 0;
int left, node, root;
cin >> n;
// 初期化
for (int i = 0; i < n; ++i)
{
T[i].parent = T[i].left = T[i].right = NIL;
}
// 各ノードに対して、
// その節点番号、子の情報を、
// 記憶していく
for (int i = 0; i < n; i++)
{
// 節点番号、次数(子の数)を取得
cin >> iNodeIdx >> iDeg;
// 全ての子の情報を記憶する
for (int k = 0; k < iDeg; k++)
{
cin >> node;
if (k == 0)
{
// 一番左の子を取得
T[iNodeIdx].left = node;
}
else
{
// 子の兄弟を記憶していく
T[left].right = node;
}
left = node;
// 子の親を記憶する
T[node].parent = iNodeIdx;
}
}
// rootを探す
for (int i = 0; i < n; ++i)
{
if (T[i].parent == NIL)
{
root = i;
}
}
// 根からはじめて深さを代入する
rec(root, 0);
// Nodeのindexごとに出力する
for (int i = 0; i < n; ++i)
{
Print(i);
}
return 0;
}