#include "dungeons.h"
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define lsb(x) (x&(-x))
#define pii pair<int,int>
#define ss second
#define ff first
#define piii pair<int,pii>
#define debu(x) (cerr << #x << " = "<< x << "\n")
#define debu2(x,y) (cerr << #x << " = "<< x << " " << #y << " = " << y << "\n")
#define debu3(x,y,z) (cerr << #x << " = "<< x << " " << #y << " = " << y << " " << #z << " = " << z<< "\n")
#define bitout(x,y) {\
cerr << #x << " : ";\
for (int justforbits = y; justforbits >=0; justforbits--)cout << (((1 << justforbits) & x)>=1);\
cout << "\n";\
}
#define rangeout(j,rangestart,rangeend) {\
cerr << "outputting " << #j<< ":\n";\
for (int forrang = rangestart; forrang <= rangeend; forrang++)cerr << j[forrang] << " ";\
cerr<<"\n";\
}
#define c1 {cerr << "Checkpoint 1! \n\n";cerr.flush();}
#define c2 {cerr << "Checkpoint 2! \n\n";cerr.flush();}
#define c3 {cerr << "Checkpoint 3! \n\n";cerr.flush();}
#define c4 {cerr << "Checkpoint 4! \n\n";cerr.flush();}
//maximum is just your largest win cond
//didn't consider reaching n before full :(
#define lgn 26
#define defN 400001
#define defV 10000001
#define ll long long
#define pll pair<ll,ll>
int N,compy;
vector<vector<pll>>twok(defN,vector<pll>(lgn));
vector<ll>findist(defN+1);
void init(int n, vector<int> s, vector<int> p, vector<int> w, vector<int> l)
{
N=n;compy=s[0];
//rangeout(l,0,l.size()-1);
for(int a=0;a<N;a++)
{
twok[a][0]=mp(l[a],p[a]);
//debu2(l[a],p[a]);
}
fill(twok[N].begin(),twok[N].end(),mp(N,2*defV));
for(int a=1;a<lgn;a++)
{
for(int b=0;b<N;b++)
{
int nx=twok[b][a-1].ff;
twok[b][a].ss=twok[b][a-1].ss+twok[nx][a-1].ss;
twok[b][a].ff=twok[nx][a-1].ff;
}
}
findist[N]=0;
for(int a=N-1;a>=0;a--)
{
//debu(s[a]);
findist[a]=s[a]+findist[w[a]];
//debu(findist[a]);
}
}
pll godec(int num, int fr)
{
ll curr=fr,amt=0;
for(int i=0;i<lgn;i++)
{
if((1ll<<i)&num)
{
amt+=twok[curr][i].ss;
curr=twok[curr][i].ff;
}
}
return mp(curr,amt);
}
bool checkers(int mid, int z, int x)
{
pii retno=godec(mid,x);
if(retno.ss+z>=compy)return true;
else return false;
}
long long simulate(int x, int z)
{
if(z>=compy)return (z+findist[x]);
int hi=defV-2,lo=0,mid;
while(hi>lo+1)
{
mid=(hi+lo)/2;
if(checkers(mid,z,x))
{
hi=mid;
}
else
{
lo=mid;
}
}
pii kk=godec(hi,x);
ll ans=z;
ans+=kk.ss;ans+=findist[kk.ff];
//debu2(kk.ff,findist[kk.ff]);
if(kk.ss>=2*defV)ans-=2*defV;
return ans;
}