This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 300300;
bool leaf[N];
vector<pair<int, int>> adj[N];
ll ansl[N], ansr[N], ans[N];
priority_queue<ll> l[N];
priority_queue<ll, vector<ll>, greater<ll>> r[N];
void dfs(int v, ll d) {
if (leaf[v]) {
ansl[v] = d;
ansr[v] = d;
return;
}
for (auto& [x, w] : adj[v]) {
dfs(x, d + w);
if (l[v].empty()) {
ans[v] = ans[x];
l[v].push(ansl[x]);
r[v].push(ansr[x]);
continue;
}
ans[v] += ans[x];
if (ansr[x] < l[v].top()) {
ans[v] += l[v].top() - ansr[x];
l[v].push(ansl[x]);
l[v].push(ansr[x]);
r[v].push(l[v].top());
l[v].pop();
}
else if (ansl[x] > r[v].top()) {
ans[v] += ansl[x] - r[v].top();
r[v].push(ansl[x]);
r[v].push(ansr[x]);
l[v].push(r[v].top());
r[v].pop();
}
else {
l[v].push(ansl[x]);
r[v].push(ansr[x]);
}
}
ansl[v] = l[v].top();
ansr[v] = r[v].top();
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int n, m;
cin >> n >> m;
for (int i = 2;i <= n + m;i++) {
int p, c;
cin >> p >> c;
adj[p].push_back({ i, c });
if (i > n) leaf[i] = 1;
}
dfs(1, 0);
cout << ans[1];
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... |