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;
if (c < d) b = b + d - c;
PQ[cur].pop();
}
// cout << "Cur: " << a << ' ' << b << '\n';
// cout << "Remain at " << cur << ":\n";
if (!cur) return;
// vector<pii> temp;
// while (!PQ[cur].empty()) {
// auto [a, b] = PQ[cur].top();
// temp.emplace_back(PQ[cur].top());
// PQ[cur].pop();
// cout << a + off[cur].first << ' ' << b + off[cur].second << '\n';
// }
// cout << '\n';
// for (auto [a, b] : temp) PQ[cur].emplace(a, b);
if (a < b) PQ[cur].emplace(a, b);
else {
vector<pii> temp;
while (!PQ[cur].empty()) {
auto [c, d] = PQ[cur].top(); PQ[cur].pop();
temp.emplace_back(c + a - b, d);
}
for (auto [c, d] : temp) PQ[cur].emplace(c, d);
}
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... |