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
using ll = long long;
using ill = pair<int, ll>;
int N, x[300005];
ll s, profit;
vector<int> adj[300005];
priority_queue<ill, vector<ill>, greater<ill> > pq[300005];
void print(priority_queue<ill, vector<ill>, greater<ill> > tmp) {
while (!tmp.empty()) {
auto [r, p] = tmp.top();
cout << r << ' ' << p << '\n';
tmp.pop();
}
}
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 {
int r = -x[u], p = x[u];
while (!pq[u].empty() && r >= pq[u].top().first) {
p += pq[u].top().second;
pq[u].pop();
}
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) {
pq[u].emplace(r, p);
}
}
}
int 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) {
s += pq[0].top().second;
profit += pq[0].top().second;
pq[0].pop();
}
cout << profit << '\n';
}
# | 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... |