1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 using namespace std;
7 int n,q;
8 int a[50010]={};//原本的文件
9 int b[50010]={};//离散化媒介
10 int bel[50010]={};//询问块
11 int tr[50010]={};//树状数组
12 int ans[50010]={};
13 struct nod{
14 int x,y;
15 int id;
16 }e[50010];
17 int sz;
18 bool mmp(nod aa,nod bb){
19 if(bel[aa.x]==bel[bb.x]){
20 if(aa.y==bb.y){
21 return aa.x<bb.x;
22 }
23 return aa.y<bb.y;
24 }
25 return bel[aa.x]<bel[bb.x];
26 }
27 inline int lowbit(int x){
28 return x&-x;
29 }
30 inline int sum(int x){
31 int ret = 0;
32 while(x>0){
33 ret+=tr[x];
34 x-=lowbit(x);
35 }
36 return ret;
37 }
38 inline void add(int x,int v){
39 while(x<=50005){
40 tr[x]+=v;
41 x+=lowbit(x);
42 }
43 }
44 void work(){
45 int l=1,r=0;
46 int an=0;
47 for(int i=1;i<=q;i++){
48 while(l>e[i].x){
49 l--;
50 an+=sum(a[l]-1);
51 add(a[l],1);
52 }
53 while(r<e[i].y){
54 r++;
55 an+=sum(50005)-sum(a[r]);
56 add(a[r],1);
57 }
58 while(l<e[i].x){
59 add(a[l],-1);
60 an-=sum(a[l]-1);
61 l++;
62 }
63 while(r>e[i].y){
64 add(a[r],-1);
65 an-=sum(50005)-sum(a[r]);
66 r--;
67 }
68 ans[e[i].id]=an;
69 }
70 for(int i=1;i<=q;i++){
71 printf("%d
",ans[i]);
72 }
73 }
74 int main(){
75 //freopen("wtf.in","r",stdin);
76 scanf("%d",&n);
77 for(int i=1;i<=n;i++){
78 scanf("%d",&a[i]);
79 b[i]=a[i];
80 }
81 sort(b+1,b+n+1);
82 int size=unique(b+1,b+n+1)-b-1;
83 for(int i=1;i<=n;i++){
84 a[i]=lower_bound(b+1,b+size+1,a[i])-b;
85 }
86 scanf("%d",&q);
87 sz=(int)sqrt((double)q);
88 for(int i=1;i<=q;i++){
89 bel[i]=(i-1)/sz+1;
90 }
91 for(int i=1;i<=q;i++){
92 scanf("%d%d",&e[i].x,&e[i].y);
93 e[i].id=i;
94 }
95 sort(e+1,e+1+q,mmp);
96 work();
97 return 0;
98 }