// Problem: No.2242 Cities and Teleporters // Contest: yukicoder // URL: https://yukicoder.me/problems/no/2242 // Memory Limit: 512 MB // Time Limit: 3000 ms #include #define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); #define dbg(x) cout << #x << " = " << (x) << "\n"; #define popcount(x) __builtin_popcountll((x)) #define all(v) ((v).begin()), ((v).end()) #define pb emplace_back #define x first #define y second using namespace std; typedef long long ll; typedef pair pll; const int inf = 0x3f3f3f3f; const int mod = 1e9 + 7; const int N = 2e5 + 7; int n; int H[N], T[N], pos[N], dp[N][21]; void solve() { cin >> n; vector v; for (int i = 1; i <= n; i++) { cin >> H[i]; v.pb(H[i], i); } for (int i = 1; i <= n; i++) { cin >> T[i]; } sort(all(v)); int ma = 0; for (int i = 0; i < n; i++) { pos[v[i].y] = i; ma = max(T[v[i].y], ma); dp[i][0] = lower_bound(v.begin(), v.end(), make_pair(ma + 1, 0)) - v.begin() - 1; dp[i][0] = max(i, dp[i][0]); } for (int j = 1; j <= 20; j++) { for (int i = 0; i < n; i++) { dp[i][j] = dp[dp[i][j - 1]][j - 1]; } } int Q; cin >> Q; while (Q--) { int x, y; cin >> x >> y; if (T[x] >= H[y]) { cout << "1\n"; } else { int to = lower_bound(all(v), make_pair(T[x] + 1, 0)) - v.begin() - 1; if (to == -1) { cout << "-1\n"; continue; } if (dp[to][20] < pos[y]) { cout << "-1\n"; continue; } int ans = 2; for (int j = 20; j >= 0; j--) { if (dp[to][j] < pos[y]) ans += 1 << j, to = dp[to][j]; } cout << ans << "\n"; } } } int main() { fastio; int t = 1; // cin >> t; while (t--) { solve(); } return 0; }