-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1066.cpp
102 lines (91 loc) · 2.01 KB
/
1066.cpp
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
//
// 1066.cpp
// 算法
//
// Created by 王怡凡 on 2017/4/1.
// Copyright © 2017年 王怡凡. All rights reserved.
//
#include<cstdio>
#include<algorithm>
using namespace std;
struct node {
int v,height;
node *lchild, *rchild;
}*root;
node* newNode(int v) {
node* Node = new node;
Node->v = v;
Node->height = 1;
Node->lchild = NULL;
Node->rchild = NULL;
return Node;
}
int getHeight(node *root) {
if(root==NULL) {
return 0;
} else {
return root->height;
}
}
void updateHeight(node* root) {
root->height = max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
void L(node* &root) {
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void R(node* &root) {
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
int getBalanceFactor(node* root) {
return getHeight(root->lchild)-getHeight(root->rchild);
}
void insert(node* &root, int v) {
if(root==NULL) {
root = newNode(v);
return;
}
if(v<root->v) {
insert(root->lchild,v);
updateHeight(root);
if(getBalanceFactor(root)==2) {
if(getBalanceFactor(root->lchild)==1) {
R(root);
} else if(getBalanceFactor(root->lchild)==-1) {
L(root->lchild);
R(root);
}
}
} else {
insert(root->rchild,v);
updateHeight(root);
if(getBalanceFactor(root)==-2) {
if(getBalanceFactor(root->rchild)==-1) {
L(root);
} else if(getBalanceFactor(root->rchild)==1) {
R(root->rchild);
L(root);
}
}
}
}
int main() {
int n,v;
scanf("%d",&n);
int i;
for(i=0;i<n;i++) {
scanf("%d",&v);
insert(root,v);
}
printf("%d\n",root->v);
return 0;
}