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;
typedef long long ll;
const int N = 3e5 + 12, MOD = (int)1e9 + 7;
#define int ll
int n, p[N], x[N];
ll s, d[N];
vector<int> g[N], rt, ord[N];
multiset<pair<ll, ll>> st[N];
void prec(int v) {
d[v] = x[v];
for(int to:g[v]) {
prec(to);
if(d[to] < 0) continue;
d[v] += d[to];
}
}
deque<pair<ll, ll>> deq[N];
void dfs(int v) {
if(d[v] < 0) return;
for(int to:g[v]) {
dfs(to);
if((int)st[to].size() > (int)st[v].size()) {
st[to].swap(st[v]);
}
for(auto i:st[to]) {
st[v].insert(i);
}
}
ll val = x[v], mn = min(0ll, val);
while(val < 0) {
auto [r, y] = (*st[v].rbegin());
st[v].erase(st[v].find(*st[v].rbegin()));
mn = min(mn, val + r);
val += y;
}
while(!st[v].empty() && (*st[v].rbegin()).first >= mn) {
auto [r, y] = (*st[v].rbegin());
st[v].erase(st[v].find(*st[v].rbegin()));
val += y;
}
st[v].insert({mn, val});
}
void test() {
cin >> n >> s;
for(int i = 1; i <= n; i++) {
cin >> x[i] >> p[i];
g[p[i]].push_back(i);
}
prec(0);
dfs(0);
ll en = s, mx = s;
vector<pair<ll, ll>> vec;
for(auto [y, x]:st[0]) {
vec.push_back({y, x});
}
reverse(vec.begin(), vec.end());
for(auto [y, x]:vec) {
if(en + y < 0) {
break;
}
en += x;
}
cout << en - s << '\n';
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while(t--)
test();
return 0;
}
Compilation message (stderr)
Main.cpp: In function 'void test()':
Main.cpp:55:16: warning: unused variable 'mx' [-Wunused-variable]
55 | ll en = s, mx = s;
| ^~
# | 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... |