Kinship
View as PDFTwo goblins want to file a joint petition, but kingdom law is unforgiving: they must present
it to their closest shared superior. That superior is the lowest goblin who sits above both
of them in the hierarchy (or one of them, if one already outranks the other). The king
(goblin ) is above everyone.
As Indra's fairy godmother, you must answer kinship queries: given goblins
and
,
who is their closest shared superior?
Input
The first line contains two integers and
: the number of goblins and the number of
queries.
The next lines each contain two integers
and
, meaning that goblin
is the
superior of goblin
.
Finally, the next lines each contain two integers
and
, representing one query.
Output
For each query, output a single integer on its own line: the closest shared superior of
goblins and
.
Constraints
- The superiors form a tree rooted at goblin
Example 1
Input
5 4
0 1
0 2
1 3
1 4
3 4
3 2
0 3
4 4
Output
1
0
0
4
Explanation
- Goblins
and
meet at
.
- Goblins
and
meet at the king
.
- Goblins
and
meet at
(the king already outranks
).
- A goblin's closest shared superior with themselves is themselves.
Comments