Under construction

Still being built. Things may change

Meeting Place

Interview

Time limit1sMemory limit128 MB

Summary
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 11 (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 NN pastures (1≤N≤10001 \le N \le 1000), numbered 11 through NN. For every pasture except pasture 11 you are given its parent PiP_i (1≤Pi≤N1 \le P_i \le N). Over the next MM days (1≤M≤10001 \le M \le 1000), on day kk Bessie is in pasture BkB_k and Jonell is in pasture JkJ_k (1≤Bk,Jk≤N1 \le B_k, J_k \le N). For each day, report their meeting place.

For example, consider the following farm, where pasture 11 is the root:

         [1]
       /  |  \
     [2] [3] [6]
     /        |  \
   [4]      [8]  [9]
           /  \
         [5]  [7]

In this farm the meeting place for pastures 77 and 55 is pasture 88 (their closest common ancestor), and the meeting place for pastures 22 and 77 is pasture 11.

Input

  • Line 11: two space-separated integers NN and MM.
  • Lines 2…N2 \dots N: line ii contains a single integer PiP_i, the parent of pasture ii.
  • Lines N+1…N+MN+1 \dots N+M: line N+kN+k contains two space-separated integers BkB_k and JkJ_k, Bessie's and Jonell's pastures on day kk.

Output

  • Lines 1…M1 \dots M: line kk contains a single integer, the meeting place for Bessie and Jonell on day kk.

Examples3

  1. Example 1

    Input
    9 6
    1
    1
    2
    8
    1
    8
    6
    6
    2 7
    4 2
    3 3
    4 1
    7 5
    9 5
    
    Expected output
    1
    2
    3
    1
    8
    6
    
  2. Example 2

    Input
    1 1
    1 1
    
    Expected output
    1
    
  3. Example 3

    Input
    2 4
    1
    1 2
    2 2
    1 1
    2 1
    
    Expected output
    1
    2
    1
    1