fork download
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3.  
  4. using namespace std;
  5.  
  6. const int MOD = 1e9 + 7;
  7.  
  8. void solve(){
  9. int n;
  10. cin >> n;
  11.  
  12. vector<vector<int>> g(n + 1, vector<int>());
  13.  
  14. for(int i = 2; i <= n; i++){
  15. int x;
  16. cin >> x;
  17. g[x].push_back(i);
  18. }
  19.  
  20. int ans = n;
  21. vector<int> dp(n + 1, 0);
  22. auto dfs = [&](int x, auto && self) -> void {
  23. for(auto y: g[x]){
  24. self(y, self);
  25. }
  26.  
  27. vector<int> p;
  28.  
  29. for(auto y: g[x]){
  30. p.push_back(dp[y]);
  31. }
  32. if(!p.size())return;
  33. sort(p.begin(), p.end());
  34. dp[x] = p.back() + 1;
  35. int cur = 1;
  36. for(int i = p.size() - 2; i >= 0; i--){
  37. dp[x] = max(dp[x], p[i] + cur);
  38. if(i >= 1)cur++;
  39. }
  40. };
  41. dfs(1, dfs);
  42.  
  43. cout << dp[1] << "\n";
  44. }
  45.  
  46. int main(){
  47. ios_base::sync_with_stdio(false);
  48. cin.tie(nullptr);
  49.  
  50. int t = 1;
  51. cin >> t;
  52.  
  53. for(int i = 1; i <= t; i++){
  54. solve();
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 5288KB
stdin
5
6
1 2 2 1 1
15
1 1 2 2 3 3 4 4 5 5 6 6 7 7
5
1 2 2 2
7
1 1 2 1 1 2
10
1 1 1 2 2 2 4 3 3
stdout
2
3
3
3
3