AVL树模板
今天刷PAT甲级的时候遇到了AVL的模板题,之前一直都不会,然后看到别人的博客,终于看懂了.
2021.3.9更:
老的那个太丑了,自己写了个简短好看的
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888
博客链接:https://www.cnblogs.com/chenxiwenruo/p/6806292.html
看懂之后自己修改成了自己熟悉的数据存储方法(数组)实现了一下,
代码:
#include<iostream> #include<string.h> #include<cmath> #include<set> #include<map> #include<string> #include<queue> #include<stack> #include<vector> #include<bitset> #include<algorithm> #include<climits> using namespace std; typedef long long ll; inline int read() { int sum = 0, f = 1; char p = getchar(); for (; !isdigit(p); p = getchar()) if (p == '-')f = -1; for (; isdigit(p); p = getchar()) sum = sum * 10 + p - 48; return sum * f; } const int maxn = 10001; #define ls(x) tree[x][0] #define rs(x) tree[x][1] int n; int tree[maxn][2], tot,val[maxn],hight[maxn]; void push_up(int root) { hight[root] = max(hight[ls(root)], hight[rs(root)]) + 1; } void newnode(int& x,int w) { x = ++tot; hight[x] = 1; val[x] = w; } void LL(int &root) { int x = root, y = ls(x); ls(x) = rs(y); rs(y) = x; push_up(x); push_up(y); root = y; } void RR(int& root) { int x = root, y = rs(x); rs(x) = ls(y); ls(y) = x; push_up(x); push_up(y); root = y; } void LR(int&root) { RR(ls(root)); LL(root); } void RL(int& root) { LL(rs(root)); RR(root); } void insert(int &root,int w){ if (root == 0) { newnode(root, w); return; } if (val[root] <= w) { insert(rs(root), w); if (hight[rs(root)] - hight[ls(root)] > 1) { if (val[rs(root)] > w) RL(root); else RR(root); } } else { insert(ls(root), w); if (hight[ls(root)] - hight[rs(root)] > 1) { if (val[ls(root)] < w)LR(root); else LL(root); } } push_up(root); } int main() { n = read(); int root = 0,t; for (int i = 1; i <= n; i++) { t = read(); insert(root, t); } cout << val[root] << endl; return 0; }

浙公网安备 33010602011771号