This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/*
Mayoeba Yabureru
*/
#include<bits/stdc++.h>
using namespace std;
void solve() {
long long n, s, ans = 0;
cin >> n >> s;
vector<long long> x(n + 1), dp(n + 1);
vector<int> p(n + 1), st, done(n + 1);
vector<vector<int>> gr(n + 1);
for (int i = 1; i <= n; i ++) {
cin >> x[i] >> p[i];
if (p[i] == 0) st.push_back(i);
else gr[p[i]].push_back(i);
}
set<pair<pair<long long, long long>, pair<int, int>>> ss;
long long sum = 0;
function<void(int)> go = [&] (int v) {
sum += x[v];
if (sum < 0 && -sum > s) {
dp[v] = 0;
sum -= x[v];
return;
}
dp[v] = x[v];
for (auto u : gr[v]) {
go(u);
dp[v] += dp[u];
}
dp[v] = max(dp[v], 0ll);
sum -= x[v];
};
function<void(int)> goo = [&] (int v) {
sum += x[v];
if (sum < 0 && -sum > s) {
sum -= x[v];
st.push_back(v);
return;
}
done[v] = 1;
for (auto u : gr[v]) {
if (dp[u] > 0) goo(u);
else st.push_back(u);
}
sum -= x[v];
};
while (true) {
int did = 0;
for (auto v : st) {
go(v);
if (dp[v] > 0) {
goo(v);
s += dp[v];
ans += dp[v];
did = 1;
break;
}
}
vector<int> stt;
for (auto v : st) {
if (done[v] == 0) stt.push_back(v);
}
st = stt;
if (did) continue;
break;
}
cout << ans << endl;
}
/*
6 1
-1 0
2 1
3 2
-10 0
1 4
-2 5
*/
int main()
{
int T = 1;
for (int I = 0; I < T; I ++){
solve();
}
}
# | 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... |