#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(x) (x).begin(), (x).end()
const int N = 3e5 + 7;
int n, m;
vector<array<ll, 2>> adj[N];
// cost of dp[0], first slope change, second slope change
array<ll, 3> dfs(int v, ll d) {
if (adj[v].empty())
return {d, d, d};
ll z = 0;
vector<ll> c;
for (auto &[u, w] : adj[v]) {
array<ll, 3> t = dfs(u, d + w);
z += t[0];
c.push_back(t[1]);
c.push_back(t[2]);
}
sort(all(c));
int h = c.size() / 2;
for (int i = 0; i < h; i++)
z -= c[i];
z += c[h - 1];
return {z, c[h - 1], c[h]};
}
int main() {
cin.tie(0)->sync_with_stdio(false);
cin >> n >> m;
for (int i = 2; i <= n + m; i++) {
int p, w;
cin >> p >> w;
adj[p].push_back({i, w});
}
array<ll, 3> res = dfs(1, 0);
cout << res[0] - res[1] << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |