四维偏序模板题:https://blog.csdn.net/baodream/article/details/82778387
四维偏序裸题思路,CDQ套CDQ即a通过flag标记,在CDQ2的时候,b已经是有序的了,所以只用再c归并,d树状数组求和。
代码:
//四维偏序模板题,求ai<aj,bi<bj,ci<cj,di<dj的对数
const int N = 1e6+5;
struct node{
int a,b,c,d;
bool flag;
}a[N],tmp[N],tmp1[N];
int n;
ll ans;
int tree[N]; //tree数组按二进制存,根据n的末尾0的个数存取,树状数组
int lowbit(int x){return x&(-x);}
int Query(int x){ //返回1到x的前缀和
int res=0;
while(x){
res+=tree[x];
x-=lowbit(x);
}
return res;
}
void Add(int x,int v){ //实现a[x]+v;
while(x<=n){ //注意这里是小于等于k,不是n,k是数据范围
tree[x]+=v;
x+=lowbit(x);
}
}
void clearr(int x){
while(x<=n){
if(tree[x]==0)
break;
tree[x]=0;
x+=lowbit(x);
}
}
void CDQ2(int l,int r){
if(l>=r) return;
int mid = l+r>>1;
CDQ2(l,mid);
CDQ2(mid+1,r);
int p=l,q=mid+1,k=l;
//这里的tmp数组已经是对b有序的一个数组,flag用于判断下标,flag=1代表在(l,mid),flag=0代表在(mid+1,r)区间
while(p<=mid&&q<=r){
if(tmp[p].c<tmp[q].c){
if(tmp[p].flag) Add(tmp[p].d,1);
tmp1[k++]=tmp[p++];
}
else{
if(!tmp[q].flag)
ans+=Query(tmp[q].d);
tmp1[k++] = tmp[q++];
}
}
while(p<=mid){
tmp1[k++] = tmp[p++];
}
while(q<=r){
if(!tmp[q].flag)
ans+=Query(tmp[q].d);
tmp1[k++] = tmp[q++];
}
for(int i=l;i<=r;i++) clearr(tmp[i].d),tmp[i] = tmp1[i];
}
void CDQ(int l,int r){
if(l>=r) return;
int mid = l+r>>1;
CDQ(l,mid);
CDQ(mid+1,r);
int p=l,q=mid+1,k=l;
while(p<=mid&&q<=r){
if(a[p].b<a[q].b){
tmp[k++] = a[p++];
tmp[k-1].flag=1;
}
else{
tmp[k++] = a[q++];
tmp[k-1].flag=0;
}
}
while(p<=mid){
tmp[k++] = a[p++];
tmp[k-1].flag = 1;
}
while(q<=r){
tmp[k++] = a[q++];
tmp[k-1].flag=0;
}
for(int i=l;i<=r;i++) a[i] = tmp[i];
CDQ2(l,r);
}
int main()
{
//freopen("partial_order.in","r",stdin);
//freopen("partial_order.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i].b);
for(int i=1;i<=n;i++) scanf("%d",&a[i].c);
for(int i=1;i<=n;i++) scanf("%d",&a[i].d), a[i].a=i;
ans=0;
CDQ(1,n);
printf("%lld\n",ans);
return 0;
}