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;
using i64 = long long;
#define debug false
#define int long long
const int maxn = 3e5;
vector<int> graph[maxn+2];
int x[maxn+2] , p[maxn+2];
bool root[maxn+2];
int n;
i64 s , pre[maxn+2] , f[maxn+2] , dp[maxn+2];
i64 dfs(int u , int p , i64 sum){
sum += x[u];
if (sum < 0) return sum;
for (auto& v : graph[u]){
if (v!=p){
sum = max(sum , dfs(v,u,sum));
}
}
if (debug){
cout << "( DEBUG )\n";
cout << u << ' ' << sum << '\n';
}
return sum;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> s;
bool ok = true;
for (int i = 1; i <= n; ++i){
cin >> x[i] >> p[i];
if (p[i] != 0 && p[i] != i - 1) ok = false;
if (p[i]==0) root[i] = true;
else graph[p[i]].push_back(i);
}
i64 alter = s;
for (int i = 1; i <= n; ++i){
if (root[i])
s = max(s , dfs(i,i,s));
}
if (ok){
cout << s - alter;
return 0;
}
for (int i = 1; i <= n; ++i) pre[i] = pre[i - 1] + x[i];
f[0] = s;
for (int i = 1; i <= n; ++i){
int pos = i;
for (int j = i; j >= 1; --j){
dp[i] = max(dp[i] , dp[j]);
if (p[j]==0){
pos = j; break;
}
}
dp[i] = max(dp[i] , f[pos - 1] + pre[i] - pre[pos - 1]);
dp[i] = max(dp[i] , f[pos - 1]);
f[i] = max(dp[i] , f[i - 1]);
}
cout << dp[n] - s;
}
# | 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... |