#include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 998244353; // constexpr int MOD = 1000000007; constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}; constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; int main() { constexpr int B = 18; int n; cin >> n; vector h(n), t(n); REP(i, n) cin >> h[i]; REP(i, n) cin >> t[i]; vector v(n * 2); ranges::copy(h, v.begin()); ranges::copy(t, next(v.begin(), n)); ranges::sort(v); v.erase(unique(ALL(v)), v.end()); REP(i, n) h[i] = distance(v.begin(), ranges::lower_bound(v, h[i])); REP(i, n) t[i] = distance(v.begin(), ranges::lower_bound(v, t[i])); // REP(i, n) cout << h[i] << " \n"[i + 1 == n]; // REP(i, n) cout << t[i] << " \n"[i + 1 == n]; int q; cin >> q; vector a(q), b(q); REP(i, q) cin >> a[i] >> b[i], --a[i], --b[i]; { vector ord(n); iota(ALL(ord), 0); ranges::sort(ord, {}, [&](const int i) -> int { return h[i]; }); vector tmp(n); REP(i, n) tmp[i] = h[ord[i]]; h.swap(tmp); REP(i, n) tmp[i] = t[ord[i]]; t.swap(tmp); REP(i, n) tmp[ord[i]] = i; REP(i, q) a[i] = tmp[a[i]]; REP(i, q) b[i] = tmp[b[i]]; } vector dp(B, vector(n, -1)); REP(i, n) { if (const auto it = ranges::upper_bound(h, t[i]); it != h.begin()) { dp[0][i] = distance(h.begin(), prev(it)); } } REP(bit, B - 1) { vector rmax = dp[bit]; FOR(i, 1, n) chmax(rmax[i], rmax[i - 1]); REP(i, n) { if (dp[bit][i] != -1) chmax(dp[bit + 1][i], rmax[dp[bit][i]]); } } // REP(i, n) cout << dp[0][i] << " \n"[i + 1 == n]; // REP(i, n) cout << dp[1][i] << " \n"[i + 1 == n]; // REP(i, q) cout << a[i] << ' ' << b[i] << '\n'; REP(i, q) { if (h[b[i]] <= t[a[i]]) { cout << 1 << '\n'; continue; } int lb = 0, ub = n; while (ub - lb > 1) { const int mid = midpoint(lb, ub); int town = a[i]; for (int j = mid, bit = 0; j > 0 && town != -1; j /= 2, ++bit) { if (j % 2 == 1) town = dp[bit][town]; } (b[i] <= town ? ub : lb) = mid; } cout << (ub == n ? -1 : ub) << '\n'; } return 0; }