#include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)< pii; typedef vector vi; typedef vector vll; const int NX = 50001, AX = 1001; int N, A[NX]; vi G[NX]; ll memo[NX][2]; unsigned maxi_[NX * 3][AX], ptr = 0, INVALID = 4294967295u; ll rec(int cur, int pre, int preUse){ ll &res = memo[cur][preUse]; if(res != -1)return res; // 葉 if(sz(G[cur]) == 1 && pre != -1)return res = 0; res = 0; if(!preUse){ // curを使わない each(nex, G[cur]) smax(res, rec(nex, cur, 0)); // A[cur]が最小 { auto maxi = maxi_[ptr++]; ll tmp = 0, cnt = 0; each(nex, G[cur])if(nex!=pre && A[cur] < A[nex]) smax(maxi[A[nex]], (unsigned)rec(nex, cur, 1)); rep(i, AX)if(maxi[i] != INVALID)tmp += maxi[i], cnt++; smax(res, tmp + cnt * (cnt - 1) / 2); } // A[cur]が最大 { auto maxi = maxi_[ptr++]; ll tmp = 0, cnt = 0; each(nex, G[cur])if(nex != pre && A[cur] > A[nex]) smax(maxi[A[nex]], (unsigned)rec(nex, cur, 1)); rep(i, AX)if(maxi[i] != INVALID)tmp += maxi[i], cnt++; smax(res, tmp + cnt * (cnt - 1) / 2); } } else{ // A[cur]が最小 if(A[cur] < A[pre]){ auto maxi = maxi_[ptr++]; ll tmp = 0, cnt = 1; each(nex, G[cur])if(A[cur] < A[nex] && A[nex] != A[pre]) smax(maxi[A[nex]], (unsigned)rec(nex, cur, 1)); rep(i, AX)if(maxi[i] != INVALID)tmp += maxi[i], cnt++; smax(res, tmp + cnt * (cnt - 1) / 2); } // A[cur]が最大 if(A[cur] > A[pre]){ auto maxi = maxi_[ptr++]; ll tmp = 0, cnt = 1; each(nex, G[cur])if(A[cur] > A[nex] && A[nex] != A[pre]) smax(maxi[A[nex]], (unsigned)rec(nex, cur, 1)); rep(i, AX)if(maxi[i] != INVALID)tmp += maxi[i], cnt++; smax(res, tmp + cnt * (cnt - 1) / 2); } } return res; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cin >> N; if(N < 3){ cout << 0 << endl; return 0; } rep(i, N)cin >> A[i + 1]; rep(i, N - 1){ int x, y; cin >> x >> y; G[x].push_back(y); G[y].push_back(x); } MEM(memo, -1); MEM(maxi_, -1); ll ans = rec(1, -1, 0); cout << ans << endl; }