算法 – 最低共同祖先

我正在寻找恒定时间实现最低共同祖先给定完整二叉树中的两个节点(父x比子2 * x和2 * x 1).

我的问题是树中有大量节点和许多查询.是否有一个算法,它预处理,以便可以在恒定的时间内回答查询.

我查看了LCA using RMQ,但我不能使用该技术,因为我不能在树中使用这个节点的数组.

有人可以给我快速回答许多查询的算法的有效实现,知道它是完整的二叉树,节点之间的关系如上所述.

我所做的是从两个给定节点开始,并连续找到它们的父节点(节点/ 2)保持被访问节点的哈希列表.当我们到达已经在哈希列表中的节点时,该节点将是最低的共同祖先.

但是当存在许多查询时,这种算法非常耗时,因为在最坏的情况下,我可能必须遍历高度30(树的最大高度)才能到达根(最坏的情况).

最佳答案
编辑: –

更快地获取O(log(logn))中的common_ancestor: –

int get_bits(unsigned int x) {
  int high = 31;
  int low = 0,mid;
  while(high>=low) {
    mid = (high+low)/2;
    if(1<<mid==x)
      return mid+1;
    if(1<<mid<x) {
      low = mid+1;
    }
    else {
      high = mid-1;
    }
  }
  if(1<<mid>x)
    return mid;
  return mid+1;
}

unsigned int Common_Ancestor(unsigned int x,unsigned int y) {

  int xbits = get_bits(x);
  int ybits = get_bits(y);
  int diff,kbits;
  unsigned int k;
  if(xbits>ybits) {
    diff = xbits-ybits;
    x = x >> diff;
  }
  else if(xbits<ybits) {
    diff = ybits-xbits;
    y = y >> diff;
  }
  k = x^y;
  kbits = get_bits(k);
  return y>>kbits;  

}

说明: –

  1. get bits needed to represent x & y which using binary search is O(log(32))
  2. the common prefix of binary notation of x & y is the common ancestor
  3. whichever is represented by larger no of bits is brought to same bit by k >> diff
  4. k = x^y erazes common prefix of x & y
  5. find bits representing the remaining suffix
  6. shift x or y by suffix bits to get common prefix which is the common ancestor.

示例: –

x = 12 = b1100 
y = 8  = b1000

xbits = 4
ybits = 4
diff = 0
k = x^y = 4 = b0100
kbits = 3
res = x >> kbits = x >> 3 = 1

ans : 1

转载注明原文:算法 – 最低共同祖先 - 代码日志