rt,wa on #5
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
struct Node {
int v, fa;
vector<int> s;
} a[MAXN];
struct Node1 {
int cnt0, cnt1, fa;
} bcj[MAXN];
int fa(int x) {
if (bcj[x].fa == x) return x;
return bcj[x].fa = fa(bcj[x].fa);
}
void shit(int u, int v) {
u = fa(u), v = fa(v);
bcj[v].cnt0 += bcj[u].cnt0;
bcj[v].cnt1 += bcj[u].cnt1;
bcj[u].cnt0 = bcj[u].cnt1 = 0;
bcj[u].fa = v;
}
void dfs(int x) {
if (a[x].fa > -1) {
if (a[x].v < a[a[x].fa].v) {
shit(x, a[x].fa);
} else {
int u = fa(a[x].fa);
while (a[u].fa > -1 && 1ll * bcj[u].cnt1 * bcj[fa(a[u].fa)].cnt0 < 1ll * bcj[u].cnt0 * bcj[fa(a[u].fa)].cnt1) {
shit(u, fa(a[u].fa));
u = fa(u);
}
}
}
for (int nx : a[x].s) {
dfs(nx);
}
}
struct Node2 {
int x, cnt0, cnt1;
bool operator>(const Node2& a) const {
return 1ll * cnt0 * a.cnt1 > 1ll * a.cnt0 * cnt1;
}
bool operator<(const Node2& a) const {
return 1ll * cnt0 * a.cnt1 < 1ll * a.cnt0 * cnt1;
}
};
priority_queue<Node2> q;
int n, ans = 0, cnt = 0;
void dfs2(int x) {
if (a[x].v > 0) {
ans += cnt;
} else {
--cnt;
}
for (int nx : a[x].s) {
if (fa(nx) == fa(x)) {
dfs2(nx);
} else {
q.push({fa(nx), bcj[fa(nx)].cnt0, bcj[fa(nx)].cnt1});
}
}
}
int main() {
ios_base :: sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
a[1].fa = -1;
for (int i = 2; i <= n; ++i) {
cin >> a[i].fa;
a[a[i].fa].s.push_back(i);
}
for (int i = 1; i <= n; ++i) {
cin >> a[i].v;
bcj[i] = {0, 0, i};
if (a[i].v > 0) {
bcj[i].cnt1 = 1;
} else {
bcj[i].cnt0 = 1;
++cnt;
}
}
dfs(1);
q.push({fa(1), bcj[fa(1)].cnt0, bcj[fa(1)].cnt1});
while (!q.empty()) {
Node2 nx = q.top();
q.pop();
dfs2(nx.x);
}
cout << ans;
return 0;
}