#include "dungeons.h"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<int> S, P, W, L;
int N;
const int MAXN = 5e4 + 1;
vector<int> adj[MAXN + 1];
ll cost[MAXN + 1];
void init(int n, std::vector<int> s, std::vector<int> p, std::vector<int> w, std::vector<int> l) {
	N = n;
	S = s;
	P = p;
	W = w;
	L = l;
	S.push_back(0);
	for (int i = 0; i < n; ++i) {
		adj[w[i]].push_back(i);
	}
	auto dfs = [&](auto& dfs, int i, ll now) -> void {
		now += S[i];
		cost[i] = now;
		for (auto& u : adj[i]) {
			dfs(dfs, u, now);
		}
	};
	dfs(dfs, n, 0);
	// for (int i = 0; i < n; ++i) {
	// 	cerr << cost[i] << " ";
	// }
	// cerr << "\n";
	return;
}
long long simulate(int x, int z) {
	ll res = z;
	vector<bool> vis(N);
	ll tot = 0;
	while (x != N && res < S[0] && !vis[x]) {
		vis[x] = true;
		if (res < S[x]) {
			res += P[x];
			x = L[x];
		}
	}
	if (x == N) return res;
	if (res >= S[0]) {
		return res + cost[x];
	}
	// cerr << x << " " << res << " " << tot << "\n";
	tot = 0;
	int y = x;
	do {
		tot += P[y];
		y = L[y];
	} while (y != x);
	// cerr << tot << " ";
	res += (S[0] - res) / tot * tot;
	// cerr << res << " " << "\n";
	while (x != N && res < S[0]) {
		if (res < S[x]) {
			res += P[x];
			x = L[x];
		}
	}
	// cerr << res << " " << x << "\n";
	res += cost[x];
	return res;
}
| # | 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... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |