#include #include #include #include #include #include #include #include #include #include using namespace std; typedef unsigned int uint; typedef long long LL; typedef vector VI; typedef vector VL; typedef vector VVI; typedef vector VVVI; typedef vector VVL; typedef pair PII; typedef pair PLL; typedef vector VPII; typedef vector VVPII; typedef unordered_map MLL; typedef long double LD; #define FOR(k,a,b) for(int k(a); k < (b); ++k) #define REP(k,a) for(int k=0; k < (a); ++k) #define ABS(a) ((a)>0?(a):-(a)) struct SEGMENT_TREE { int N; vector P; vector data; SEGMENT_TREE(const vector& _data, const vector& _P) { N = _data.size(); P = _P; data.clear(); data.resize(2 * N); REP(i, N) { data[N + i] = _data[i]; } for (int i = N - 1;i > 0;--i) { data[i] = (P[data[2 * i]] > P[data[2 * i + 1]] ? data[2 * i] : data[2 * i + 1]); } } int query(int l, int r) { int res = -1; for (l += N, r += N; l < r;l /= 2, r /= 2) { if (l & 1) { if (res == -1 || P[res] < P[data[l]]) res = data[l]; l++; } if (r & 1) { if (res == -1 || P[res] < P[data[r - 1]]) res = data[r - 1]; r--; } } return res; } }; int main(int argc, char** argv) { #ifdef HOME freopen("in.txt", "rb", stdin); freopen("out.txt", "wb", stdout); #endif int T, N, u, v; scanf("%d", &T); while (T--) { scanf("%d", &N); vector P(N), parent(N, -1), childstart(N, -1), childend(N, -1), Q, Z(N); vector used(N, false); Q.reserve(N); Q.push_back(0); used[0] = 1; vector > edges(N); REP(i, N) { scanf("%d", &P[i]); } REP(i, N - 1) { scanf("%d %d", &u, &v); edges[u - 1].push_back(v - 1); edges[v - 1].push_back(u - 1); } REP(i, N) { Z[Q[i]] = i; int act = Q[i]; childstart[act] = Q.size(); REP(j, edges[act].size()) { if (!used[edges[act][j]]) { used[edges[act][j]] = 1; Q.push_back(edges[act][j]); parent[edges[act][j]] = i; } } childend[act] = Q.size(); } SEGMENT_TREE st(Q, P); REP(i, N) { int ar = -1, tar; //0-> parent ar = st.query(0, parent[i]); //parent -> actual node tar = st.query(parent[i] + 1, Z[i]); if (tar != -1 && (ar == -1 || P[tar] > P[ar])) ar = tar; //actual node -> child start tar = st.query(Z[i] + 1, childstart[i]); if (tar != -1 && (ar == -1 || P[tar] > P[ar])) ar = tar; //child end -> end tar = st.query(childend[i], N); if (tar != -1 && (ar == -1 || P[tar] > P[ar])) ar = tar; printf("%d ", ar + 1); } printf("\n"); } return 0; }