Processing math: 100%
(Analysis by Benjamin Qi)

If pj=i, say that j is a child of i and i is a parent of j. Let's first compute the length and number of children for each word i.

When Bessie chooses a word wi to read from the word bank, what she actually reads will be some word xi that is a prefix of wi. We will initialize xi=wi and then repeatedly replace xi with its parent while wi can still be uniquely identified from xi. Specifically,

  1. If xi=0 or pxi has more than one child, we should stop (wi can't be uniquely identified from pxi).
  2. Otherwise, xi is the only child of pxi, so reading pxi is enough to uniquely identify xi and therefore wi. Thus, we can repeatedly set xi=pxi until the first case holds.

When xi has been determined, print its length. Then wi is removed from the word bank, so all words from xi to wi inclusive can be ignored going forward. We also decrease the number of children of pxi by one to account for ignoring xi.

The number of operations performed for wi is proportional to a constant plus the number of ignored words. As the total number of ignored words cannot exceed the total number of words, the overall time complexity is O(N).

Python code:

N = int(input())
P = [0] + list(map(int, input().split()))
num_child = [0] * (N+1)
length = [0]*(N+1)
for i in range(1,N+1):
    length[i] = length[P[i]]+1
    num_child[P[i]] += 1
 
M = sum(x == 0 for x in num_child)
for _ in range(M):
    x = int(input())
    while True:
        assert num_child[x] == 0
        if x == 0:
            print(0)
            break
        if num_child[P[x]] == 1:
            x = P[x]
            num_child[x] = 0
            continue
        print(length[x])
        num_child[P[x]] -= 1
        break

Bonus: The above solution may take proportional to N time to process a single wi. Write a solution that preprocesses the pi in O(N) time, and then processes each wi in O(1) time.