/* * Problem link * */ #include using namespace std; struct INIT{INIT(){cin.tie(0);ios_base::sync_with_stdio(false);} }init; typedef vector V; typedef vector E; typedef vector Graph; typedef long long LL; #define rep(i,n) for (auto i = 0; i < n; i++) #define range(it,v) for(auto &it:v) void make_tree(int v, Graph &G, E &P,Graph &C) { range(to, G[v]) { if (to != P[v]) { C[v].push_back(to); P[to] = v; make_tree(to, G, P, C); } } } int main() { #ifdef INPUT_FROM_FILE ifstream cin("sample.in"); ofstream cout("sample.out"); #endif int N; while (cin >> N) { V val(N + 1), par(N, -1); rep(i, N)cin >> val[i]; val[N] = 0; Graph G(N), child(N); rep(i, N - 1) { int x, y; cin >> x >> y; x--, y--; G[x].push_back(y); G[y].push_back(x); } par[0] = N; make_tree(0, G, par, child); //自ノードより小さい葉ノードのみ(親含む vector dp_small(N, 0); //自ノードより小さい葉ノードのみ(親なし vector dp_small_p(N, 0); //自ノードより大きい葉ノードのみ(親含む vector dp_large(N, 0); //自ノードより大きい葉ノードのみ(親なし vector dp_large_p(N, 0); LL res = 0ll; std::function dfs = [&](int v) { map l, s; range(u, child[v]) { dfs(u); int x = val[u]; if (x > val[v]) l[x] = max(l[x], dp_small_p[u]); if (x < val[v]) s[x] = max(s[x], dp_large_p[u]); } LL l_sum = 0, s_sum = 0; LL ln = (LL)l.size(); LL sn = (LL)s.size(); range(it, l)l_sum += it.second; range(it, s)s_sum += it.second; dp_large[v] = l_sum + (ln)*(ln - 1) / 2; dp_small[v] = s_sum + (sn)*(sn - 1) / 2; if (l.count(val[par[v]]))l_sum -= l[val[par[v]]], ln--; if (s.count(val[par[v]]))s_sum -= s[val[par[v]]], sn--; if (val[par[v]] > val[v])ln++; if (val[par[v]] < val[v])sn++; if (val[par[v]] != val[v]) { dp_large_p[v] = l_sum + (ln)*(ln - 1) / 2; dp_small_p[v] = s_sum + (sn)*(sn - 1) / 2; } }; dfs(0); rep(i, N) { res = max(res, dp_large[i]); res = max(res, dp_small[i]); if (i) { res = max(res, dp_large_p[i]); res = max(res, dp_small_p[i]); } } cout << res << endl; } return 0; }