11688 uva 二叉树的旋转+dp Rotate to root
来源:互联网 发布:青牛软件电话 编辑:程序博客网 时间:2024/06/09 19:30
把二叉树旋转先模拟几遍,要不然这个题。。。gg
模拟下叶子节点如何转为root
h:向下还能到达的深度
dep:所在的深度
lm:root到节点需要左移多少次
rm:root到节点需要右移多少次
这个方程还比较好理解,最后转为root的时候他的子树的lm,rm,一定是这样的距离
dp[root] = max(h[r[root]]+lm+1,h[l[root]]+rm+1);
关键是这部分:
lm++,dfs(l[root],max(last_max,h[r[root]]+lm+1));
lm--,rm++,dfs(r[root],max(last_max,h[l[root]]+rm+1));
rm--;
在这个节点作为root的时候比它大(之前父节点,父节点的父节点。。。。)
也会成为比它小的节点,这个就是这些节点用来更新此节点的,多模拟一下就会明白的
#include <algorithm>#include <cstdio>#include <iostream>#include <vector>#include <cstring>#include <cmath>#include <map>#include <queue>using namespace std;bool f[100005];//判断是否有父节点int l[100005],r[100005];int root;int h[100005];//向下还能到达的深度int dep[100005];//所在的深度int dp[100005];int rm,lm;int get_num(int root,int d){if(!root){dep[root] = dep[root] = 0;return 0;}dep[root] = d;h[root] = max(1+get_num(l[root],d+1),1+get_num(r[root],d+1));return h[root]; }void dfs(int root,int last_max){if(!root)return;if(!f[root]){dp[root] = 1+max(h[l[root]],h[r[root]]);}else{dp[root] = max(max(h[r[root]]+lm+1,h[l[root]]+rm+1),last_max);}lm++,dfs(l[root],max(last_max,h[r[root]]+lm+1));lm--,rm++,dfs(r[root],max(last_max,h[l[root]]+rm+1));rm--;}int main(void){//freopen("in.txt","r",stdin);int n,i;while(cin >> n && n){rm = lm = 0;for(i=0;i<=n;i++){f[i] = 0;dp[i] = 0;}for(i=1;i<=n;i++){int a,b;cin >> a >> b;//cout << a << b << endl;l[i] = a, r[i] = b;f[a] = f[b] = true;}for(i=1;i<=n;i++){if(!f[i]){root = i;break;}}get_num(root,1);dfs(root,0);for(int i=1;i<=n;i++){printf("%d\n",dp[i]);}}}
0 0
- 11688 uva 二叉树的旋转+dp Rotate to root
- uva - 11688 - Rotate to root
- UVa 11688 Rotate to root
- 以AVL树为例理解二叉树的旋转(Rotate)操作
- 以AVL树为例理解二叉树的旋转(Rotate)操作
- 图片的旋转rotate
- leetcode:Sum Root to Leaf Numbers (二叉树的DFS)
- Sum Root to Leaf Numbers 二叉树的path 和
- 5-6 Root of AVL Tree (25分) (二叉平衡树的旋转操作)
- Rotate Array 数组的旋转
- 平衡二叉树的旋转
- 平衡二叉树的旋转
- 平衡二叉树的旋转
- 5.4.7—二叉树的递归—Sum Root to Leaf Numbers
- 二叉树遍历129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers | 二叉树整数和
- (二叉树相关)LeetCode#129. Sum Root to Leaf Numbers
- LeetCode Rotate Image(矩阵的旋转)
- red hat 安装 mongodb
- addSubView会使内存计数+1
- JAVA程序员最常犯的10个错误
- Java去除掉HTML里面所有标签,
- UNIX编程——互斥锁和条件变量
- 11688 uva 二叉树的旋转+dp Rotate to root
- map解析的几种方式
- MQTT连接服务器发送和接收数据
- Oracle 统计信息(备份/导入)表分析-[注意要刷缓存]
- sturts调用支付宝接口。
- java.lang.noclassdeffounderror:com/mchange/v2/ser/Indirector
- Margin和Padding的注意事项 不定时增添
- Mysql避免全表扫描sql查询优化
- AppCan移动开发平台的新业态思维