首页 > 其他 > 详细

最近公共祖先(LCA树上倍增)

时间:2020-07-07 18:00:22      阅读:65      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

class TreeAncestor {
int[][] dp; //预处理数组 dp[i][j] 表示i的第2^j个祖先 // 倍增思想 public TreeAncestor(int n, int[] parent) { dp = new int[n][(int)(Math.log(n) / Math.log(2)) + 1]; for(int i = 0; i < n; i++) { dp[i][0] = parent[i]; } for(int i = 0; i < n; i++) { // 先枚举状态j i都可 for(int j = 1; 1 << j < n; j++) { if(dp[i][j-1] != -1) { dp[i][j] = dp[dp[i][j-1]][j-1]; } else { dp[i][j] = -1; } } } } public int getKthAncestor(int node, int k) { if(node == -1 || k == 0) return node; int num = (int)(Math.log(k) / Math.log(2)); return getKthAncestor(dp[node][num],k - (1 << num)); } } /** * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor obj = new TreeAncestor(n, parent); * int param_1 = obj.getKthAncestor(node,k); */

 

最近公共祖先(LCA树上倍增)

原文:https://www.cnblogs.com/yonezu/p/13261751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!