Inversions in a Tree#13094

Inversions in a Tree

3 seconds
256 megabytes

You are given a tree with vertices numbered from to . The tree is rooted at vertex .

Each vertex has a label p_i. All labels are distinct and form a permutation of the integers from to .

An inversion is a pair of vertices satisfying both conditions:

You may perform at most one operation: choose any edge and swap the labels of its endpoints. The structure of the tree does not change.

Find the maximum possible number of inversions after performing at most one operation.

Input

The first line contains an integer (1 \leq n \leq 2 \cdot 10^5) — the number of vertices.

The second line contains integers p_1,p_2,\ldots,p_n (1 \leq p_i \leq n) — the labels. All these numbers are distinct.

Each of the next n-1 lines contains two integers and (1 \leq u,v \leq n, u \ne v), describing an edge of the tree.

It is guaranteed that the given graph is a tree.

Output

Print one integer — the maximum possible number of inversions.

Examples

Example 1

Loading
Loading

Example 2

Loading
Loading

Example 3

Loading
Loading

Note

In the first sample, the tree consists of one vertex. There are no inversions, and no operation is possible. Therefore, the answer is .

In the second sample, swap the labels at vertices and . Then vertex contains , and all four other vertices contain smaller labels. As vertex is an ancestor of all of them, there are inversions. No higher value is possible.

In the third sample, the vertices form the path ––– with labels 4,3,2,1. Every pair of distinct vertices is an inversion, giving inversions in total. This is already the maximum for four vertices, so no operation is needed.

Scoring

  1. points — 1 \leq n \leq 10.

  2. points — the tree is a star centered at vertex .

  3. points — the tree is a simple path with vertex as one of its endpoints.

  4. points — 1 \leq n \leq 3000.

  5. points — no additional constraints.