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;
const int MAXN = 3e5+5;
typedef long long ll;
const ll inf = 1e18;
int n;
vector<int> nxt[MAXN];
ll val[MAXN];
ll mx_val[MAXN];
vector<int> rts;
ll s;
ll dfs(int cur) {
ll res = 0;
for (int v: nxt[cur]) {
res += dfs(v);
}
return max(0ll,res+val[cur]);
}
void solve1() {
ll ans = 0;
for (int i: rts) ans += dfs(i);
cout << ans << '\n';
}
typedef array<ll, 2> ar2;
void make_prof(vector<ar2> &prof, int cur, ll sm = 0, ll mn = 0, ll mx = 0) {
sm += val[cur];
mn = min(mn, sm);
if (sm > mx) {
prof.push_back({-mn, sm-mx});
mx = sm;
}
if (!nxt[cur].empty()) make_prof(prof, nxt[cur][0], sm, mn, mx);
}
void solve2() {
vector<ar2> prof;
for (int rt: rts) {
make_prof(prof, rt);
}
sort(prof.begin(), prof.end());
ll o = s;
for (ar2 a: prof) {
if (s < a[0]) break;
s += a[1];
}
cout << s-o << '\n';
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
cin >> n >> s;
for (int i = 0; i < n; i++) {
int p; cin >> val[i] >> p;
if (p == 0) rts.push_back(i);
else nxt[p-1].push_back(i);
}
if (s == inf) solve1();
else if (n <= 2000) solve2();
else assert(false);
}
# | 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... |