#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; } vectormxto(N); vectormxh(N); mxto[0] = node[0].to; mxh[0] = node[0].height; for (int i = 1; i < N; i++) { mxto[i] = max(mxto[i - 1], node[i].to); mxh[i] = max(mxh[i - 1], node[i].height); } vector>height(20, vector(N, -1)); vector>to(20, vector(N, -1)); for (int i = 0; i < N; i++) { height[0][i] = node[i].to; } for (int i = 1; i < 20; i++) { for (int j = 0; j < N; j++) { auto it = upper_bound(mxh.begin(), mxh.end(), height[i - 1][j]); if (it != mxh.begin()) { height[i][j] = mxto[it - mxh.begin() - 1]; } height[i][j] = max(height[i][j], height[i - 1][j]); } } 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; } L = it - mxh.begin() - 1; if (height.back()[L] < node[R].height) { cout << -1 << endl; continue; } for (int i = 19; i >= 0; i--) { if (height[i][L] < node[R].height) { ans += i << i; L = upper_bound(mxh.begin(), mxh.end(), height[i][L]) - mxh.begin() - 1; } } cout << ans + 1 << endl; } }