#include #pragma GCC optimize("O3") #pragma GCC target("sse4") using namespace std; #define all(x) begin(x), end(x) signed main() { cin.tie(0)->sync_with_stdio(0); int N, Q; cin >> N; using City = array; vector A(N); for (City& c : A) cin >> c[0]; for (City& c : A) cin >> c[1]; for (int i = 0; i < N; ++i) A[i][2] = i; sort( all(A) ); vector H(N), T(N), I(N+1); for (int i = 0; i < N; ++i) { auto [h, t, idx] = A[i]; H[i] = h; I[idx+1] = i; T[i] = t; // T[i] = (i == 0) ? t : max(t, T[i-1]); } // for (int i = 0; i < N; ++i) { // int t = A[i][1]; // upper_bound( all(H), t ) - begin(H) // } int K = 31 - __builtin_clz(N); vector> next(N, vector(K+1, -1)); vector> dp(N, vector(K+1, -1)); auto get_next = [&] (int i) -> int { int t = T[i]; auto idx = upper_bound(all(H), t) - begin(H); return idx - 1; }; auto dfs = [&] (auto&& dfs, int i, int j) -> pair { if (i < 0) return {-1, -1}; if (next[i][j] != -1) return {next[i][j], dp[i][j]}; if (j == 0) return {next[i][j] = get_next(i), dp[i][j] = T[i]}; auto [inner, ival] = dfs(dfs, i, j-1); std::tie(next[i][j], dp[i][j]) = dfs(dfs, inner, j-1); dp[i][j] = max(dp[i][j], T[i]); return {next[i][j], dp[i][j]}; }; auto solve = [&] (int a, int b) { int ans = 0; bool can = false; for (int i = 1; i <= K; ++i) { if (dfs(dfs, a, 0).first == b) { return ans + 1; } auto [nxt, val] = dfs(dfs, a, i); if (val >= H[b]) { a = dfs(dfs,a,--i).first; ans += (1 << i); can = true; } } if (!can) return -1; return ans; // int ans = 0; // while (8) { // int j = K; // int n = dfs(dfs, a, j); // while (T[n] >= H[b] && j > 0) { // n = dfs(dfs, a, --j); // } // if (n == a) break; // a = n; // ans += 1 << j; // if (j == 0 && T[a] >= H[b]) return ans; // } // if (T[a] < H[b]) return -1; // return ans; }; // vector dbug(N); // for (int i = 0; i < N; ++i) // dbug[i] = get_next(i); cin >> Q; while (Q--) { int a, b; cin >> a >> b; cout << solve(I[a], I[b]) << '\n'; } }