#include using namespace std; template bool chmax(T &a, const T &b){ if (a >= b) return false; a = b; return true; } void input(int &x){ char c; x = 0; while ((c = getchar_unlocked() ^ 48) < 10){ x *= 10; x += c; } } template struct csr { csr (int n_ = 0, int m_ = -1) : n(n_), m(m_) { if (m >= 0){ es.reserve(m); start.reserve(m); } if (m == 0){ build(); } } int add(int idx, E elem){ int eid = start.size(); es.emplace_back(elem); start.emplace_back(idx); if (eid+1 == m) build(); return eid; } void build(){ if (m == -2) return ; m = start.size(); std::vector nes(m); std::vector nstart(n+2,0); for (int i = 0; i < m; i++) nstart[start[i]+2]++; for (int i = 1; i < n; i++) nstart[i+2] += nstart[i+1]; for (int i = 0; i < m; i++) nes[nstart[start[i]+1]++] = es[i]; swap(es,nes); swap(start,nstart); m = -2; } const auto operator[](int idx) const { assert(m == -2); return std::ranges::subrange(es.begin()+start[idx],es.begin()+start[idx+1]); } private: int n, m; std::vector es; std::vector start; }; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; input(n); vector a(n); for (auto &x : a) input(x); csr g(n,(n-1)*2); for (int i = 0; i < n-1; i++){ int u, v; input(u), input(v); u--, v--; g.add(u,v); g.add(v,u); } vector ids(n); iota(ids.begin(),ids.end(),0); sort(ids.begin(),ids.end(),[&](int l, int r){ return a[l] > a[r]; }); vector dmax(n,0); vector from(n,-1); auto dfs_update = [&](auto sfs, int v, int f) -> void { for (int u : g[v]){ if (u == f) continue; dmax[u] = dmax[v]+1; from[u] = v; sfs(sfs,u,v); } }; dfs_update(dfs_update,ids[0],-1); int dmax_v = max_element(dmax.begin(),dmax.end()) - dmax.begin(); vector dmax2(n,0); auto dfs_2 = [&](auto sfs, int v, int f) -> void { for (int u : g[v]){ if (u == f) continue; dmax2[u] = dmax2[v]+1; sfs(sfs,u,v); } }; dfs_2(dfs_2,dmax_v,-1); int diam = *max_element(dmax2.begin(),dmax2.end()); assert(diam <= 1000); auto dfs = [&](auto sfs, int v, int f, int d) -> void { int u = from[v]; if (u == f) return ; assert(u != -1); if (chmax(dmax[u],d+1)){ from[u] = v; dfs_update(dfs_update,u,v); } else { sfs(sfs,u,v,d+1); } }; vector ans(n); for (int l = 0, r = 0; l < n; l = r){ while (r < n && a[ids[r]] == a[ids[l]]){ if (r != 0){ dfs(dfs,ids[r],-1,0); } r++; } for (int i = l; i < r; i++){ ans[ids[i]] = dmax[ids[i]]; } } for (int i = 0; i < n; i++){ if (i != 0) cout << ' '; cout << ans[i]; } cout << '\n'; }