//dp[j]:以j为根节点的子树的最大深度
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int N=1e5+9;
int dp[N],n;
vector<int> e[N];
void dfs(int x)
{
for(const auto& y : e[x])
{
dfs(y);
dp[x]=max(dp[x],(int)e[x].size()+dp[y]);
}
}
int main()
{
cin>>n;
for(int i=2;i<=n;i++)//因为第一个结点是没有父节点的
{//不存在x是i=1的父节点
int x;cin>>x;
e[x].push_back(i);
}
dfs(1);
cout<<dp[1]<<endl;
return 0;
}

//将dp[i]最大的放在最后一个能够使得i+dp[i]最大
//从表达式来看 高度等于结点到根的距离+子树深度
//dp[i]表示 i的最大深度
//将i放在后面使得 i 最大 dp[i]也最大
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n,dp[N];
//dp[i]定义:以i为根节点的子树最大深度
vector<int>a[N];
void dfs(int x) // x表示当前正在访问的节点编号
{
for(const auto &y : a[x]) // 遍历节点x的所有邻接节点y
{
dfs(y); // 对邻接节点y递归调用dfs函数,继续深度优先搜索
//收集所有子结点的情况
dp[x] = max(dp[x], (int)a[x].size() + dp[y]);
//考虑所有子结点的深度取最大值
//a[x].size()会更新值
}
}
int main() {
cin >> n;
for(int i=2;i<=n;i++)//输入某点的父节点编号
{
int x;cin>>x;
a[x].push_back(i);
}
dfs(1);
cout << dp[1]<<endl;
return 0;
}

7502

被折叠的 条评论
为什么被折叠?



