因为不用回到起点,最后停的点一定是最远的点,所以距离即为2*当前所有路径长度-当前最长路径长度
#include<bits/stdc++.h>
using namespace std;
int n,m;
const int N=1e5+5;
int fa[N];
bool vis[N];
int cnt;
int d[N];
int h[N],e[N],ne[N],idx;
int maxn=-1;
int rt;
void add(int a,int b){
e[idx]=b;
ne[idx]=h[a];
h[a]=idx++;
}
void bfs(){
queue<int> q;
q.push(rt);
d[rt]=0;
while(!q.empty()){
int u=q.front();q.pop();
for(int i=h[u];~i;i=ne[i]){
int j=e[i];
if(vis[j]) continue;
vis[j]=true;
d[j]=d[u]+1;
q.push(j);
}
}
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof h);
for(int i=1;i<=n;i++){
cin>>fa[i];
if(fa[i]==-1) rt=i;
add(fa[i],i);
}
bfs();
memset(vis,false,sizeof vis);
vis[rt]=true;
while(m--){
int x;cin>>x;
while(!vis[x]){
maxn=max(maxn,d[x]);
cnt++;
vis[x]=true;
x=fa[x];
}
cout<<2*cnt-maxn<<endl;
}
}