1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <bits/stdc++.h> #define MAX_N 400000 #define mid ((s+t)>>1) using namespace std; typedef long long lnt; template <class T> inline void read(T &x) { x = 0; int c = getchar(), f = 1; for (; !isdigit(c); c = getchar()) if (c == 45) f = -1; for (; isdigit(c); c = getchar()) (x *= 10) += f*(c-'0'); } int n, m, r, s[MAX_N+5][2]; int sz, rt[MAX_N+5]; lnt s1, s2, ans; struct node {int ls, rs, c;} tr[MAX_N*20]; int merge(int u, int v) { if (!u) return v; if (!v) return u; s1 += 1LL*tr[tr[u].ls].c*tr[tr[v].rs].c; s2 += 1LL*tr[tr[u].rs].c*tr[tr[v].ls].c; tr[u].ls = merge(tr[u].ls, tr[v].ls); tr[u].rs = merge(tr[u].rs, tr[v].rs); tr[u].c = tr[tr[u].ls].c+tr[tr[u].rs].c; return u; } void modify(int &v, int s, int t, int p) { if (!v) v = ++sz; if (s == t) {tr[v].c++; return;} if (p <= mid) modify(tr[v].ls, s, mid, p); if (p >= mid+1) modify(tr[v].rs, mid+1, t, p); tr[v].c = tr[tr[v].ls].c+tr[tr[v].rs].c; } void build(int &u) { if (!u) u = ++m; int x; read(x); if (!x) build(s[u][0]), build(s[u][1]); else modify(rt[u], 1, n, x); } void DFS(int u) { if (!u) return; DFS(s[u][0]), DFS(s[u][1]), s1 = s2 = 0; if (s[u][0] || s[u][1]) rt[u] = merge(rt[s[u][0]], rt[s[u][1]]), ans += min(s1, s2); } int main() { read(n), build(r), DFS(r); return printf("%lld\n", ans), 0; }
|