# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1004675 | Trisanu_Das | Jobs (BOI24_jobs) | C++17 | 0 ms | 0 KiB |
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;
vector<long long> x;
vector<vector<int> > c;
vector<pair<long long, long long> > res;
long long dfs(int a) {
long long sum = x[a];
for(int i = 0; i < c[a].size(); i++) sum += dfs(c[a][i]);
return max(sum, 0ll);
}
void dfs2(int a, long long pr, long long mp, long long lo) {
long long nex = pr + x[a];
if(nex > mp) res.push_back({lo - mp, nex - mp});
for(int i = 0; i < c[a].size(); i++) dfs2(c[a][i], nex, max(mp, nex), min(lo, nex));
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n, a; long long s;
cin >> n >> s;
x.resize(n + 1);
c.resize(n + 1);
x[0] = 0ll;
for(int i = 1; i <= n; i++){
cin >> x[i] >> a;
c[a].push_back(i);
}
if(s == 1e18) cout << dfs(0) << '\n';
else {
ll ans = 0;
for(int i = 0; i < c[0].size(); i++) dfs2(c[0][i], 0ll, 0ll, 0ll);
sort(res.begin(), res.end(), greater<pair<long long, long long> >());
for(int i = 0; i < res.size(); i++){
if(res[i].fir + s < 0) break;
s += res[i].sec;
ans += res[i].sec;
}
cout << ans << '\n';
}
}