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>
#define pii pair<ll, ll>
typedef long long ll;
using namespace std;
const int MAX = 300003;
vector<int> G[MAX];
priority_queue<pii, vector<pii>, greater<pii>> PQ[MAX];
pii S[MAX];
ll P[MAX];
void DFS(int cur) {
for (int next : G[cur]) DFS(next);
auto& [a, b] = S[cur];
while (!PQ[cur].empty()) {
auto [c, d] = PQ[cur].top();
if (b < c) break;
b += d - c;
PQ[cur].pop();
}
if (!cur) return;
if (a < b) PQ[cur].push(S[cur]);
else {
while (!PQ[cur].empty() && (a >= b || PQ[cur].top().first <= a)) {
auto [c, d] = PQ[cur].top(); PQ[cur].pop();
if (b <= c) a += c - b, b = d;
else b += d - c;
}
if (a < b) PQ[cur].emplace(a, b);
}
if (PQ[cur].size() > PQ[P[cur]].size()) swap(PQ[cur], PQ[P[cur]]);
while (!PQ[cur].empty()) {
auto [c, d] = PQ[cur].top(); PQ[cur].pop();
PQ[P[cur]].emplace(c, d);
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
ll N, IS;
cin >> N >> IS;
S[0] = {0, IS};
for (int i = 1; i <= N; ++i) {
ll s;
cin >> s >> P[i];
G[P[i]].push_back(i);
if (s < 0) S[i] = {-s, 0};
else S[i] = {0, s};
}
DFS(0);
ll ans = S[0].second - IS;
cout << ans;
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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |