이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 300300;
bool leaf[N];
vector<pair<int, ll>> adj[N];
ll ansl[N], ansr[N], ans[N];
multiset<ll, greater<ll>> l[N];
multiset<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);
ans[v] += ans[x];
if (l[v].empty()) {
l[v].insert(ansl[x]);
r[v].insert(ansr[x]);
continue;
}
ll nowl = *l[v].begin(), nowr = *r[v].begin();
ll newl = ansl[x], newr = ansr[x];
if (newr < nowl) {
ans[v] += nowl - newr;
l[v].insert(newl);
l[v].insert(newr);
l[v].erase(l[v].begin());
r[v].insert(nowl);
}
else if (nowr < newl) {
ans[v] += newl - nowr;
r[v].insert(newl);
r[v].insert(newr);
r[v].erase(r[v].begin());
l[v].insert(nowr);
}
else {
l[v].insert(newl);
r[v].insert(newr);
}
}
ansl[v] = *l[v].begin();
ansr[v] = *r[v].begin();
}
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;
ll c;
cin >> p >> c;
adj[p].push_back({ i, c });
}
for (int i = n + 1;i <= n + m;i++) leaf[i] = 1;
dfs(1, 0ll);
cout << ans[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... |