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>
#define sz(s) (int)s.size()
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;
typedef priority_queue<ar2, vector<ar2>, greater<ar2>> pq;
ll pval[MAXN];
void make_prof(pq &prof, int cur, ll sm = 0, ll mn = 0) {
sm += val[cur];
mn = min(mn, sm);
if (sm > 0) {
prof.push({-mn, cur});
pval[cur] = sm;
return;
}
if (!nxt[cur].empty()) make_prof(prof, nxt[cur][0], sm, mn);
}
void solve2() {
pq prof;
for (int rt: rts) {
make_prof(prof, rt);
}
ll o = s;
while (!prof.empty()) {
ar2 t = prof.top();
prof.pop();
if (s < t[0]) break;
s += pval[t[1]];
if (!nxt[t[1]].empty()) make_prof(prof, nxt[t[1]][0]);
}
cout << s-o << '\n';
}
bool chk_nxt() {
for (int i = 0; i < n; i++) {
if (sz(nxt[i]) > 1) return 0;
}
return 1;
}
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 (chk_nxt()) 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... |