#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll segtree[4*20005];
ll mx[4*20005];
ll arr[20005];
ll brr[20005];
ll ans[20005];
ll k,sum;
struct point
{
ll l,r,id;
} q[20005];
bool cmp(point &a,point &b)
{
ll blocka=a.l/k,blockb=b.l/k;
if(blocka==blockb)
return a.r<b.r;
return blocka<blockb;
}
void build(ll n,ll b,ll e)
{
if(b==e)
{
mx[n]=brr[b];
return ;
}
ll mid=(b+e)/2;
build(2*n,b,mid);
build(2*n+1,mid+1,e);
mx[n]=max(mx[2*n],mx[2*n+1]);
}
void update(ll n,ll b,ll e,ll val,ll on)
{
if(b==e)
{
if(on==1){
segtree[n]++;
}
else{
segtree[n]--;
}
return ;
}
ll mid=(b+e)/2;
ll left=2*n;
ll right=2*n+1;
if(mx[left]<val&&mx[right]>=val)
update(right,mid+1,e,val,on);
else
update(left,b,mid,val,on);
segtree[n]=segtree[left]+segtree[right];
}
ll query(ll n,ll b,ll e,ll val)
{
if(e==b){ return 0; }
ll mid=(b+e)/2;
ll left=2*n;
ll right=2*n+1;
if(mx[left]>=val){
return query(left,b,mid,val);
}
else{
return segtree[left]+query(right,mid+1,e,val);
}
}
ll query1(ll n,ll b,ll e,ll val)
{
if(e==b){ return 0; }
ll mid=(b+e)/2;
ll left=2*n;
ll right=2*n+1;
if(mx[left]>=val){
return segtree[right]+query1(left,b,mid,val);
}
else{
return query1(right,mid+1,e,val);
}
}
void leftadd(ll pos,ll len)
{
sum+=query(1,1,len,arr[pos]);
update(1,1,len,arr[pos],1);
}
void rightadd(ll pos,ll len)
{
sum+=query1(1,1,len,arr[pos]);
update(1,1,len,arr[pos],1);
}
void leftrmv(ll pos,ll len)
{
sum-=query(1,1,len,arr[pos]);
update(1,1,len,arr[pos],0);
}
void rightrmv(ll pos,ll len)
{
sum-=query1(1,1,len,arr[pos]);
update(1,1,len,arr[pos],0);
}
int main()
{
ll i,j,n,m,t;
set<ll>s;
scanf("%lld",&n);
k=sqrt(n);
for(i=1; i<=n; i++)
{
scanf("%lld",&arr[i]);
s.insert(arr[i]);
}
ll len=s.size();
set< ll >::iterator it=s.begin();
for(i=1; i<=len; i++)
{
brr[i]=*it;
it++;
}
build(1,1,len);
scanf("%lld",&t);
for(i=1; i<=t; i++)
{
scanf("%lld%lld",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+1,q+t+1,cmp);
ll l=1,r=0;
for(i=1; i<=t; i++)
{
while(l>q[i].l){ leftadd(--l,len); }
while(l<q[i].l){ leftrmv(l++,len); }
while(r>q[i].r){ rightrmv(r--,len); }
while(r<q[i].r){ rightadd(++r,len); }
ans[q[i].id]=sum;
}
for(i=1; i<=t; i++)
{
printf("%lld\n",ans[i]);
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCiNkZWZpbmUgbGwgbG9uZyBsb25nCmxsIHNlZ3RyZWVbNCoyMDAwNV07CmxsIG14WzQqMjAwMDVdOwpsbCBhcnJbMjAwMDVdOwpsbCBicnJbMjAwMDVdOwpsbCBhbnNbMjAwMDVdOwpsbCBrLHN1bTsKc3RydWN0IHBvaW50CnsKICAgIGxsIGwscixpZDsKfSBxWzIwMDA1XTsKCmJvb2wgY21wKHBvaW50ICZhLHBvaW50ICZiKQp7CiAgICBsbCBibG9ja2E9YS5sL2ssYmxvY2tiPWIubC9rOwogICAgaWYoYmxvY2thPT1ibG9ja2IpCiAgICAgICAgcmV0dXJuIGEucjxiLnI7CiAgICByZXR1cm4gYmxvY2thPGJsb2NrYjsKfQoKdm9pZCBidWlsZChsbCBuLGxsIGIsbGwgZSkKewogICAgaWYoYj09ZSkKICAgIHsKICAgICAgICBteFtuXT1icnJbYl07CiAgICAgICAgcmV0dXJuIDsKICAgIH0KICAgIGxsIG1pZD0oYitlKS8yOwogICAgYnVpbGQoMipuLGIsbWlkKTsKICAgIGJ1aWxkKDIqbisxLG1pZCsxLGUpOwoKICAgIG14W25dPW1heChteFsyKm5dLG14WzIqbis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