#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
#define lgn 26
#define defN 400001
#define defV 10000001
int N,compy;
vector<vector<pii>>twok(defN,vector<pii>(lgn));
vector<int>findist(defN);
void init(int n, vector<int> s, vector<int> p, vector<int> w, vector<int> l)
{
N=n;compy=s[0];
for(int a=0;a<N;a++)
{
twok[a][0]=mp(l[a],p[a]);
}
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;
}
}
for(int a=N-1;a>=0;a--)
{
findist[a]=s[a]+findist[w[a]];
}
}
pii godec(int num, int fr)
{
int curr=fr,amt=0;
for(int i=0;i<defN;i++)
{
if((1<<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-1,lo=0,mid;
while(hi>lo+1)
{
mid=(hi+lo)/2;
if(checkers(mid,z,x))
{
hi=mid;
}
else
{
lo=mid;
}
}
pii kk=godec(x,hi);
z+=kk.ss;z+=findist[kk.ff];
return z;
}