#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
const int N = 1<<20;
const int TREE_SIZE = N<<2;
int tests,current_case;
int n,a[N],q;
vector < pair < int, int > > v[N];
int tree[TREE_SIZE];
int ans[N];
void message(int current_case) {
//cerr<<"Case "<<current_case<<" solved!"<<endl;
fprintf(stderr, "Case %d solved!\n", current_case);
}
void update_tree(int a, int b, int pos, int node, int value) {
if(a>b || a>pos || b<pos) return;
if(a==b) {
tree[node]=value;
return;
}
update_tree(a,(a+b)>>1,pos,node<<1,value);
update_tree(((a+b)>>1)+1,b,pos,(node<<1)|1,value);
tree[node]=min(tree[node<<1],tree[(node<<1)|1]);
}
int query_tree(int a, int b, int node, int value) {
if(a==b) return a;
if(tree[node<<1]<value) return query_tree(a,(a+b)>>1,node<<1,value);
else return query_tree(((a+b)>>1)+1,b,(node<<1)|1,value);
}
int main() {
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
int i,j,x,y;
tests=1;
//scanf("%d", &tests);
//cin>>tests;
for(current_case=1;current_case<=tests;current_case++) {
scanf("%d", &n);
for(i=1;i<=n;i++) {
scanf("%d", &a[i]);
++a[i];
}
scanf("%d", &q);
for(i=1;i<=q;i++) {
scanf("%d %d", &x, &y);
v[y].push_back(make_pair(x,i));
}
for(i=1;i<=n;i++) {
update_tree(1,1000001,a[i],1,i);
for(j=0;j<(int)(v[i].size());j++) ans[v[i][j].second]=query_tree(1,1000001,1,v[i][j].first);
}
for(i=1;i<=q;i++) {
printf("%d\n", ans[i]-1);
}
MESSAGE:
message(current_case);
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgZW5kbCAnXG4nCgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IE4gPSAxPDwyMDsKY29uc3QgaW50IFRSRUVfU0laRSA9IE48PDI7CgppbnQgdGVzdHMsY3VycmVudF9jYXNlOwppbnQgbixhW05dLHE7CnZlY3RvciA8IHBhaXIgPCBpbnQsIGludCA+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HM9MTsKICAgIC8vc2NhbmYoIiVkIiwgJnRlc3RzKTsKICAgIC8vY2luPj50ZXN0czsKICAgIGZvcihjdXJyZW50X2Nhc2U9MTtjdXJyZW50X2Nhc2U8PXRlc3RzO2N1cnJlbnRfY2FzZSsrKSB7CiAgICAgICAgc2NhbmYoIiVkIiwgJm4pOwogICAgICAgIGZvcihpPTE7aTw9bjtpKyspIHsKICAgICAgICAgICAgc2NhbmYoIiVkIiwgJmFbaV0pOwogICAgICAgICAgICArK2FbaV07CiAgICAgICAgfQogICAgICAgIHNjYW5mKCIlZCIsICZxKTsKICAgICAgICBmb3IoaT0xO2k8PXE7aSsrKSB7CiAgICAgICAgICAgIHNjYW5mKCIlZCAlZCIsICZ4LCAmeSk7CiAgICAgICAgICAgIHZbeV0ucHVzaF9iYWNrKG1ha2VfcGFpcih4LGkpKTsKICAgICAgICB9CiAgICAgICAgZm9yKGk9MTtpPD1uO2krKykgewogICAgICAgICAgICB1cGRhdGVfdHJlZSgxLDEwMDAwMDEsYVtpXSwxLGkpOwogICAgICAgICAgICBmb3Ioaj0wO2o8KGludCkodltpXS5zaXplKCkpO2orKykgYW5zW3ZbaV1bal0uc2Vjb25kXT1xdWVyeV90cmVlKDEsMTAwMDAwMSwxLHZbaV1bal0uZmlyc3QpOyAKICAgICAgICB9CiAgICAgICAgZm9yKGk9MTtpPD1xO2krKykgewogICAgICAgICAgICBwcmludGYoIiVkXG4iLCBhbnNbaV0tMSk7CiAgICAgICAgfQoKICAgICAgICBNRVNTQUdFOgogICAgICAgIG1lc3NhZ2UoY3VycmVudF9jYXNlKTsKICAgIH0KCiAgICByZXR1cm4gMDsKfQ==