PivotOJ

Cat Exercise

시간 제한: 2000ms메모리 제한: 1024MB출처: JOI 2022-2023 본선BOJ 27539

문제

There are NN cat towers, numbered from 11 to NN. The height of Tower ii (1 ≤ i ≤ N) is PiP_i. The heights of the towers are distinct integers between 11 and NN, inclusive. There are N1N - 1 adjacent pairs of towers. For each jj (1 ≤ j ≤ N - 1), Tower AjA_j and Tower BjB_j are adjacent to each other. In the beginning, it is possible to travel from a tower to any other tower by repeating moves from towers to adjacent towers.

In the beginning, a cat stays in a tower of height NN.

Then we perform cat exercises. In cat exercises, we repeatedly choose a tower and put an obstacle on it. However, we cannot put an obstacle on a tower where we already put an obstacle on it. During the process, the following will happen.

  • If the cat does not stay in the chosen tower, nothing will happen.
  • If the cat stays in the chosen tower and there is an obstacle on every tower which is adjacent to the chosen tower, the cat exercises will finish.
  • Otherwise, among the towers where the cat can arrive by repeating moves from towers to adjacent towers without obstacles, the cat will move to the highest tower except for the current tower by repeating moves from towers to adjacent towers. In this process, the cat takes the route where the number of moves from towers to adjacent towers becomes minimum.

Given information of the heights of the towers and pairs of adjacent towers, write a program which calculates the maximum possible sum of the number of moves of the cat from towers to adjacent towers if we put obstacles suitably

입력

Read the following data from the standard input.

NN

P1P_1 P2P_2 \cdots PNP_N

A1A_1 B1B_1

A2A_2 B2B_2

\vdots

AN1A_{N-1} BN1B_{N-1}

출력

Write one line to the standard output. The output should contain the maximum possible sum of the number of moves of the cat from towers to adjacent towers.

예제

예제 1

입력
4
3 4 1 2
1 2
2 3
3 4
출력
3

예제 2

입력
7
3 2 7 1 5 4 6
1 2
1 3
2 4
2 5
3 6
3 7
출력
7
코드를 제출하려면 로그인하세요.