Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests.
If you've seen these problems, a virtual contest is not for you - solve these problems in the archive.
If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive.
Never use someone else's code, read the tutorials or communicate with other person during a virtual contest.

No tag edit access

The problem statement has recently been changed. View the changes.

×
F. Imbalance Value of a Tree

time limit per test

4 secondsmemory limit per test

256 megabytesinput

standard inputoutput

standard outputYou are given a tree *T* consisting of *n* vertices. A number is written on each vertex; the number written on vertex *i* is *a*_{i}. Let's denote the function *I*(*x*, *y*) as the difference between maximum and minimum value of *a*_{i} on a simple path connecting vertices *x* and *y*.

Your task is to calculate .

Input

The first line contains one integer number *n* (1 ≤ *n* ≤ 10^{6}) — the number of vertices in the tree.

The second line contains *n* integer numbers *a*_{1}, *a*_{2}, ..., *a*_{n} (1 ≤ *a*_{i} ≤ 10^{6}) — the numbers written on the vertices.

Then *n* - 1 lines follow. Each line contains two integers *x* and *y* denoting an edge connecting vertex *x* and vertex *y* (1 ≤ *x*, *y* ≤ *n*, *x* ≠ *y*). It is guaranteed that these edges denote a tree.

Output

Print one number equal to .

Example

Input

4

2 2 3 1

1 2

1 3

1 4

Output

6

Codeforces (c) Copyright 2010-2020 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Oct/25/2020 02:33:24 (h1).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|