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
63
64
65
66
67
68
69
70
71
72
73
74
75
| // 42jerrykim.github.io에서 더 많은 정보를 확인 할 수 있습니다.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
if (!(cin >> T)) return 0;
while (T--) {
int n, m;
cin >> n >> m;
vector<vector<int>> children(n + 1);
vector<int> parent(n + 1, 0);
for (int i = 2; i <= n; ++i) {
int p; cin >> p;
parent[i] = p;
children[p].push_back(i);
}
vector<long long> apples(n + 1, 0);
long long totalApples = 0;
for (int i = 1; i <= n; ++i) {
cin >> apples[i];
totalApples += apples[i];
}
vector<vector<pair<int, long long>>> cameras(n + 1);
for (int i = 0; i < m; ++i) {
int x, k; long long c;
cin >> x >> k >> c;
cameras[x].push_back({k, c});
}
vector<int> depth(n + 1, 0);
for (int i = 2; i <= n; ++i) depth[i] = depth[parent[i]] + 1;
vector<map<int, long long>> depthToApples(n + 1);
long long flow = 0;
for (int v = n; v >= 1; --v) {
depthToApples[v][depth[v]] += apples[v];
for (int u : children[v]) {
if (depthToApples[v].size() < depthToApples[u].size())
depthToApples[v].swap(depthToApples[u]);
for (auto &kv : depthToApples[u])
depthToApples[v][kv.first] += kv.second;
depthToApples[u].clear();
}
if (!cameras[v].empty()) {
for (auto &cam : cameras[v]) {
int k = cam.first;
long long ff = cam.second;
while (ff > 0 && !depthToApples[v].empty()) {
auto it = depthToApples[v].upper_bound(depth[v] + k);
if (it == depthToApples[v].begin()) break;
--it;
long long take = min(ff, it->second);
flow += take;
ff -= take;
it->second -= take;
if (it->second == 0) depthToApples[v].erase(it);
}
}
}
}
cout << (totalApples - flow) << '\n';
}
return 0;
}
|