参考博客:https://www.cnblogs.com/JYYHH/p/8777468.html
这题从叶子结点开始 从下往上贪心就是正确的 贪心的思路就是 计算出左右两颗子树的顺序对和逆序对 然后取最小 一直向上合并线段树就行了 因此我们要维护siz(叶子节点的个数)
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
int L[N*30],R[N*30],siz[N*30],tot,cnt,n,rot[N];
typedef long long ll;
ll ans,g[2];
void update(int &rt,int l,int r,int pos){
if(!rt) rt=++cnt;
siz[rt]++;
if(l==r) return;
int mid = l+r>>1;
if(pos<=mid) update(L[rt],l,mid,pos);
else update(R[rt],mid+1,r,pos);
}
int merge(int x,int y){
if(!x||!y) return x+y;
g[0]+=1ll*siz[L[x]]*siz[R[y]];
g[1]+=1ll*siz[R[x]]*siz[L[y]];
L[x]=merge(L[x],L[y]);
R[x]=merge(R[x],R[y]);
siz[x]+=siz[y];
return x;
}
int solve(){
int u;
scanf("%d",&u);
if(u){
update(rot[++tot],1,n,u);
return rot[tot];
}else{
int root=merge(solve(),solve());
ans+=min(g[0],g[1]);
g[0]=g[1]=0;
return root;
}
}
int main(){
scanf("%d",&n);
solve();
printf("%lld\n",ans);
return 0;
}