fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void solve() {
  6. int t;
  7. cin >> t;
  8. while (t--) {
  9. int n;
  10. cin >> n;
  11. vector<vector<int>> tree(n + 1);
  12. for (int i = 2; i <= n; ++i) {
  13. int p;
  14. cin >> p;
  15. tree[p].push_back(i);
  16. }
  17.  
  18. vector<int> depth(n + 1, 0);
  19.  
  20. // Define dfs as a lambda function
  21. function<void(int)> dfs = [&](int u) {
  22. vector<int> child_depths;
  23. for (int v : tree[u]) {
  24. dfs(v);
  25. child_depths.push_back(depth[v]);
  26. }
  27. if (child_depths.empty()) {
  28. depth[u] = 1;
  29. } else {
  30. sort(child_depths.rbegin(), child_depths.rend()); // Sort in decreasing order
  31. int max_temp = 0;
  32. for (int i = 0; i < child_depths.size(); ++i) {
  33. int temp = child_depths[i] + i;
  34. if (temp > max_temp) {
  35. max_temp = temp;
  36. }
  37. }
  38. depth[u] = max_temp;
  39. }
  40. };
  41.  
  42. dfs(1);
  43. cout << depth[1] << '\n';
  44. }
  45. }
  46. int main() {
  47. ios::sync_with_stdio(false);
  48. cin.tie(nullptr);
  49. solve();
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5280KB
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
3
4
3
4
3