AcWing 3422. 左孩子右兄弟
原题链接
中等
作者:
PBomb
,
2021-05-03 23:53:02
,
所有人可见
,
阅读 611
C++ 代码
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
int h[N], ne[N], e[N], idx;
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
int find(int x)
{
int cnt = 0, m = -1;
for(int i = h[x]; i != -1; i = ne[i])
{
cnt++;
int k = e[i];
m = max(m, find(k));
}
if(cnt == 0) return 1;
return m + cnt;
}
int main()
{
int n ;
cin >> n;
memset(h, -1, sizeof h);
for(int i = 2; i <= n; i++)
{
int x;
cin >> x;
add(x, i);
}
cout << find(1) - 1;
return 0;
}