#HK4105. 「BalkanOI 2023 Day1」Car Race

「BalkanOI 2023 Day1」Car Race

Description

To attract more visitors and money to the once proud but now more or less abandoned industrial area of Maribor, the city built a race track on the site of the former Metalna factory (one of multiple large Maribor businesses that were forced to shut down in the early 1990s). The track is constructed in the form of a rooted tree of nn vertices. The vertices of the tree are numbered with integer numbers 0,1,,n10,1, \ldots, n-1, with the root having the number 00.

Let the race begin! Initially, there are cars at some vertices of the tree. Every second, each car moves to the adjacent vertex in the direction towards the root. At any moment, if two or more cars happen to be simultaneously at the same vertex with a number greater than 00, they collide and cannot participate in the race any more. For vertex 00 (the root), this rule does not hold; the root may hold any number of cars at any moment.

For each vertex vv, output the integer cvc_{v}, which is defined as follows:

  • If there was no car at vertex vv at the beginning of the race, cvc_{v} is 1-1.
  • Otherwise, if the car that started at vertex vv collides on its way to the root, then cvc_{v} is 1-1.
  • Otherwise, cvc_{v} is the time when the car that started at vertex vv reaches the root.

Input format

The first line contains an integer nn, which represents the number of vertices in the tree.

The second line contains n1n-1 integers, namely p1,p2,,pn1p_{1}, p_{2}, \ldots, p_{n-1}. For each i{1,,n1}i \in\{1, \ldots, n-1\}, pip_{i} denotes the parent of vertex ii; it holds that 0pi<i0 \leq p_{i}<i.

The third line contains nn integers, namely a0,a1,,an1a_{0}, a_{1}, \ldots, a_{n-1}. For each i{0,,n1}i \in\{0, \ldots, n-1\}, aia_{i} is either 00 or 11. If there is a car at vertex ii at the beginning of the race, then ai=1a_{i}=1; otherwise, ai=0a_{i}=0.

Output format

Print the integers c0,c1,,cn1c_{0}, c_{1}, \ldots, c_{n-1} on a single line, separated by a single space.

Input bounds

  • 1n1061 \leq n \leq 10^{6}.

Subtasks

  1. (3 points) n3n \leq 3.
  2. (5 points) pi=i1p_{i}=i-1 for each i{1,,n1}i \in\{1, \ldots, n-1\}.
  3. (8 points) n500n \leq 500.
  4. (9 points) n3000n \leq 3000.
  5. (10 points) n105n \leq 10^{5}.
  6. (9 points) pi=i12p_{i}=\frac{i-1}{2}.
  7. (14 points) n2105n \leq 2 \cdot 10^{5}.
  8. (19 points) Each vertex has at most 3 neighbors (i.e., the root has at most 3 children, and all other vertices have at most 2 children).
  9. (23 points) No additional constraints.
5
0 1 1 3
0 1 1 1 1
-1 1 -1 -1 3

Vertex 00 (the root) contained no car at the beginning of the race. It takes 11 second for the car starting from vertex 11 to arrive to the root, and 33 seconds for the car starting from vertex 44 to do the same. The cars starting from vertices 2 and 33 collide on their way to the root (this happens at node 11).