zoukankan      html  css  js  c++  java
  • 最近公共祖先(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); */
  • 相关阅读:
    List三个子类的特点
    三种迭代是否可以删除
    Vector
    LinkedList
    ArrayList
    ListIterator
    ConcurrentModificationException并发修改异常
    List
    Collection
    数组转换成集合
  • 原文地址:https://www.cnblogs.com/yonezu/p/13261751.html
Copyright © 2011-2022 走看看