#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <deque>
#include <map>
#include <chrono>
#include <random>
#include <bitset>
#include <tuple>
#include "dungeons.h"
#define SZ(x) int(x.size())
#define FR(i,a,b) for(int i=(a);i<(b);++i)
#define FOR(i,n) FR(i,0,n)
#define FAST ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define A first
#define B second
#define mp(a,b) make_pair(a,b)
typedef long long LL;
typedef long double LD;
typedef unsigned long long ULL;
typedef unsigned __int128 U128;
typedef __int128 I128;
typedef std::pair<int,int> PII;
typedef std::pair<LL,LL> PLL;
using namespace std;
//does simulation work? only one way to find out
LL n;
const LL MAXN=5e4+5;
LL s[MAXN], p[MAXN], w[MAXN], l[MAXN];
void init(int N, std::vector<int> S, std::vector<int> P, std::vector<int> W, std::vector<int> L) {
n=(LL)N;
FOR(i,n){
s[i]=(LL)S[i];
p[i]=(LL)P[i];
w[i]=(LL)W[i];
l[i]=(LL)L[i];
}
return;
}
long long simulate(int X, int Z) {
LL x=(LL)X, z=(LL)Z;
LL pos=x, cur=z;
while (pos!=n){
if (cur>=s[pos]){
cur+=s[pos];
pos=w[pos];
}
else{
cur+=p[pos];
pos=l[pos];
}
//cout<<pos<<" "<<cur<<"\n";
}
return cur;
}