显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1000010;
int n,m,ans,a[N],t[N],dep[N];
int head[N],tot;
struct edge {
int v,nxt;
}e[N];
void add (int u,int v) {
e[++tot].v=v;
e[tot].nxt=head[u];
head[u]=tot;
}
void dfs1 (int u) {
dep[u]=dep[a[u]]+1;
if (!t[u]) m++;
for (int i=head[u];i;i=e[i].nxt) dfs1(e[i].v);
}
void dfs2 (int u) {
if (t[u]) {
ans=dep[u]+1;
return;
}
if (u==0) {
ans=0;
return;
}
t[a[u]]--;
dfs2(a[u]);
}
int main () {
freopen("Vocabulary.in","r",stdin);
freopen("Vocabulary.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> n;
for (int i=1;i<=n;i++) {
cin >> a[i];
t[a[i]]++;
add(a[i],i);
}
dep[0]=-1;
dfs1(0);
for (int i=1;i<=m;i++) {
int x;
cin >> x;
dfs2(x);
cout << ans <<endl;
}
return 0;
}