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

 

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); */

 

posted @ 2020-07-07 16:43  Sexyomaru  阅读(159)  评论(0编辑  收藏  举报