#include "iostream" #include "climits" #include "list" #include "queue" #include "stack" #include "set" #include "functional" #include "algorithm" #include "string" #include "map" #include "unordered_map" #include "unordered_set" #include "iomanip" #include "cmath" #include "random" #include "bitset" #include "cstdio" #include "numeric" #include "cassert" #include "ctime" using namespace std; //constexpr long long int MOD = 1000000007; constexpr long long int MOD = 998244353; constexpr double EPS = 1e-8; //int N, M, K, T, H, W, L, R; long long int N, M, K, T, H, W, L, R; struct Node { int height; int to; int idx; bool operator<(const Node& n)const { return height < n.height; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> N; vectornode(N); for (int i = 0; i < N; i++) { cin >> node[i].height; node[i].idx = i; } for (int i = 0; i < N; i++) { cin >> node[i].to; } sort(node.begin(), node.end()); vectorconv(N); for (int i = 0; i < N; i++) { conv[node[i].idx] = i; } vectormxh(N); vectormxmx(N); mxh[0] = node[0].height; mxmx[0] = node[0].to; for (int i = 1; i < N; i++) { mxh[i] = max(mxh[i - 1], node[i].height); mxmx[i] = max(mxmx[i - 1], node[i].to); } vector>to(20, vector(N, -1)); vector>mxto(20, vector(N, -1)); for (int i = 0; i < N; i++) { to[0][i] = upper_bound(mxh.begin(), mxh.end(), node[i].to) - mxh.begin(); to[0][i]--; mxto[0][i] = to[0][i]; if(i)mxto[0][i] = max(mxto[0][i-1], to[0][i]); } for (int i = 1; i < 20; i++) { int mx = -1; for (int j = 0; j < N; j++) { if (mxto[i - 1][j] >= 0) { to[i][j] = upper_bound(mxh.begin(), mxh.end(), mxmx[mxto[i - 1][j]]) - mxh.begin(); to[i][j]--; if (to[i][j] >= 0)to[i][j] = mxto[i - 1][to[i][j]]; } mx = max(mx, to[i][j]); mxto[i][j] = mx; // cout << i << " " << j << " " << mxto[i][j] << endl; } } cin >> K; while (K--) { cin >> L >> R; L--, R--; L = conv[L]; R = conv[R]; int ans = 1; H = node[L].to; if (H >= node[R].height) { cout << 1 << endl; continue; } auto it = upper_bound(mxh.begin(), mxh.end(), H); if (it == mxh.begin()) { cout << -1 << endl; continue; } //if(L==) L = it - mxh.begin() - 1; if (mxto.back()[L] < R) { cout << -1 << endl; continue; } for (int i = 19; i >= 0; i--) { if (mxto[i][L] < R) { L = mxto[i][L]; ans += 1 << i; } } cout << ans + 1 << endl; } }