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;
#ifdef Nero
#include "Deb.h"
#else
#define debug(...)
#endif
const int N = 3e5 + 5;
int x[N];
int p[N];
bool taken[N];
bool active[N];
vector<int> g[N];
long long sum[N];
long long best[N];
long long nbest[N];
long long min_suf[N];
long long min_seg[N];
void dfs(int v) {
min_suf[v] = min(0LL, min_suf[v] + x[v]);
min_seg[v] = min(min_seg[v], min_suf[v]);
for (int u : g[v]) {
min_suf[u] = min_suf[v];
min_seg[u] = min_seg[v];
dfs(u);
}
}
void activate(int v) {//no child is activated before a parent
//debug(v);
int b = x[v];
nbest[v] = b;
active[v] = true;
while (v != 0) {
nbest[p[v]] = best[p[v]] - max(0LL, best[v]);
nbest[p[v]] += max(0LL, nbest[v]);
best[v] = nbest[v];
//debug(v, best[v]);
v = p[v];
}
//cout << '\n';
}
void dfs2(int v) {
taken[v] = true;
for (int u : g[v]) {
if (best[u] > 0) {
dfs2(u);
} else {
p[u] = 0;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long s;
cin >> n >> s;
for (int i = 1; i <= n; ++i) {
cin >> x[i] >> p[i];
g[p[i]].push_back(i);
}
long long cur = s;
for (int rep = 0; rep < n; ++rep) {
for (int i = 1; i <= n; ++i) {
if (p[i] == 0 && !taken[i]) {
min_suf[i] = min_seg[i] = 0;
dfs(i);
}
}
for (int i = 1; i <= n; ++i) {
if (!active[i] && !taken[i] && cur + min_seg[i] >= 0) {
activate(i);
}
}
for (int i = 1; i <= n; ++i) {
if (!taken[i] && p[i] == 0 && best[i] > 0) {
//debug(i, best[i]);
cur += best[i];
dfs2(i);
break;
}
}
}
cout << cur - s << '\n';
return 0;
}
# | 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... |