LCA - Lowest Common Ancestor

no tags 

A tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree. - Wikipedia 

The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T be a rooted tree with N nodes. The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself). - Wikipedia

Your task in this problem is to find the LCA of any two given nodes v and w in a given tree T.

For example the LCA of nodes 9 and 12 in this tree is the node number 3.


The first line of input will be the number of test cases. Each test case will start with a number N the number of nodes in the tree, 1 <= N <= 1,000. Nodes are numbered from 1 to N. The next N lines each one will start with a number M the number of child nodes of the Nth node, 0 <= M <= 999 followed by M numbers the child nodes of the Nth node. The next line will be a number Q the number of queries you have to answer for the given tree T, 1 <= Q <= 1000. The next Q lines each one will have two number v and w in which you have to find the LCA of v and w in T, 1 <= v, w <= 1,000.

Input will guarantee that there is only one root and no cycles.


For each test case print Q + 1 lines, The first line will have “Case C:” without quotes where C is the case number starting with 1. The next Q lines should be the LCA of the given v and w respectively.


3 2 3 4
3 5 6 7
5 7
2 7

Case 1:

hide comments
harshiscoding: 2021-01-23 15:13:42

@up_in_smoke ,use if(n===0) break

princemishra: 2020-12-31 18:35:09

even LCA with O(n) works and rooted at node 1

Last edit: 2020-12-31 18:35:33
wille_25: 2020-12-29 13:48:57

the value of M is not really 999, its around 200 ..the problem setter should look at this ...i took the value 999 & total iteration using sparse table +RMQ is (N*M)=(1000*999) but it gives TLE ..take M=200 .

Last edit: 2020-12-29 13:49:26
satyamkr118: 2020-12-27 12:35:12

My 100th one!!

s_tank00_: 2020-10-27 09:24:47

why i m getting a tle please help here's my code

[NG]: Read the footer.

Last edit: 2020-10-29 13:47:29
raka143: 2020-08-28 14:12:59

LCA using binary lifting works fine. Took me 0.05s.

k_r_i_s_h_123: 2020-08-24 15:03:35

getting wrong answer using binary lifting .............HELP

junloveyin: 2020-08-22 16:03:42

@sknayak you should reset array after found all LCA of (u,v) .

Last edit: 2020-08-22 16:04:02
sknayak: 2020-08-20 09:27:44

I am getting TLE using binary lifting and sparse table in c++. Can anyone help please?

up_in_smoke: 2020-08-10 14:43:50

I am getting this error : runtime error (SIGABRT) and I've no idea how please help. Used RMQ + segment tree

Last edit: 2020-08-10 14:44:18

Added by:hossamyosef
Time limit:0.600s-1.113s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Resource:FCIS/ASU Local Contest 2013