可以看错把数字倒着插入,然后做CDQ分治
这题的答案统计十分的权(应该是我太cai了),具体看注释
Code
#include <cstdio> #include <algorithm> #define lowbit(x) ((x)&(-x)) #define N 150010 #define ll long long using namespace std; struct info{ int t,x,y; info(){} info(int a,int b,int c):t(a),x(b),y(c){} friend bool operator <(info a,info b){return (a.x==b.x)?a.y<b.y:a.x<b.x;} }A[N],tmp[N]; int n,mm,pos[N]; ll Ans[N]; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } namespace bit{ int T[N]; inline void add(int x,int v){for(;x<=n;x+=lowbit(x))T[x]+=v;} inline int sum(int x){int r=0;for(;x;x-=lowbit(x))r+=T[x];return r;} inline void clear(int x){for(;x<=n&&T[x];x+=lowbit(x))T[x]=0;} } void solve(int l,int r){ if(l==r) return; int m=(l+r)>>1; solve(l,m),solve(m+1,r); for(int p=l,q=m+1,cnt=l;p<=m||q<=r;) if(q>r||p<=m&&A[p]<A[q]) bit::add(A[p].y,1),tmp[cnt++]=A[p++]; else Ans[A[q].t]+=bit::sum(n)-bit::sum(A[q].y),tmp[cnt++]=A[q++]; for(int i=l;i<=m;++i) bit::clear(A[i].y); for(int i=l;i<=r;++i) A[i]=tmp[i]; //Ans{i]算的是单个贡献,所以不仅要算前面比它大的,还要算后面比它小的 for(int i=r;i>=l;--i) if(A[i].t<=m) bit::add(A[i].y,1); else Ans[A[i].t]+=bit::sum(A[i].y); for(int i=l;i<=r;++i) bit::clear(A[i].y); } bool cmpt(info a,info b){return a.t<b.t;} int main(){ n=read(),mm=read(); for(int i=1,x;i<=n;++i) pos[x=read()]=i,A[i]=info(0,i,x); int tim=n; for(int i=1,x;i<=mm;++i) A[pos[read()]].t=tim--; for(int i=1;i<=n;++i) if(!A[i].t) A[i].t=tim--; sort(A+1,A+n+1,cmpt); solve(1,n); //此时算出的Ans[i]是对于单个数的贡献,而答案要求此时所有的逆序对,所以应该做一个前缀和 for(int i=1;i<=n;++i) Ans[i]+=Ans[i-1]; for(int i=n;i>=n-mm+1;--i) printf("%lld ",Ans[i]); return 0; }