-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCartesian Tree.cpp
More file actions
84 lines (70 loc) · 1.42 KB
/
Copy pathCartesian Tree.cpp
File metadata and controls
84 lines (70 loc) · 1.42 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
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1000;
typedef struct node{
int id;
int key, val;
int f, l, r;
bool operator < (node t) const
{
return key < t.key;
}
} node;
node T[MAXN];
int stack[MAXN], top;
int create(int n)
{
top = 1;
stack[top] = 1;
for(int i = 2; i <= n; i++)
{
while(top > 0 && T[i].val > T[stack[top]].val)
top --;
if(top > 0) // 右链中的节点
{
T[i].f = stack[top];
T[i].l = T[stack[top]].r;
T[T[stack[top]].r].f = i;
T[stack[top]].r = i;
stack[++top] = i;
}
else // 根节点
{
T[stack[1]].f = i;
T[i].l = stack[1];
stack[++top] = i;
}
}
return stack[1];
}
void show(int i)
{
cout << "id: " << T[i].id << " key: " << T[i].key
<< " val: " << T[i].val << " fa: " << T[T[i].f].key
<< " l: " << T[T[i].l].key << " r: " << T[T[i].r].key << endl;
if(T[i].l)
{
show(T[i].l);
}
if(T[i].r)
{
show(T[i].r);
}
}
int main()
{
int n;
scanf("%d", &n);
memset(T, 0, sizeof(T));
for(int i = 1; i <= n; i++)
{
scanf("%d %d", &T[i].key, &T[i].val);
T[i].id = i;
}
sort(T + 1, T + n + 1);
int root = create(n);
show(root);
return 0;
}