Binary path in a tree

2.3

6 votes
Dynamic Programming, Algorithms, 1-D, Trees, DFS
Problem

You are given a rooted tree consisting of n vertices. The vertices of the tree are numbered by integers from 1 to n. The parent of vertex v is represented as parv. The root of the tree is a vertex with number 1.

You are required to answer q queries. Each query is described by two integers vj and uj. The answer to query vj, uj is the minimum number of attempts for reaching the vertex uj from vj. You can perform one of the following operations per attempt:

  • Traverse to a neighbor of the current vertex.
  • Traverse to the (2k)th parent of current vertex where k is a non-negative integer.
  • If the current distance with the root is an even number, going to the vertex in the path between me and root where the distance of those vertex with me and root is equal.

Input format

  • First line: An integer n denoting the number of nodes in the tree (1n5000)
  • Next line: n1 space-separated integers where the ith integers is pari and it denotes the parent of vertex i (1pari<i)

Output format

For each query, print the minimum number of attempts to reach from the first node to the second node.

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

The path for each query is as follows (select path with minimum length):

7 -> 5 -> 1

7 -> 3 -> 8

5 -> 1 -> 10

9 -> 3 -> 4 -> 5 -> 6

Editor Image

?