#P2982. Cow Traffic Slowdown

    ID: 16240 Type: Default 1000ms 256MiB

Cow Traffic Slowdown

Cow Traffic Slowdown

Farmer John's farm consists of N pastures arranged in a tree with N−1 paths. The barn is at pasture 1. Each path connects two pastures and the unique path from the barn to any pasture is well‐defined. The farm also has N cows numbered from 1 to N. Cow i has a private pasture Pi. The barn door is so small that only one cow exits at a time. Thus, cows leave one by one: cow 1 leaves and travels from the barn (pasture 1) to P1, then cow 2 leaves and travels from pasture 1 to P2, and so on. When cow i travels along the unique path from 1 to Pi, she must slow down in any pasture that is already occupied by a cow that arrived earlier (i.e. a cow that already reached her private pasture).

For example, consider the following farm layout (each edge is bidirectional; the barn is at node 1) and the private pastures indicated in parentheses:

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

The cows leave in order. Suppose the private pastures for cows 1..5 are:

  • Cow 1: 4
  • Cow 2: 2
  • Cow 3: 1
  • Cow 4: 5
  • Cow 5: 3

When cow 1 moves to pasture 4, no pasture is occupied and she never slows down. When cow 2 moves along the path 1→4→2, she finds that pasture 4 is already occupied by cow 1, so she slows down once. Similarly, subsequent cows slow down each time they pass through a pasture where a previous cow is grazing. Farmer John would like to know the total number of slowdowns encountered by all cows.

Note: The unique path from 1 to Pi is exactly the list of ancestors of Pi (including 1 and Pi) in the tree rooted at 1.

inputFormat

The first line contains a single integer N (1 ≤ N ≤ 100,000), the number of cows (and pastures).

The next N−1 lines each contain two integers Ai and Bi (1 ≤ Ai, Bi ≤ N), indicating that there is a path connecting pasture Ai and pasture Bi.

The last line contains N integers: P1, P2, …, PN (1 ≤ Pi ≤ N), where Pi is the private pasture of cow i.

outputFormat

Output a single integer, the total number of times that cows slow down.

sample

5
1 4
4 2
1 3
4 5
4 2 1 5 3
4