题目
一个树中逆序对的个数等于 左子树逆序对个数+右子树逆序对个数+左子树>右子树的对数。可以递归。关键就是怎么每次都处理 左子树>右子树的对树这一部分。
假如左子树所有出现的权值可以在一颗权值线段树上体现出来,右子树的所有出现的权值可以在另一颗权值线段树上体现出来。那么这一部分就是要求treeA 比treeB大的对数也可以递归得到。记两颗权值线段树分别是treeA,treeB;
分为三部分 treeA左子树比treeB左子树大的部分 treeA右子树比treeB右子树大的部分
treeA的右子树 treeB的左子树(当然必须是同构同区间的节点。。) 第三部可以直接求出 前两部递归得到。
前面说了是假如,总不能我们每次 怎么每次都处理 左子树>右子树的对树这一部分。这个时候时都重新建立两颗权值线段树。当然不现实。我们可以把这两颗权值线段树合并就是他父亲对应的权值线段树啊。 合并的时候统计答案。。开ans ans1 ans2全局变量。
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=4e5+5;
struct tree{int l,r,sum;}t[N*50];
int root[N],sz;
int ch[N][2],rt,tot,a[N];
void build(int &p){
p=++tot;scanf("%d",&a[p]);
if(a[p]) return;
build(ch[p][0]),build(ch[p][1]);
}
void update(int &x,int l,int r,int wh){
x=++sz;
if(l==r){t[x].sum=1;return;}
int mid=(l+r)>>1;
if(wh<=mid) update(t[x].l,l,mid,wh);
else update(t[x].r,mid+1,r,wh);
t[x].sum=t[t[x].l].sum+t[t[x].r].sum;
}
ll ans,ans1,ans2;
int combine(int x,int y){
if(!x||!y) return x+y;
ans1+=(ll)t[t[x].r].sum*t[t[y].l].sum;
ans2+=(ll)t[t[x].l].sum*t[t[y].r].sum;
t[x].sum+=t[y].sum;
t[x].l=combine(t[x].l,t[y].l);
t[x].r=combine(t[x].r,t[y].r);
return x;
}
void query(int x){
if(a[x]) return;
query(ch[x][0]),query(ch[x][1]);
ans1=ans2=0;
root[x]=combine(root[ch[x][0]],root[ch[x][1]]);
ans+=min(ans1,ans2);
}
int main(){
int n;scanf("%d",&n);
build(rt);
for(int i=1;i<=tot;++i)
if(a[i]) update(root[i],1,n,a[i]);//建立权值线段树
query(rt);
printf("%lld\n",ans);
}