import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } real readReal() { return readToken.to!real; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } int N; int[] A; int[] X, Y; int[][] G; long[][] dp; void dfs(int u, int p) { foreach (v; G[u]) { if (v != p) { dfs(v, u); } } auto pss = new Tuple!(int, int)[][2]; foreach (v; G[u]) { if (v != p) { if (A[v] < A[u]) { pss[0] ~= tuple(A[v], v); } else if (A[v] > A[u]) { pss[1] ~= tuple(A[v], v); } } } foreach (h; 0 .. 2) { pss[h].sort; } auto psLens = pss.map!(ps => cast(int)(ps.length)).array; // not using p foreach (h; 0 .. 2) { long sum, cnt; for (int i = 0, j; i < psLens[h]; i = j) { long mx; for (; j < psLens[h] && pss[h][i][0] == pss[h][j][0]; ++j) { chmax(mx, dp[1][pss[h][j][1]]); } sum += mx; ++cnt; } chmax(dp[0][u], sum + cnt * (cnt - 1) / 2); } // using p if (p != -1) { const h = (A[p] < A[u]) ? 0 : 1; long sum, cnt = 1; for (int i = 0, j; i < psLens[h]; i = j) { long mx; for (; j < psLens[h] && pss[h][i][0] == pss[h][j][0]; ++j) { chmax(mx, dp[1][pss[h][j][1]]); } if (A[p] != pss[h][i][0]) { sum += mx; ++cnt; } } dp[1][u] = sum + cnt * (cnt - 1) / 2; } } void main() { try { for (; ; ) { N = readInt(); A = new int[N]; foreach (u; 0 .. N) { A[u] = readInt(); } X = new int[N - 1]; Y = new int[N - 1]; foreach (i; 0 .. N - 1) { X[i] = readInt() - 1; Y[i] = readInt() - 1; } G = new int[][N]; foreach (i; 0 .. N - 1) { G[X[i]] ~= Y[i]; G[Y[i]] ~= X[i]; } dp = new long[][](2, N); dfs(0, -1); const ans = dp[0].maxElement; writeln(ans); } } catch (EOFException e) { } }