C++#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=1e18+10;
ll n,m;
ll res[1000009];
struct node{
ll vl,id;
};
node a[1000009];
struct NODE{
ll k,b,id;
};
NODE h[1000009];
bool flag[1000009];
bool cmp(const node&x,const node&y){
return x.vl<y.vl||(x.vl==y.vl&&x.id<y.id);
}
bool cmp_1(const NODE&x,const NODE&y){
return x.k>y.k;
}
struct seg{
ll l,r,maxn,minn,id,tag,minx;
};
seg tr[4000009];
void build(ll rt,ll l,ll r){
if(l==r){
tr[rt]=(seg){l,r,a[l].vl,a[l].vl,a[l].id,0,a[l].id};
return;
}
ll mid=(l+r)/2;
build(rt*2,l,mid);
build(rt*2+1,mid+1,r);
tr[rt]=(seg){l,r,max(tr[rt*2].maxn,tr[rt*2+1].maxn),min(tr[rt*2].minn,tr[rt*2+1].minn),0,0,min(tr[rt*2].minx,tr[rt*2+1].minx)};
}
void pushdown(ll rt){
ll d=tr[rt].tag;
if(d==0)
return;
tr[rt].tag=0;
tr[rt*2].maxn+=d;
tr[rt*2].minn+=d;
tr[rt*2].tag+=d;
tr[rt*2+1].maxn+=d;
tr[rt*2+1].minn+=d;
tr[rt*2+1].tag+=d;
}
void update(ll rt,ll l,ll r,ll d){
if(tr[rt].l>=l&&tr[rt].r<=r){
tr[rt].maxn+=d;
tr[rt].minn+=d;
tr[rt].tag+=d;
return;
}
if(tr[rt].l>r||tr[rt].r<l)
return;
pushdown(rt);
update(rt*2,l,r,d);
update(rt*2+1,l,r,d);
tr[rt].maxn=max(tr[rt*2].maxn,tr[rt*2+1].maxn);
tr[rt].minn=min(tr[rt*2].minn,tr[rt*2+1].minn);
}
ll query_1(ll rt,ll x){
if(x==n+1)
return INF;
if(x==0)
return -INF;
if(tr[rt].l==x&&tr[rt].r==x)
return tr[rt].maxn;
pushdown(rt);
if(tr[rt*2].r>=x)
return query_1(rt*2,x);
else
return query_1(rt*2+1,x);
}
ll query_2(ll rt,ll l,ll r){
if(tr[rt].l>=l&&tr[rt].r<=r)
return tr[rt].minx;
if(tr[rt].l>r||tr[rt].r<l)
return INF;
return min(query_2(rt*2,l,r),query_2(rt*2+1,l,r));
}
ll query(ll rt,ll x){
if(tr[rt].maxn<=x)
return tr[rt].r;
if(tr[rt].minn>x)
return 0;
pushdown(rt);
if(tr[rt*2+1].minn>x)
return query(rt*2,x);
else
return query(rt*2+1,x);
}
ll query_3(ll rt,ll x){
if(tr[rt].minn>=x)
return tr[rt].l;
if(tr[rt].maxn<x)
return n+1;
pushdown(rt);
if(tr[rt*2].maxn>=x)
return query_3(rt*2,x);
else
return query_3(rt*2+1,x);
}
int main(){
// freopen("bean.in","r",stdin);
// freopen("bean.out","w",stdout);
cin>>n;
for(ll i=1;i<=n;i++){
cin>>a[i].vl;
a[i].id=i;
}
cin>>m;
for(ll i=1;i<=m;i++){
cin>>h[i].k>>h[i].b;
h[i].id=i;
}
sort(a+1,a+1+n,cmp);
build(1,1,n);
sort(h+1,h+1+m,cmp_1);
for(ll i=1;i<=m;i++){
ll nw=h[i].b;
ll l=query(1,nw),r=query_3(1,nw);
if(query_1(1,l)==nw){
res[h[i].id]=query_2(1,r,l);
continue;
}
ll res1=abs(query_1(1,l)-nw),res2=abs(query_1(1,r)-nw);
ll g=query_1(1,l),p=query_1(1,r);
ll ans=0;
if(r==n+1||(res1<res2&&l!=0)){
ans=query_2(1,query_3(1,g),query(1,g));
res[h[i].id]=ans;
update(1,1,l,res1);
update(1,r,n,-res1);
}else if(l==0||res1>res2){
ans=query_2(1,query_3(1,p),query(1,p));
res[h[i].id]=ans;
update(1,1,l,res2);
update(1,r,n,-res2);
}else if(res1==res2){
ans=query_2(1,query_3(1,g),query(1,p));
res[h[i].id]=ans;
update(1,1,l,res1);
update(1,r,n,-res1);
}
}
for(ll i=1;i<=m;i++)
cout<<res[i]<<"\n";
return 0;
}