Previous problem Introduction
You are given a sequence . For each , you have to find the number of that satisfied . .
This problem is a classic problem, and I believe Mr.Jia has told you the solution.
It’s clear that we have two different solutions:
- We can use the Fenwick Tree to solve it.
- We can use Divide and Conquer, which is the algorithm for merge sort.
The code for algorithm 1
signed main(){
read(n);
rep(i,1,n) read(a[i]);
rep(i,1,n){
write(bit.ask(a[i])),pc(' ');
bit.add(a[i],1);
}
}The code for algorithm 2
inline bool cmp(int x,int y){return a[x]<a[y];}
void solve(int l,int r){
if(l==r) return;
int mid=(l+r)>>1;
solve(l,mid),solve(mid+1,r);
int j=l,cnt=0;
rep(i,mid+1,r){
while(j<=mid&&a[id[j]]<a[id[i]]) ++cnt,++j;
ans[id[i]]+=cnt;
}
inplace_merge(id+l,id+mid+1,id+r+1,cmp);
}Both two algorithms are important in today’s problem.
The Real Problem
Here, you are given two sequences and . In this problem, you have to find the number of that satisfied and .
What’s the problem? It’s obvious that the old ways fail. One solution is to use complex data structures like trees on trees, but there are many drawbacks, for instance, the high space complexity up to . Is there any way to decrease the space complexity and make the code concise?
This is a 3-d problem. As we know, Divide and Conquer can make a 3-d problem into 2-d problem. So we Just need to solve a 2-d problem in each floor of the Divide Conquer. In detail, we first solve both the left and right, then we use the fenwick tree to maintain the information of the left half, and use these infomation to answer the right half of the sequence.
The Code
inline bool cmp(node a,node b){
if(a.a!=b.a) return a.a<b.a; //j<i
if(a.b!=b.b) return a.b<b.b; //x[j]<x[i]
return a.c<b.c; //y[j]<y[i]
}
inline bool cmp1(node a,node b){
return a.b<b.b;
}
void cdq(int l,int r){
if(l==r) return;
int mid=(l+r)>>1;
cdq(l,mid),cdq(mid+1,r);
int i=l,j=mid+1;
for(;j<=r;++j){
while(i<=mid&&a[i].b<=a[j].b) bit.add(a[i].c,a[i].cnt),++i;
a[j].ans+=bit.ask(a[j].c);
}
rep(j,l,i-1) bit.add(a[j].c,-a[j].cnt);
inplace_merge(a+l,a+mid+1,a+r+1,cmp1);
}