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;
#define mp make_pair
#define pb push_back
#define int long long
using ll = long long;
using ll2 = pair<ll, ll>;
int N, x[300005];
ll s, profit;
vector<int> adj[300005];
priority_queue<ll2, vector<ll2>, greater<ll2> > pq[300005];
void dfs(int u) {
for (auto v : adj[u]) {
dfs(v);
if (pq[u].size() < pq[v].size()) {
swap(pq[u], pq[v]);
}
while (!pq[v].empty()) {
pq[u].push(pq[v].top());
pq[v].pop();
}
}
if (x[u] >= 0) {
pq[u].emplace(0, x[u]);
} else {
ll r = -x[u], p = x[u];
while (!pq[u].empty() && p < 0) {
auto [nr, np] = pq[u].top();
r = max(r, nr - p);
p += np;
pq[u].pop();
}
if (p >= 0) {
while (!pq[u].empty() && r >= pq[u].top().first) {
p += pq[u].top().second;
pq[u].pop();
}
pq[u].emplace(r, p);
} else {
assert(pq[u].empty());
}
}
}
main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> s;
for (int i = 1, p; i <= N; i++) {
cin >> x[i] >> p;
adj[p].pb(i);
}
dfs(0);
while (!pq[0].empty() && s >= pq[0].top().first && pq[0].top().second >= 0) {
s += pq[0].top().second;
profit += pq[0].top().second;
pq[0].pop();
}
cout << profit << '\n';
}
Compilation message (stderr)
Main.cpp:49:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
49 | main() {
| ^~~~
# | 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... |