I'm having an issue understanding how to exactly approach the following problem:
Rooted tree is given on the standard input as a List of parents. First line contain the number N of the vertices, labeled from 1 to N, and on each of the next N всхея – the father of the corresponding vertex (I-th of these lines contain the father of the vertex I). As a father of the root of the tree the nonexisting vertex 0 is mentioned. The last line will contain the vertices u and v separated by an interval.
And on the single line of the standard output the program has to print the lowest common ancestor of u and v in the given rooted tree.
I am given the following example input :
1 2 3 4 5 6 7 8 9 10 11 12
10
0
1
2
3
3
5
5
7
5
2
6 10
And the following example Output :
2
I'm really failing to understand exactly how to approach this problem, so if anyone can give a hint or show me some example so i can get e better idea.
Because i try to get a somewhat of a tree built, but how do you exactly make this search ?
a basic approach would be to get the root to u path and root to v path.
Then compare those two paths and the node previous to the first mismatch will be the LCA of u and v.