#ifdef LOCAL #include #else #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2") #include #define debug(...) (static_cast(0)) #define postprocess() (static_cast(0)) #endif // #include "atcoder/dsu.hpp" // #include "atcoder/modint.hpp" // using mint = atcoder::modint998244353; // using mint = atcoder::modint1000000007; using namespace std; using ll = long long; using ld = long double; void solve([[maybe_unused]] int test) { int N; cin >> N; vector> _H(N); for (int i = 0; i < N; i++) { cin >> _H[i].first; _H[i].second = i; } sort(_H.begin(), _H.end()); vector index(N); for (int i = 0; i < N; i++) { index[_H[i].second] = i; } vector H(N); for (int i = 0; i < N; i++) { H[i] = _H[i].first; } vector T(N); for (int i = 0; i < N; i++) { cin >> T[index[i]]; } vector uniqueH; for (int i = 0; i < N; i++) { if (i == 0 || H[i] != H[i - 1]) { uniqueH.push_back(H[i]); } } vector next_idx[20]; for (int i = 0; i < 20; i++) { next_idx[i].resize(uniqueH.size()); fill(next_idx[i].begin(), next_idx[i].end(), -1); } for (int i = 0; i < N; i++) { auto itr = upper_bound(uniqueH.begin(), uniqueH.end(), T[i]); if (itr == uniqueH.begin()) continue; itr--; int idx = itr - uniqueH.begin(); int cur = lower_bound(uniqueH.begin(), uniqueH.end(), H[i]) - uniqueH.begin(); next_idx[0][cur] = idx; } for (int i = 0; i + 1 < (int)uniqueH.size(); i++) { next_idx[0][i + 1] = max(next_idx[0][i + 1], next_idx[0][i]); } for (int i = 1; i < 20; i++) { for (int j = 0; j < (int)uniqueH.size(); j++) { if (next_idx[i - 1][j] != -1) { next_idx[i][j] = next_idx[i - 1][next_idx[i - 1][j]]; } } } int Q; cin >> Q; for (int q = 0; q < Q; q++) { int x, y; cin >> x >> y; x--; y--; x = index[x]; y = index[y]; int from = upper_bound(uniqueH.begin(), uniqueH.end(), T[x]) - uniqueH.begin(); from--; if (from == -1) { cout << -1 << endl; continue; } int to = lower_bound(uniqueH.begin(), uniqueH.end(), H[y]) - uniqueH.begin(); int ans = 1; int cur = from; for (int i = 20 - 1; i >= 0; i--) { if (next_idx[i][cur] != -1 && next_idx[i][cur] < to) { cur = next_idx[i][cur]; ans += 1 << i; } } if (cur < to && next_idx[0][cur] != -1) { ans++; cur = next_idx[0][cur]; } cout << (cur >= to ? ans : -1) << endl; } } int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int t = 1; // cin >> t; for (int _t = 1; _t <= t; _t++) solve(_t); postprocess(); }