通过观察可知,题目本质上是让我们去求树的高度,假如有多个最高层,则有多棵树,求最高的那棵树的高度,因为存在一种方案,使得树的每一高度都分为一个小组,而低矮的树可以合并到高的树当中

#include <bits/stdc++.h>
#define int long long
using namespace std;
#define endl '\n'
#define pb push_back
#define ull unsigned long long
#define all(a) a.begin(), a.end()
#define vi vector<int>
#define vii vector<vector<int>>
#define fi first 
#define se second
#define vs vector<string>
#define eb emplace_back
#define in insert
#define pf push_front
const int inf = 2e18 + 9 ;
const int mod1 = 1e9 + 7 ; 
const int mod2 = 998244353 ; 
typedef pair<int, int> pll;
typedef long double db;

inline int gcd(int a , int b) {return b ? gcd(b , a % b) : a;};
template<class T>inline void read(T &res){char c;T flag=1;while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;res=c-'0';while((c=getchar())>='0'&&c<='9')res=res*10+c-'0';res*=flag;}
inline int qsm(int a , int b){int res = 1 ; while(b){if(b & 1){res *= a ; }b >>= 1 ; a *= a ; }return res ; }
int dir[4][2] = {{1 , 0} , {-1 , 0} , {0 , 1} , {0 , -1}};
int dirx[8] = {-1, -1, -1, 0, 0, 1, 1, 1}; 
int diry[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int n ; 
int ans = 1 ;
vi dp; 
void dfs(int root , vii &a)
{
    for(int i = 0 ; i < a[root].size() ; i++)
    {
        dp[a[root][i]] = dp[root] + 1 ;
        ans = max(ans , dp[a[root][i]]);
        dfs(a[root][i] , a);
    }
}
void work() 
{
    cin >> n ;
    vii a(n + 1);
    dp.resize(n + 1 , 1);
    vi root ; 
    for(int i = 1 ; i <= n ; i++)
    {
        int x ; cin >> x ; 
        if(x == -1)
        {
            root.pb(i); 
        }
        else 
        {
            a[x].pb(i) ; 
        }
    }
    for(int i = 0 ; i < root.size() ; i++)
    {
        dfs(root[i] , a);
    }
    cout << ans << endl ; 
}
signed main() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    while (t--) 
    {
        work();
    }
    return 0;
}