-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path6865.cpp
62 lines (51 loc) · 1.26 KB
/
6865.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @file 6865.cpp
* @author Macesuted ([email protected])
* @date 2023-03-05
*
* @copyright Copyright (c) 2023
*
*/
#include <bits/stdc++.h>
using namespace std;
#ifndef LOCAL
#define endl '\n'
#endif
bool mem1;
#define maxn 200005
int a[maxn], siz[maxn], dep[maxn], dfni[maxn], dfno[maxn];
vector<int> graph[maxn];
int dfnt = 0;
void dfs(int p, int pre = 0) {
dep[p] = dep[pre] + 1, siz[p] = 1, dfni[p] = ++dfnt;
for (auto i : graph[p])
if (i != pre) dfs(i, p), siz[p] += siz[i];
dfno[p] = dfnt;
return;
}
void solve(void) {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 2, x; i <= n; i++) cin >> x, graph[x].push_back(i);
dep[0] = -1, dfs(1);
for (int i = 1; i <= n; i++) a[i] = siz[i] - 1 - a[i] - dep[i];
sort(a + 1, a + n + 1, greater<int>());
int64_t sum = 0;
for (int i = 1; i <= n; i += 2) sum += a[i];
cout << sum << endl;
return;
}
bool mem2;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
#ifdef LOCAL
cerr << "Memory Cost: " << abs(&mem1 - &mem2) / 1024. / 1024. << "MB" << endl;
#endif
int _ = 1;
while (_--) solve();
#ifdef LOCAL
cerr << "Time Cost: " << clock() * 1000. / CLOCKS_PER_SEC << "MS" << endl;
#endif
return 0;
}