Meeting Place
InterviewTime limit1sMemory limit128 MB
Given a rooted tree and M queries, report the lowest common ancestor of two nodes for each query.
- Level
Medium4 of 10
- Topics
- Tree, DFS, Implementation, Brute force
- Solved
- No attempts yet
Problem
Bessie and Jonell are great friends. Because Farmer John shuffles where the cows graze every day, they sometimes end up far apart and cannot talk.
The pastures and paths on the farm form a tree: between any two pastures there is exactly one path, and every pasture except pasture (the root) has exactly one parent pasture.
Whenever they want to gossip, Bessie and Jonell agree to meet at the closest pasture that is an ancestor of both Bessie's pasture and Jonell's pasture. A pasture is considered an ancestor of itself, so if one of them is already an ancestor of the other, they simply meet at that pasture.
The farm has pastures (), numbered through . For every pasture except pasture you are given its parent (). Over the next days (), on day Bessie is in pasture and Jonell is in pasture (). For each day, report their meeting place.
For example, consider the following farm, where pasture is the root:
[1]
/ | \
[2] [3] [6]
/ | \
[4] [8] [9]
/ \
[5] [7]
In this farm the meeting place for pastures and is pasture (their closest common ancestor), and the meeting place for pastures and is pasture .
Input
- Line : two space-separated integers and .
- Lines : line contains a single integer , the parent of pasture .
- Lines : line contains two space-separated integers and , Bessie's and Jonell's pastures on day .
Output
- Lines : line contains a single integer, the meeting place for Bessie and Jonell on day .