#include #include #include using namespace std; using Graph = vector>; struct LowestCommonAncestor { const Graph &g; int root, h; vector> par; // par[k][v] := 2^k-th parent of v vector dep; LowestCommonAncestor(const Graph &g, int r = 0) : \ g(g), root(r), dep(g.size()) { } void build() { int V = g.size(); h = 1; while ((1 << h) < V) ++h; // 32 - __builtin_clz(V) par.assign(h, vector(V, -1)); dfs(root, -1, 0); for (int k = 0; k + 1 < h; ++k) for (int v = 0; v < V; ++v) { if (par[k][v] != -1) par[k + 1][v] = par[k][par[k][v]]; } } void dfs(int u, int p, int d) { par[0][u] = p; dep[u] = d; for (auto v: g[u]) if (v != p) dfs(v, u, d + 1); } int get(int u, int v) { if (dep[u] > dep[v]) swap(u, v); for (int k = 0; k < h; ++k) { if ((dep[v] - dep[u]) >> k & 1) v = par[k][v]; } if (u == v) return u; for (int k = h - 1; k >= 0; --k) { if (par[k][u] != par[k][v]) u = par[k][u], v = par[k][v]; } return par[0][u]; } int ancestor(int u, int k) { for (int i = h - 1; i >= 0; i--) if (k >> i & 1) u = par[i][u]; return u; } int dist(int u, int v) { return dep[u] + dep[v] - dep[get(u, v)] * 2; } }; int main() { int n; cin >> n; vector a(n); for (auto &ai: a) cin >> ai; Graph g(n); for (int i = 0; i < n - 1; ++i) { int x, y; cin >> x >> y; x--, y--; g[x].emplace_back(y); g[y].emplace_back(x); } LowestCommonAncestor lca(g); lca.build(); auto &par = lca.par; auto &dep = lca.dep; auto is_kado = [](int x, int y, int z) { if (x == y || y == z || z == x) return false; return (x < y && y > z) || (x > y && y < z); }; auto check = [&](int v) { if (dep[v] < 2) return false; return is_kado(a[v], a[par[0][v]], a[par[1][v]]); }; int h = par.size(); vector> dp(h, vector(n)); for (int v = 0; v < n; v++) dp[0][v] = check(v); for (int k = 0; k + 1 < h; ++k) for (int v = 0; v < n; ++v) { if (~par[k][v]) dp[k + 1][v] = dp[k][v] && dp[k][par[k][v]]; } auto query = [&](int v, int p) { int d = dep[v] - dep[p] - 1, k = 0, flg = true; while (d > 0) { if (d & 1) flg &= dp[k][v], v = par[k][v]; k++, d >>= 1; } return flg; }; int Q; cin >> Q; while (Q--) { int u, v; cin >> u >> v; u--, v--; int p = lca.get(u, v); bool ok = true; if (par[0][u] == v || par[0][v] == u) { ok = false; } else if (u != p && v != p) { int pu = lca.ancestor(u, dep[u] - dep[p] - 1); int pv = lca.ancestor(v, dep[v] - dep[p] - 1); ok &= is_kado(a[pu], a[p], a[pv]); ok &= is_kado(a[par[0][u]], a[u], a[v]); ok &= is_kado(a[par[0][v]], a[v], a[u]); ok &= query(u, p); ok &= query(v, p); } else { if (p == v) swap(u, v); // u == p int q = lca.ancestor(v, dep[v] - dep[u] - 1); ok &= is_kado(a[q], a[u], a[v]); ok &= is_kado(a[par[0][v]], a[v], a[u]); ok &= query(v, u); } cout << (ok ? "YES" : "NO") << endl; } return 0; }