传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3289
莫队啦啦啦
Code:
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
#include<cctype>
using namespace std;
const int maxn=50005;
int getint(){
int res=0;char c=getchar();
while(!isdigit(c))c=getchar();
while(isdigit(c))res=res*10+c-'0',c=getchar();
return res;
}
int n,m,sqrtn,bel[maxn],a[maxn];
struct BIT{
int d[maxn];
inline int lowbit(int x){return x&-x;}
int get(int x){
int ans=0;
while(x)ans+=d[x],x-=lowbit(x);
return ans;
}
void updata(int x,int f){
while(x<=n)d[x]+=f,x+=lowbit(x);
}
}T;
struct qes{
int l,r,id;
bool operator<(const qes oth)const{
return bel[l]<bel[oth.l]||(bel[l]==bel[oth.l]&&r<oth.r);
}
}q[maxn];
int anss[maxn],ans;
map<int,int>M;
int main(){
n=getint();sqrtn=sqrt(n);
for(int i=1;i<=n;i++)a[i]=getint(),bel[i]=i/sqrtn,M[a[i]]=1;int tot=0;
for(map<int,int>::iterator it=M.begin();it!=M.end();it++)it->second=++tot;
for(int i=1;i<=n;i++)a[i]=M[a[i]];
m=getint();
for(int i=1;i<=m;i++)q[i].l=getint(),q[i].r=getint(),q[i].id=i;
sort(q+1,q+1+m);
int L=1,R=0;
for(int i=1;i<=m;i++){
while(q[i].l<L){
L--;
ans+=T.get(a[L]-1);
T.updata(a[L],1);
}
while(q[i].l>L){
ans-=T.get(a[L]-1);
T.updata(a[L],-1);
L++;
}
while(q[i].r>R){
R++;
ans+=(R-L)-T.get(a[R]);
T.updata(a[R],1);
}
while(q[i].r<R){
ans-=(R-L+1)-T.get(a[R]);
T.updata(a[R],-1);
R--;
}anss[q[i].id]=ans;
}for(int i=1;i<=m;i++)printf("%d\n",anss[i]);
return 0;
}