记录编号 605991 评测结果 AAAAAAAAAAAAAAAAAA
题目名称 4176.[USACO25 Feb Silver]Vocabulary Quiz 最终得分 100
用户昵称 Gravatar彭欣越 是否通过 通过
代码语言 C++ 运行时间 9.322 s
提交时间 2025-09-13 16:37:20 内存使用 19.30 MiB
显示代码纯文本
#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;
}