#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#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);
for (int i = 1; i <= n; i++){
cin>>a[i]>>p[i];
g[p[i]].pb(i);
}
pair<ll, int> mx;
function<void(int, ll)> dfs = [&](int v, ll k){
k += a[v];
if ((s + k) < 0) return;
mx = max(mx, {k, v});
for (int i: g[v]){
if (i == p[v]) continue;
dfs(i, k);
}
};
ll out = 0;
while (true){
mx = {0, 0};
dfs(0, 0);
if (mx.ff <= 0) break;
out += mx.ff;
s += mx.ff;
int v = mx.ss;
while (v > 0){
a[v] = 0;
v = p[v];
}
}
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... |