调了好久。。。。
转化成三维偏序,cdq处理。
好像比较快?
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 300500
using namespace std;
long long n,m,x,a[maxn],pos[maxn],f1[maxn],f2[maxn],t[maxn],ans=;
struct pnt
{
long long a,b,c,ans;
}p[maxn];
bool cmp1(pnt x,pnt y) {return x.b<y.b;}
bool cmp2(pnt x,pnt y) {return x.b>y.b;}
bool cmp3(pnt x,pnt y) {return x.a<y.a;}
long long lowbit(long long x) {return (x&(-x));}
void add(long long x,long long val)
{
for (long long i=x;i<=n;i+=lowbit(i))
t[i]+=val;
}
long long ask(long long x)
{
long long ret=;
for (long long i=x;i>=;i-=lowbit(i))
ret+=t[i];
return ret;
}
void cdq1(long long left,long long right)
{
long long mid=left+right>>;
sort(p+left,p+mid+,cmp1);sort(p+mid+,p+right+,cmp1);
long long i=left,j=mid+;
while (j<=right)
{
while ((i<=mid) && (p[i].b<p[j].b))
{
add(p[i].c,);
i++;
}
p[j].ans+=ask(n)-ask(p[j].c);
j++;
}
for (long long j=left;j<i;j++) add(p[j].c,-);
}
void cdq2(long long left,long long right)
{
long long mid=left+right>>;
sort(p+left,p+mid+,cmp2);sort(p+mid+,p+right+,cmp2);
long long i=left,j=mid+;
while (j<=right)
{
while ((i<=mid) && (p[i].b>p[j].b))
{
add(p[i].c,);
i++;
}
p[j].ans+=ask(p[j].c-);
j++;
}
for (long long j=left;j<i;j++) add(p[j].c,-);
}
void cdq(long long left,long long right)
{
if (left==right) return;
long long mid=left+right>>;
cdq(left,mid);cdq(mid+,right);
cdq1(left,right);
cdq2(left,right);
}
int main()
{
scanf("%lld%lld",&n,&m);
for (long long i=;i<=n;i++)
{
scanf("%lld",&a[i]);
pos[a[i]]=i;
}
for (long long i=;i<=n;i++)
{
f1[pos[i]]=(pos[i]-)-ask(pos[i]-);
ans+=f1[pos[i]];
f2[pos[i]]=ask(n)-ask(pos[i]);
add(pos[i],);
}
memset(t,,sizeof(t));
for (long long i=;i<=m;i++)
{
scanf("%lld",&x);
p[i].a=i;p[i].b=pos[x];p[i].c=x;
}
cdq(,m);
sort(p+,p+m+,cmp3);
for (long long i=;i<=m;i++)
{
printf("%lld\n",ans);
x=p[i].c;
ans-=(f1[pos[x]]+f2[pos[x]]);
ans+=(p[i].ans);
}
return ;
}