Slowing down

Time limit1sMemory limit128 MB

Summary
For each cow in order, count how many pastures already occupied by earlier cows lie on the tree path from node 1 to that cow's pasture.
Level

Medium7 of 10

Topics
Tree, DFS, Prefix sum, Implementation
Solved
No attempts yet

Problem

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

The pastures form a tree of NN nodes; the barn sits at pasture 11. Exactly N−1N-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 ii connects pastures AiA_i and BiB_i.

Cow ii owns the private pasture PiP_i. Every pasture is owned by exactly one cow, so P1,P2,…,PNP_1, P_2, \dots, P_N is a permutation of 1…N1 \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 11 leaves and walks from pasture 11 to P1P_1 and starts eating there. Then cow 22 leaves and walks from pasture 11 to P2P_2, and so on.

While cow ii walks to PiP_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 ii slows down once for every earlier cow (among cows 1…i−11 \dots i-1) whose pasture lies on the route from the barn (pasture 11) to PiP_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 11 walks to pasture 44 and meets no one. Cow 22 walks to pasture 22, passing the occupied pasture 44 on the way, so she slows down once. Cow 33 owns pasture 11 (the barn) and slows down zero times. Cow 44 walks to pasture 55, passing the occupied pastures 11 and 44, slowing down twice. Cow 55 walks to pasture 33, passing the occupied pasture 11, slowing down once.

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

Input

  • Line 11: a single integer NN (1≤N≤100,000)(1 \le N \le 100{,}000).
  • Lines 2…N2 \dots N: line i+1i+1 contains two space-separated integers AiA_i and BiB_i (1≤Ai,Bi≤N)(1 \le A_i, B_i \le N), a path between pastures AiA_i and BiB_i.
  • Lines N+1…N+NN+1 \dots N+N: line N+iN+i contains a single integer PiP_i (1≤Pi≤N)(1 \le P_i \le N), the pasture owned by cow ii.

Output

  • Lines 1…N1 \dots N: line ii contains a single integer, the number of times cow ii slows down on her way to pasture PiP_i.

Examples2

  1. Example 1

    Input
    5
    1 4
    5 4
    1 3
    2 4
    4
    2
    1
    5
    3
    
    Expected output
    0
    1
    0
    2
    1
    
  2. Example 2

    Input
    5
    1 2
    2 3
    3 4
    4 5
    1
    2
    3
    4
    5
    
    Expected output
    0
    1
    2
    3
    4