显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
int n;
int p[1000005];
int d[1000005];
int c[1000005];
int nxt[1000005];
int dsu[1000005];
int root(int x) {
while (dsu[x] != x)
x = dsu[x] = dsu[dsu[x]];
return x;
}
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 >> p[i], d[i] = d[p[i]] + 1, c[p[i]]++, nxt[p[i]] ^= i, dsu[i] = i;
for (int i = 0; i < n; i++)
if (c[i] == 1)
dsu[nxt[i]] = i;
for (int x; cin >> x; ) {
cout << d[root(x)] << '\n';
while (x != 0 && c[x] == 0)
nxt[p[x]] ^= x, c[x = p[x]]--;
if (c[x] == 1)
dsu[nxt[x]] = x;
}
return 0;
}