#P11162. Car Race

    ID: 13226 Type: Default 1000ms 256MiB

Car Race

Car Race

This problem is adapted from BalkanOI 2023 Day1 T1 "Car Race".

The city has built a racetrack in the old industrial area in the shape of a rooted tree with $n$ vertices labeled $0,1,\dots,n-1$, where the vertex $0$ is the root. Initially, some vertices contain a race car. Every second, each car moves from its current vertex to its parent (i.e. towards the root). At any non‐root vertex, if two or more cars arrive at the same time, they collide and are removed from the race. The root can hold any number of cars at any time.

For each vertex $v$, define an integer $c_v$ as follows:

  • If vertex $v$ does not have a car at the beginning, then $c_v=-1$.
  • If the car starting from vertex $v$ collides on the way to the root, then $c_v=-1$.
  • Otherwise, $c_v$ is the time taken for the car to reach the root (i.e. the length of the unique path from $v$ to $0$).

Your task is to compute $c_v$ for every vertex $v$.

Note: If a car collides at any non-root vertex on its path, it will not continue the journey.

inputFormat

The first line contains an integer $n$ ($1\le n\le 10^5$) representing the number of vertices in the tree.

The second line contains $n-1$ space-separated integers $p_1, p_2, \dots, p_{n-1}$, where $p_i$ is the parent of vertex $i$ ($0 \le p_i < i$). It is guaranteed that the tree is rooted at vertex $0$.

The third line contains $n$ space-separated integers, each either 0 or 1. The $i$-th integer indicates whether vertex $i$ initially has a car (1 means there is a car, and 0 means there is no car).

outputFormat

Output $n$ space‐separated integers $c_0, c_1, \dots, c_{n-1}$ where $c_v$ is defined as described in the problem.

sample

5
0 0 1 1
0 1 1 0 1
-1 1 -1 -1 2