Slowing down

No attempts yetTime limit1sMemory limit128 MB

Problem

Farmer John has $N$ cows, conveniently numbered $1 \dots N$. Every day each cow walks from the barn to her own private pasture.

The pastures form a tree of $N$ nodes; the barn sits at pasture $1$. Exactly $N-1$ two-way paths connect the pastures, and any two directly connected pastures share exactly one path, so there is a unique route between any pair of pastures. Path $i$ connects pastures $A_i$ and $B_i$.

Cow $i$ owns the private pasture $P_i$. Every pasture is owned by exactly one cow, so $P_1, P_2, \dots, P_N$ is a permutation of $1 \dots N$.

The barn's narrow door lets only one cow leave at a time, and each cow waits until the cow before her has reached her own pasture. First cow $1$ leaves and walks from pasture $1$ to $P_1$ and starts eating there. Then cow $2$ leaves and walks from pasture $1$ to $P_2$, and so on.

While cow $i$ walks to $P_i$, she may pass through pastures already occupied by a cow that arrived earlier. Each time she enters such an occupied pasture she slows down to avoid disturbing her friend. In other words, cow $i$ slows down once for every earlier cow (among cows $1 \dots i-1$) whose pasture lies on the route from the barn (pasture $1$) to $P_i$.

In the network below, the number in parentheses is the owner of each pasture:

        1 (3)
       / \
  (1) 4   3 (5)
     / \
(2) 2   5 (4)

Cow $1$ walks to pasture $4$ and meets no one. Cow $2$ walks to pasture $2$, passing the occupied pasture $4$ on the way, so she slows down once. Cow $3$ owns pasture $1$ (the barn) and slows down zero times. Cow $4$ walks to pasture $5$, passing the occupied pastures $1$ and $4$, slowing down twice. Cow $5$ walks to pasture $3$, passing the occupied pasture $1$, slowing down once.

Farmer John wants to know how many times each cow slows down.

Input

  • Line $1$: a single integer $N$ $(1 \le N \le 100{,}000)$.
  • Lines $2 \dots N$: line $i+1$ contains two space-separated integers $A_i$ and $B_i$ $(1 \le A_i, B_i \le N)$, a path between pastures $A_i$ and $B_i$.
  • Lines $N+1 \dots N+N$: line $N+i$ contains a single integer $P_i$ $(1 \le P_i \le N)$, the pasture owned by cow $i$.

Output

  • Lines $1 \dots N$: line $i$ contains a single integer, the number of times cow $i$ slows down on her way to pasture $P_i$.