PAT 1066. Root of AVL Tree (25)
2015-09-01 16:07
190 查看
AVL树的练习
#include<cstdio> #include<iostream> #include<algorithm> #include<cmath> #include<set> #include<map> #include<string> #include<cstring> #include<stack> #include<queue> #include<vector> #include<cstdlib> //#define lson (rt<<1),L,M //#define rson (rt<<1|1),M+1,R #define M ((L+R)>>1) #define cl(a,b) memset(a,b,sizeof(a)); //#define LL long long #define P pair<int,int> #define X first #define Y second #define pb push_back #define fread(zcc) freopen(zcc,"r",stdin) #define fwrite(zcc) freopen(zcc,"w",stdout) using namespace std; const int maxn=100; const int inf=1<<28; struct node{ int data; int hight; node *lson,*rson; node(){lson=rson=NULL;hight=0;} }; int geth(node *root){ return root?root->hight:-1; } bool isbalanced(node *root){ return abs(geth(root->lson)-geth(root->rson))<2; } node* LL(node* root){ node *tmp=root->lson; root->lson=tmp->rson; tmp->rson=root; root->hight=max(geth(root->lson),geth(root->rson))+1; tmp->hight=max(geth(tmp->lson),geth(tmp->rson))+1; return tmp; } node *RR(node *root){ node *tmp=root->rson; root->rson=tmp->lson; tmp->lson=root; root->hight=max(geth(root->lson),geth(root->rson))+1; tmp->hight=max(geth(tmp->lson),geth(tmp->rson))+1; return tmp; } node *RL(node *root){ root->rson=LL(root->rson); return RR(root); } node *LR(node *root){ root->lson=RR(root->lson); return LL(root); } node *insert(node *root,int v){ if(root==NULL){ root=new node(); root->data=v; return root; } if(v>root->data){ root->rson=insert(root->rson,v); if(!isbalanced(root)){ if(v>root->rson->data){ root=RR(root); } else { root=RL(root); } } } else { root->lson=insert(root->lson,v); if(!isbalanced(root)){ if(v<root->lson->data){ root=LL(root); } else { root=LR(root); } } } root->hight=max(geth(root->lson),geth(root->rson))+1; return root; } int main(){ int n; scanf("%d",&n); node *root=NULL; for(int i=0;i<n;i++){ int v; scanf("%d",&v); root=insert(root,v); } printf("%d\n",root->data); return 0; }
相关文章推荐
- Laravel 爬过的坑
- struts之Action中获取request、response对象的方法
- react-native试玩(5)-小菊花控件
- Myeclipse10的优化设置
- 我自己的
- ListView绑定数据后界面显示一条数据原因
- *** Assertion failure in -[CompensaCommentView _dequeueReusableViewOfType:withIdentifier:],
- C++文件的读取到string以及string分割
- 如何通过Xcode将代码上传到git上。
- 利用navicat创建存储过程、触发器和使用游标的简单实例
- C++ stringstream的用法
- Google 2015 APAC Round A Problem C - Addition
- iOS中socket的使用
- 文件系统与磁盘格式
- 决策树模型组合之(在线)随机森林与GBDT
- TQ2440 学习笔记—— 10、嵌入式编程基础知识【arm-linux-ld 选项】
- 好像原来是判断如果是新增的则直接插入如果是修改的,把所有的都修改
- struts2使用action方式实现文件下载(支持中文文件名)
- android canvas 编辑bitmap画虚线
- The 10 Best Open Source Projects You Should Be Volunteering To Help With