#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];
int lst[N];
// value of dp[0], points where slope changes
ll z[N];
multiset<ll> slope[N];
void dfs(int v) {
for (auto &[u, w] : adj[v]) {
dfs(u);
if (adj[u].empty()) {
slope[u] = {w, w};
z[u] = w;
} else {
while (lst[u] > 1) {
slope[u].erase(prev(slope[u].end()));
lst[u]--;
}
vector<ll> v;
while (v.size() < 2) {
auto it = prev(slope[u].end());
v.push_back(*it);
slope[u].erase(it);
}
for (ll x : v)
slope[u].insert(x + w);
z[u] += w;
}
if (slope[u].size() > slope[v].size())
slope[u].swap(slope[v]);
z[v] += z[u];
for (ll x : slope[u])
slope[v].insert(x);
lst[v]++;
}
}
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});
}
dfs(1);
ll ans = z[1];
slope[1].erase(prev(slope[1].end()));
for (ll x : slope[1]) {
ans -= x;
}
cout << ans << '\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... |