传送门
线段树套线段树会TLE+MLE!
树状数组不仅空间小,常数也小(我写的除外)
思考一下求逆序对需要的条件,树套树就过了
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void read(int &x) {
char ch; bool ok;
for(ok=0,ch=getchar(); !isdigit(ch); ch=getchar()) if(ch=='-') ok=1;
for(x=0; isdigit(ch); x=x*10+ch-'0',ch=getchar()); if(ok) x=-x;
}
#define rg register
const int maxn=1e5+10;
int n,m,rt[maxn],ls[maxn*100],rs[maxn*100],id,sum[maxn*100],w[maxn];
long long ans;
struct oo
{
void update(int x){sum[x]=sum[ls[x]]+sum[rs[x]];}
void change(int &k,int l,int r,int v,int val)
{
if(!k)k=++id;
if(l==r){sum[k]+=val;return ;}int mid=(l+r)>>1;
if(v<=mid)change(ls[k],l,mid,v,val);else change(rs[k],mid+1,r,v,val);
update(k);
}
int get(int &k,int l,int r,int a,int b)
{
if(!k)return 0;
if(a<=l&&b>=r)return sum[k];
int ans=0,mid=(l+r)>>1;
if(a<=mid)ans+=get(ls[k],l,mid,a,b);
if(b>mid)ans+=get(rs[k],mid+1,r,a,b);
return ans;
}
}f[maxn];
#define lowbit(i) (i&(-i))
int get(int x,int a,int b){int ans=0;for(rg int i=x;i;i-=lowbit(i))ans+=f[i].get(rt[i],1,n,a,b);return ans;}
void change(int x,int v,int val){for(rg int i=x;i<=n;i+=lowbit(i))f[i].change(rt[i],1,n,v,val);}
int main()
{
// freopen("1.in","r",stdin);
// freopen("my.out","w",stdout);
read(n),read(m);
for(rg int i=1,x;i<=n;i++)read(x),w[x]=i,ans+=get(i,x,n),change(i,x,1);
for(rg int i=1,x;i<=m;i++)
{
printf("%lld
",ans),read(x);
ans-=get(w[x]-1,x+1,n);
ans-=(get(n,1,x-1)-get(w[x]-1,1,x-1));
change(w[x],x,-1);
}
}