-
Notifications
You must be signed in to change notification settings - Fork 0
/
OJ4.cc
129 lines (117 loc) · 2.42 KB
/
OJ4.cc
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <cstdio>
using namespace std;
int N;
int newData;
int nodeNum = 0;
struct node
{
int data1 = -1;
int data2 = -1;
int left = -1;
int right = -1;
};
node NodeList[100010];
int lastIndex = -1;
void InsertNode(int index)
{
if (NodeList[index].data1 == -1)
NodeList[nodeNum].data1 = newData;
else
{
if (newData < NodeList[index].data1)
{
if (NodeList[index].left == -1)
NodeList[index].left = ++nodeNum;
InsertNode(NodeList[index].left);
}
else
{
if (NodeList[index].right == -1)
NodeList[index].right = ++nodeNum;
InsertNode(NodeList[index].right);
}
}
}
void BuildTree()
{
scanf("%d", &newData);
NodeList[0].data1 = newData;
for (int i = 1; i < N; i++)
{
scanf("%d", &newData);
InsertNode(0);
}
}
unsigned GetLayer(int index, int res)
{
if (index == -1)
return 0;
if (res > NodeList[index].data1)
return GetLayer(NodeList[index].right, res) + 1;
else if (res < NodeList[index].data1)
return GetLayer(NodeList[index].left, res) + 1;
else
return 1;
}
void tryData(int index)
{
if (lastIndex == -1)
{
lastIndex = index;
return;
}
else
{
if (GetLayer(0, NodeList[lastIndex].data1) < GetLayer(0, NodeList[index].data1))
{
lastIndex = index;
return;
}
else
{
NodeList[index].data2 = NodeList[lastIndex].data1;
if (NodeList[lastIndex].left == -1 && NodeList[lastIndex].right == -1 && NodeList[lastIndex].data2 == -1)
{
NodeList[lastIndex].data1 = -2;
NodeList[lastIndex].data2 = -2;
}
lastIndex = index;
return;
}
}
}
void Zip(int index)
{
if (index != -1)
{
Zip(NodeList[index].left);
tryData(index);
Zip(NodeList[index].right);
}
}
void PrintData(int i)
{
if (i == -1)
printf("-");
else if (i == -2)
;
else
printf("%d ", i);
}
void Output(int index)
{
if (index != -1)
{
PrintData(NodeList[index].data1);
PrintData(NodeList[index].data2);
Output(NodeList[index].left);
Output(NodeList[index].right);
}
}
int main()
{
scanf("%d", &N);
BuildTree();
Zip(0);
Output(0);
}