#include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; template istream& operator >> (istream& is, vector& vec){for(T& val: vec) is >> val; return is;} template istream& operator , (istream& is, T& val){ return is >> val;} template ostream& operator << (ostream& os, const vector& vec){for(int i=0; i ostream& operator , (ostream& os, const T& val){ return os << " " << val;} template ostream& operator >> (ostream& os, const T& val){ return os << " " << val;} bool is_kadomatsu(int a, int b, int c){ return a!=c && ((ac) || (a>b&&b> n; vector a(n); cin >> a; vector> G(n); for(int i=0; i> u,v; u--; v--; G[u].push_back(v); G[v].push_back(u); } vector> par(n, vector(20)); vector> kad(n, vector(20)); vector dep(n, -1); function dfs = [&](int pos, int last){ dep[pos] = dep[last]+1; par[pos][0] = last; if(is_kadomatsu(a[pos], a[last], a[par[last][0]])){ kad[pos][0] = 1; }else{ kad[pos][0] = 0; } for(int next : G[pos]){ if(next == last) continue; dfs(next, pos); } }; dfs(0,0); for(int k=1; k<20; k++){ for(int i=0; i>= 1; } return pos; }; auto lca = [&](int u, int v){ if(dep[u] < dep[v]) swap(u,v); u = k_anc(u, dep[u]-dep[v]); if(u==v) return u; for(int k=19; k>=0; k--){ if(par[u][k] != par[v][k]){ u = par[u][k]; v = par[v][k]; } } return par[u][0]; }; auto kadomatsu_line = [&](int u, int p) -> bool{ int d = dep[u] - dep[p] - 2; if(d<0) return true; d++; int ret = kad[u][0]; int b = 0; while(d>0){ if(d&1){ ret &= kad[u][b]; u = par[u][b]; } b++; d>>=1; } return ret; }; int q; cin >> q; while(q--){ int u,v; cin >> u,v; u--; v--; if(dep[u] < dep[v]) swap(u,v); int p = lca(u,v); if(p==v){ int pu = k_anc(u, dep[u]-dep[p]-1); int qu = par[u][0]; bool ok = ( is_kadomatsu(a[pu],a[p],a[u]) && is_kadomatsu(a[p],a[u],a[qu]) && kadomatsu_line(u, p) ); cout << (ok?"YES":"NO") << endl; }else{ int pu = k_anc(u, dep[u]-dep[p]-1); int pv = k_anc(v, dep[v]-dep[p]-1); int qu = par[u][0]; int qv = par[v][0]; bool ok = ( is_kadomatsu(a[pu], a[p], a[pv]) && is_kadomatsu(a[qu], a[u], a[v]) && is_kadomatsu(a[u], a[v], a[qv]) && kadomatsu_line(u,p) && kadomatsu_line(v,p) ); cout << (ok?"YES":"NO") << endl; } } return 0; }