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;
#define int long long
vector<int> adj[300005];
int a[300005];
deque<int> v[300005];
int mn[300005], sm[300005];
void dfs(int x) {
v[x].push_back(a[x]);
sm[x] = a[x];
mn[x] = min(a[x], 0LL);
vector<pair<int, int>> vec;
for(int i : adj[x]) {
dfs(i);
vec.push_back({-mn[i],i});
}
sort(vec.begin(), vec.end());
for(auto [m, idx] : vec) {
m = -m;
if(v[x].size() < v[idx].size()) {
swap(v[x], v[idx]);
while(v[idx].size()) {
v[x].push_front(v[idx].back());
v[idx].pop_back();
}
} else {
while(v[idx].size()) {
v[x].push_back(v[idx].front());
v[idx].pop_front();
}
}
mn[x] = min(mn[x], sm[x]+m);
sm[x] += sm[idx];
}
if(sm[x] <= 0) {
v[x].clear();
sm[x] = mn[x] = 0;
}
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n, s, x, ans = 0, cur = 0;
cin >> n >> s;
a[0] = s;
for(int i = 1; i <= n; i++) {
cin >> a[i] >> x;
adj[x].push_back(i);
}
dfs(0);
for(int i : v[0]) {
cur += i;
if(cur < 0) break;
ans = max(ans, cur);
}
cout << ans-s;
}
Compilation message (stderr)
Main.cpp: In function 'void dfs(long long int)':
Main.cpp:21:11: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
21 | for(auto [m, idx] : vec) {
| ^
# | 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... |