【解析】
贪心,使一个非叶子结点的两棵子树前序遍历逆序对最少,得出的便是最优解。
证明:
因为交换一个非叶子结点的两棵子树,对该子树内叶子结点与子树外结点组成的逆序对个数无影响,所以局部最优解就是最优解。
将二叉树上的每个结点的子树情况用一棵权值线段树表示,每次合并即可。
【代码】
#include<cstdio>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
void read(int &x) {
char c = getchar(); x = 0;
while (!isdigit(c)) c = getchar();
while (isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
}
const int N = 4e5 + 10;
const int M = 4e6 + 10;
int n;
struct node_ { // 二叉树结点
int w, lc, rc;
} a[N];
int root_, cnt_; // 二叉树相关
void build(int &o) {
o = ++cnt_;
read(a[o].w);
if (a[o].w) return;
build(a[o].lc);
build(a[o].rc);
}
struct node { // 线段树结点
int size, lc, rc;
} s[M];
int root[N], cnt;
LL cnt1, cnt2, ans;
inline void push_up(int o) {
s[o].size = s[s[o].lc].size + s[s[o].rc].size;
}
void ins(int &o, int l, int r, int x) {
if (!o) o = ++cnt;
s[o].size++;
if (l == r) return;
int mid = (l + r) >> 1;
if (x <= mid) ins(s[o].lc, l, mid, x);
else ins(s[o].rc, mid + 1, r, x);
}
int merge(int x, int y) {
if (!x || !y) return x | y;
cnt1 += (LL) s[s[x].rc].size * s[s[y].lc].size;
cnt2 += (LL) s[s[x].lc].size * s[s[y].rc].size;
s[x].lc = merge(s[x].lc, s[y].lc);
s[x].rc = merge(s[x].rc, s[y].rc);
push_up(x);
return x;
}
void solve(int o) {
if (!o) return;
int lc = a[o].lc, rc = a[o].rc;
solve(lc), solve(rc);
if (!a[o].w) {
cnt1 = cnt2 = 0;
root[o] = merge(root[lc], root[rc]);
ans += min(cnt1, cnt2);
}
}
int main() {
read(n);
build(root_);
for (int i = 1; i <= cnt_; i++) if (a[i].w) ins(root[i], 1, n, a[i].w);
solve(root_);
cout << ans;
return 0;
}