fork download
  1. #include <algorithm> // max_element
  2. #include <functional> // function
  3. #include <iostream>
  4. #include <iterator> // istream_iterator
  5. #include <vector>
  6.  
  7. int main()
  8. {
  9. // get the number of nodes
  10. size_t n;
  11. if (!(std::cin >> n))
  12. return 1;
  13.  
  14. // read nodes from stdin
  15. std::istream_iterator<int> nodes{std::cin}, eof;
  16. std::vector<int> a(nodes, eof); // a[i] is the parent of an i node, -1 is root
  17. if (a.size() != n)
  18. return 2;
  19.  
  20. // find all depths for each i node
  21. std::vector<int> d(n); // d[i] -- depth of i node
  22. std::function<int(size_t)> depth = [&](size_t i) -> int {
  23. if (!d[i])
  24. d[i] = (a[i] == -1) ? 1 : 1 + depth(a[i] - 1);
  25. return d[i];
  26. };
  27. for (size_t i = 0; i < n; ++i)
  28. depth(i);
  29.  
  30. // find max depth
  31. auto it = std::max_element(std::begin(d), std::end(d));
  32. std::cout << ((it == std::end(d)) ? 0 : *it);
  33. }
Success #stdin #stdout 0s 16064KB
stdin
5
-1
1
2
1
-1
stdout
3