Under construction

Still being built. Things may change

Cat Exercise

Time limit2sMemory limit1024 MB

Summary
Place obstacles on a tree of towers to maximize the total number of moves a cat makes while jumping to the highest reachable tower each time.
Level

Hard8 of 10

Topics
Tree, Dynamic programming, Greedy
Solved
No attempts yet

Problem

There are NN cat towers, numbered from 11 to NN. The height of Tower ii (1≤i≤N1 \le i \le N) is PiP_i. The heights are distinct integers between 11 and NN, inclusive. There are N−1N-1 adjacent pairs of towers. For each jj (1≤j≤N−11 \le j \le N-1), Tower AjA_j and Tower BjB_j are adjacent. At the start, you can travel from any tower to any other tower by moving between adjacent towers.

At the start, a cat stays in the tower of height NN.

Then we perform cat exercises. In each exercise, we choose a tower and put an obstacle on it. A tower cannot receive a second obstacle. The following happens.

  • If the cat is not in the chosen tower, nothing happens.
  • If the cat is in the chosen tower and every tower adjacent to it has an obstacle, the cat exercises end.
  • Otherwise, the cat moves to the highest tower, excluding its current tower, among the towers it can reach from its current tower without passing through obstacles. It takes the route with the fewest moves between adjacent towers.

Given the tower heights and the adjacency pairs, write a program that finds the maximum possible sum of the cat's moves between adjacent towers when obstacles are placed optimally.

Input

NN

P1P_1 P2P_2 ⋯\cdots PNP_N

A1A_1 B1B_1

A2A_2 B2B_2

⋮\vdots

AN−1A_{N-1} BN−1B_{N-1}

Output

Print one line containing the maximum possible sum of the cat's moves between adjacent towers.

Constraints

  • 2≤N≤200 0002 \le N \le 200\,000.
  • 1≤Pi≤N1 \le P_i \le N (1≤i≤N1 \le i \le N).
  • Pi≠PjP_i \ne P_j (1≤i<j≤N1 \le i < j \le N).
  • 1≤Aj<Bj≤N1 \le A_j < B_j \le N (1≤j≤N−11 \le j \le N-1).
  • At the start, you can travel from any tower to any other tower through adjacent towers.
  • All given values are integers.

Examples2

  1. Example 1

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

    Input
    7
    3 2 7 1 5 4 6
    1 2
    1 3
    2 4
    2 5
    3 6
    3 7
    
    Expected output
    7