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 mp make_pair
#define pb push_back
#define int long long
using ll = long long;
int N, s, cur, x[300005], p[300005];
vector<int> adj[300005];
namespace ufds {
int lnk[300005], sz[300005], l[300005], v[300005], highest[300005];
void init(int n) {
iota(lnk, lnk + 1 + n, 0);
iota(highest, highest + 1 + n, 0);
fill(sz, sz + 1 + n, 1);
}
int find(int x) {
if (x == lnk[x]) {
return x;
}
return lnk[x] = find(lnk[x]);
}
void unite(int a, int b) {
//~ cout << "MERGE " << a << ' ' << b << '\n';
a = find(a);
b = find(b);
if (a == b) {
return;
}
if (sz[b] > sz[a]) {
swap(a, b);
}
sz[a] += sz[b];
lnk[b] = a;
highest[a] = highest[b];
}
};
void pass(int u) {
if (u && ufds::find(u) != ufds::find(p[u])) {
int l_p = ufds::l[ufds::find(p[u])];
int v_p = ufds::v[ufds::find(p[u])];
int l_u = ufds::l[ufds::find(u)];
int v_u = ufds::v[ufds::find(u)];
//~ cout << "@ " << u << ' ' << l_u << ' ' << v_u << ' ' << l_p << ' ' << v_p << '\n';
if (l_p + v_p >= l_u && v_u >= 0) {
ufds::unite(u, p[u]);
ufds::l[ufds::find(u)] = l_p;
ufds::v[ufds::find(u)] = v_p + v_u;
}
}
}
int dfs(int u, int sf = 0) {
//~ cout << "@ " << u << ' ' << sf << ' ' << ufds::l[ufds::find(u)] << ' ' << sf << '\n';
if (u == ufds::highest[ufds::find(u)] && ufds::l[ufds::find(u)] - sf > cur) {
return 0;
}
int tmp = 0;
if (u == ufds::highest[ufds::find(u)]) {
tmp += ufds::v[ufds::find(u)];
sf += ufds::v[ufds::find(u)];
}
for (auto v : adj[u]) {
tmp += dfs(v, sf);
}
return max(tmp, 0ll);
}
main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> s;
ufds::l[0] = 0;
ufds::v[0] = s;
for (int i = 1; i <= N; i++) {
cin >> x[i] >> p[i];
adj[p[i]].pb(i);
ufds::l[i] = max(0ll, -x[i]);
ufds::v[i] = x[i];
}
ufds::init(N);
for (int rep = 0; rep < N; rep++) {
for (int i = 1; i <= N; i++) {
pass(i);
}
}
for (int rep = 0; rep < N; rep++) {
cur = dfs(0) - s;
}
cout << cur << '\n';
}
Compilation message (stderr)
Main.cpp:74:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
74 | main() {
| ^~~~
# | 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... |