#include <bits/stdc++.h>
#include "dungeons.h"
using namespace std;
constexpr int lg = 30;
int n;
vector<int> s, p, w, l;
vector<vector<int>> to;
vector<vector<long long>> f;
void init(int _n, vector<int> _s, vector<int> _p, vector<int> _w, vector<int> _l) {
n = _n;
s = _s;
p = _p;
w = _w;
l = _l;
to.resize(n + 1, vector<int>(lg, n));
f.resize(n + 1, vector<long long>(lg));
for (int i = 0; i < n; i++) {
to[i][0] = l[i];
f[i][0] = p[i];
}
for (int j = 1; j < lg; j++) {
for (int i = 0; i < n; i++) {
to[i][j] = to[to[i][j - 1]][j - 1];
f[i][j] = f[i][j - 1] + f[to[i][j - 1]][j - 1];
}
}
}
long long simulate(int x, int z) {
long long ans = z;
while (x != n) {
if (ans >= s[x]) {
ans += s[x];
x = w[x];
} else {
if (l[x] < x) {
for (int i = lg - 1; i >= 0; i--) {
if (ans + f[x][i] < s[0] && to[x][i] < n) {
ans += f[x][i];
x = to[x][i];
}
}
}
ans += p[x];
x = l[x];
}
}
return ans;
}