【BZOJ3295】【CQOI2011】—动态逆序对(cdq分治)

传送门

简单 c d q cdq 分治

离线后变成一个个插入
考虑实际上就是对于 ( t i m e , p o s , v a l ) (time,pos,val)
满足 t i m e i < t i m e j , ( p o s i < p o s j & & v a l i > v a l j ) ( p o s i > p o s j & & v a l i < v a l j ) time_i<time_j,(pos_i<pos_j\&\&val_i>val_j)||(pos_i>pos_j\&\&val_i<val_j)

的点对 ( i , j ) (i,j) 个数

直接 c d q cdq 就完了

#include<bits/stdc++.h>
using namespace std;
#define ll long long
inline int read(){
    char ch=getchar();
    int res=0,f=1;
    while(!isdigit(ch)){if(ch=='-')f=-f;ch=getchar();}
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=getchar();
    return res*f;
}	
const int N=100005;
#define lowbit(x) (x&(-x))
int n,m,tim,tr[N],bel[N];
ll ans[N];
struct ask{
	int x,y,p;
	inline bool operator <(const ask &a)const{
		return p==a.p?x<a.x:p<a.p;
	}
}q[N],q1[N];
inline void update(int p,int k){
	for(;p<=n;p+=lowbit(p))tr[p]+=k;
}
inline int query(int p,int res=0){
	for(;p;p-=lowbit(p))res+=tr[p];return res;
}
void cdq(int l,int r){
	if(l==r)return;
	int mid=(l+r)>>1,cnt=l;
	cdq(l,mid),cdq(mid+1,r);
	int i=l,j=mid+1;
	while(i<=mid||j<=r){
		if(j>r||(i<=mid&&q[i].x<q[j].x))update(q[i].y,1),q1[cnt++]=q[i++];
		else ans[q[j].p]+=query(n)-query(q[j].y),q1[cnt++]=q[j++];
	}
	for(int j=l;j<=mid;j++)update(q[j].y,-1);
	for(int i=l;i<=r;i++)q[i]=q1[i];
	for(int i=r;i>=l;i--){
		if(q[i].p<=mid)update(q[i].y,1);
		else ans[q[i].p]+=query(q[i].y);
	}
	for(int i=l;i<=r;i++)if(q[i].p<=mid)update(q[i].y,-1);
}
int main(){
	tim=n=read(),m=read();
	for(int i=1;i<=n;i++)q[i].x=i,q[i].y=read(),bel[q[i].y]=i;
	for(int i=1;i<=m;i++)q[bel[read()]].p=tim--;
	for(int i=1;i<=n;i++)if(!q[i].p)q[i].p=tim--;
	sort(q+1,q+n+1);
	cdq(1,n);
	for(int i=1;i<=n;i++)ans[i]+=ans[i-1];
	for(int i=n;i>=n-m+1;i--)cout<<ans[i]<<'\n';
}

猜你喜欢

转载自blog.csdn.net/qq_42555009/article/details/88251427