Professional Documents
Culture Documents
Col106 Lca PDF
Col106 Lca PDF
Algorithms
Keerti Choudhary
Department of Computer Science, IIT Delhi
Lowest Common Ancestor
De nition: For any two vertices x and y in a tree T rooted at source s, the
Lowest-Common-Ancestor of x, y a.k.a. LCA(x, y) is that common ancestor
of x and y that is farthest from s.
Example:
S
0
A B C
1
D F H I J 2
LCA(P,Q)
K L M N 3
O P Q 4
fi
Lowest Common Ancestor
De nition: For any two vertices x and y in a tree T rooted at source s, the
Lowest-Common-Ancestor of x, y a.k.a. LCA(x, y) is that common ancestor
of x and y that is farthest from s.
Example:
S
0
LCA(K,F) 1
A B C
D F H I J 2
K L M N 3
O P Q 4
fi
Lowest Common Ancestor
De nition: For any two vertices x and y in a tree T rooted at source s, the
Lowest-Common-Ancestor of x, y a.k.a. LCA(x, y) is that common ancestor
of x and y that is farthest from s.
Example:
LCA(L,Q)
S
0
A B C
1
D F H I J 2
K L M N 3
O P Q 4
fi
LCA Oracle
A(X, 3)
A(X, 1)
Values A(x, i) can be computed in top-down
manner in a total of O(n log n) time as
A(X, 0)
A(x, i + 1) = A(y, i), where y = A(x, i) X
S
Answering Query
W
Step 1: Suppose level(x) ⩾ level(y), then in
O(log n) time nd an ancestor ‘z’ of x such that
level(z) = level(y)
A(J, 1) Z Y
Algorithm to nd z:
Represent | level(x) − level(y) | as sum of
J A(X, 2)
powers of 2, and take hops according to these
powers.
Example: if level di erence is 6 = 22 + 21,
then rst hop is of 22 and second hop is 21.
X
fi
fi
fi
ff
S
Answering Query
Parent(Y’’)
W
Step 2: Given y, z satisfying level(y) = level(z),
we will compute LCA(y, z) in O(log n) time.
A(Y’, 1) Y’’ Z’’
Y Z
fi