#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
inline int read(){
register int x=0,f=0,ch=getchar();
while('0'>ch||ch>'9')f^=ch=='-',ch=getchar();
while('0'<=ch&&ch<='9')x=(x<<1)+(x<<3)+(ch^'0'),ch=getchar();
return f?-x:x;
}
const int MAX=5e5;
int T,now,s,n,u,t,l;
int to[MAX],vis[MAX],de[MAX],dis[MAX];
inline int qpow(int x,int p,int P){
register int res=1ll;
for(;p;p>>=1,x=1ll*x*x%P)if(p&1)res=1ll*res*x%P;
return res;
}
int dfs(int x){
if(vis[x])return 0;
return dis[x]=(dfs(to[x])+1)%l;
}
signed main(){
n=read();
for(register int i=1;i<=n;++i)u=read(),to[i]=u,++de[u];
for(now=1;!vis[now];now=to[now])vis[now]=1;
memset(vis,0,sizeof(vis));
for(;!vis[now];now=to[now])++l,vis[now]=1;
for(register int i=1;i<=n;++i)if(!vis[i]&&!de[i])dis[i]=(dfs(to[i])+1)%l;
T=read();
while(T--){
s=read(),t=read(),u=read();
t=qpow(t,u,l);
if(vis[s])for(register int i=1;i<=t;s=to[s],++i);
else for(register int i=1;i<=t+dis[s];++i,s=to[s]);
printf("%d\n",s);
}
return 0;
}