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
76
77
78
79
80
81
82
83
84
85
86
87
| // 42jerrykim.github.io에서 더 많은 정보를 확인 할 수 있습니다.
#include <bits/stdc++.h>
using namespace std;
using lint = long long;
const int MAXN = 300000 + 5;
int n, m, sz[MAXN];
lint dep[MAXN], c[MAXN];
vector<int> gph[MAXN];
struct Func {
priority_queue<lint> pq;
lint cost;
int slope;
void init() {
cost = 0;
slope = -1;
pq.push(0);
pq.push(0);
}
void upperize(int x) {
cost += c[x];
while (!pq.empty() && slope + (int)pq.size() > 1) {
pq.pop();
}
vector<lint> v;
while (!pq.empty() && slope + (int)pq.size() >= 0) {
v.push_back(pq.top());
pq.pop();
}
while (!v.empty()) {
pq.push(v.back() + c[x]);
v.pop_back();
}
}
} dp[MAXN];
static inline bool cmpSize(int a, int b) { return sz[a] > sz[b]; }
void dfs(int x) {
if (x > n) { sz[x] = 1; return; }
for (int y : gph[x]) {
dep[y] = dep[x] + c[y];
dfs(y);
sz[x] += sz[y];
}
sort(gph[x].begin(), gph[x].end(), cmpSize);
}
int solve(int x) {
if (x > n) { dp[x].init(); return x; }
int ret = solve(gph[x][0]);
dp[ret].upperize(gph[x][0]);
for (int i = 1; i < (int)gph[x].size(); i++) {
int t = solve(gph[x][i]);
dp[t].upperize(gph[x][i]);
dp[ret].cost += dp[t].cost;
dp[ret].slope += dp[t].slope;
while (!dp[t].pq.empty()) {
dp[ret].pq.push(dp[t].pq.top());
dp[t].pq.pop();
}
}
return ret;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 2; i <= n + m; i++) {
int p; scanf("%d %lld", &p, &c[i]);
gph[p].push_back(i);
}
dfs(1);
Func ret = dp[solve(1)];
ret.upperize(0);
lint best = ret.pq.top();
lint ans = ret.cost + best * ret.slope;
while (!ret.pq.empty()) {
ans += best - ret.pq.top();
ret.pq.pop();
}
printf("%lld\n", ans);
return 0;
}
|