#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
#define pb push_back
#define ff first
#define ss second
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n; ll s; cin>>n>>s;
vector<int> g[n + 1], a(n + 1), p(n + 1), l(n + 1), r(n + 1);
for (int i = 1; i <= n; i++){
cin>>a[i]>>p[i];
l[i] = i;
g[p[i]].pb(i);
}
int t = n + 1;
for (int i = n; i > 0; i--){
r[i] = t - 1;
if (!p[i]) t = i;
}
priority_queue<pli> pq;
vector<ll> v(n + 1);
auto add = [&](int i){
ll sum = 0, mn = 0;
while (l[i] <= r[i]){
sum += a[l[i]];
mn = min(mn, sum);
l[i]++;
if (sum > 0){
pq.push({mn, i});
v[i] = sum;
break;
}
}
};
for (int i = 1; i <= n; i++){
if (!p[i]){
add(i);
}
}
ll out = 0;
while (!pq.empty()){
auto [f, i] = pq.top(); pq.pop();
if ((f + s) < 0) break;
s += v[i]; out += v[i];
add(i);
}
cout<<out<<"\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... |