#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; template struct Compress { vector xs; Compress() = default; Compress(const vector &vs) { add(vs); } Compress(const initializer_list> &vs) { for (auto &p : vs) add(p); } void add(const vector &vs) { copy(begin(vs), end(vs), back_inserter(xs)); } void add(const T &x) { xs.emplace_back(x); } void build() { sort(begin(xs), end(xs)); xs.erase(unique(begin(xs), end(xs)), end(xs)); } vector get(const vector &vs) const { vector ret; transform(begin(vs), end(vs), back_inserter(ret), [&](const T &x) { return lower_bound(begin(xs), end(xs), x) - begin(xs); }); return ret; } int get(const T &x) const { return lower_bound(begin(xs), end(xs), x) - begin(xs); } size_t size() const { return xs.size(); } const T &operator[](int k) const { return xs[k]; } }; struct Doubling { const int LOG; vector< vector< int > > table; Doubling(int sz, int64_t lim_t) : LOG(64 - __builtin_clzll(lim_t)) { table.assign(LOG, vector< int >(sz, -1)); } void set_next(int k, int x) { table[0][k] = x; } void build() { for(int k = 0; k + 1 < LOG; k++) { for(int i = 0; i < table[k].size(); i++) { if(table[k][i] == -1) table[k + 1][i] = -1; else table[k + 1][i] = table[k][table[k][i]]; } } } int query(int k, int64_t t) { for(int i = LOG - 1; i >= 0; i--) { if((t >> i) & 1) k = table[i][k]; if (k == -1){ return -1; } } return k; } }; ll answer(Doubling &d,ll Tfrom,ll Tto,ll l,ll r){ if (l+1 == r){ return r; } ll center = (l+r)/2; if (d.query(Tfrom,center) >= Tto){ return answer(d,Tfrom,Tto,l,center); }else{ return answer(d,Tfrom,Tto,center,r); } } int main() { // 整数の入力 ll N; cin >> N; Compress C; vector H(N); vector T(N); for(int i = 0;i < N;i++){ cin >> H[i]; C.add(H[i]); } for(int i = 0;i < N;i++){ cin >> T[i]; C.add(T[i]); } C.build(); vector maximumT(C.size(),-1); for(int i = 0;i < N;i++){ maximumT[C.get(H[i])] = max(maximumT[C.get(H[i])],(ll)C.get(T[i])); } for(ll i = 1;i < C.size();i++){ maximumT[i] = max(max(maximumT[i],maximumT[i-1]),i); } Doubling d(C.size(),C.size()); for(int i = 0;i < C.size();i++){ d.set_next(i,maximumT[i]); } ll Q; cin >> Q; for(int i = 0;i < Q;i++){ ll a,b; cin >> a >> b; a--;b--; ll t = answer(d,C.get(T[a]),C.get(H[b]),-1,N); if (t == N){ cout << -1 << endl; }else{ cout << t + 1 << endl; } } return 0; }