Source Code
n = int(input())
if n < 2:
    print(0)
    exit()
m = [int(b) for b in input().split(" ")]
p = [int(b) for b in input().split(" ")]
answers = [0 for i in range(n)]

h = {}
for i in range(1, n + 1):
    h[i] = []
for i in range(n - 1):
    h[m[i]].append(i + 2)
    
def find_candidates(current, depth, target):
    if depth == 0:
        if answers[target - 1] == 0 or abs(p[target - 1] - p[current - 1]) < abs(p[target - 1] - p[answers[target - 1] - 1]):
            answers[target - 1] = current
        elif abs(p[target - 1] - p[current - 1]) == abs(p[target - 1] - p[answers[target - 1] - 1]):
            answers[target - 1] = min(answers[target - 1], current)
        return
    for can in h[current]:
        find_candidates(can, depth - 1, target)

for i in range(1 ,n + 1):
    #candidates = []
    find_candidates(i, 4, i)
    
for ans in answers:
    print(ans, end=" ")
print()
Copy
Find a Friend Heromnxpw0
Python 3
1268 ms
66.3 MB
Accepted