Advertisement
smatskevich

Seminar3

Feb 24th, 2022
724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. //        0
  6. //   1      3   4
  7. //   2      5
  8. // 6 7 8
  9.  
  10. // 9
  11. // 0 1   0 3   0 4   1 2   3 5   2 6   2 7   2 8
  12.  
  13. struct TreeNode {
  14.   int Parent = 0;
  15.   int Depth = 0;
  16.   std::vector<int> Children;
  17. };
  18.  
  19. void CalcDepth(std::vector<TreeNode>& nodes, int a) {
  20.   for (auto x : nodes[a].Children) {
  21.     CalcDepth(nodes, x);
  22.     nodes[a].Depth = std::max(nodes[a].Depth, nodes[x].Depth + 1);
  23.   }
  24. }
  25.  
  26. int FindMaxPath(std::vector<TreeNode>& nodes) {
  27.   int result = 0;
  28.   for (auto& node : nodes) {
  29.     if (node.Children.size() <= 1)
  30.       result = std::max(result, node.Depth);
  31.     else {
  32.       std::sort(node.Children.begin(), node.Children.end(), [&nodes](int l, int r) {
  33.         return nodes[l].Depth > nodes[r].Depth;
  34.       });
  35.       auto first = node.Children.begin();
  36.       result = std::max(result, nodes[*first].Depth + nodes[*(first + 1)].Depth + 2);
  37.     }
  38.   }
  39.   return result;
  40. }
  41.  
  42. int main() {
  43.   int n = 0;
  44.   std::cin >> n;
  45.   // Вектор из n узлов.
  46.   std::vector<TreeNode> nodes(n);
  47.   for (int i = 1; i < n; ++i) {
  48.     int a = 0, aa = 0;
  49.     std::cin >> a >> aa;
  50.     if (a > aa) std::swap(a, aa);
  51.     nodes[a].Children.push_back(aa);
  52.     nodes[aa].Parent = a;
  53.   }
  54.  
  55.   CalcDepth(nodes, 0);
  56.   std::cout << FindMaxPath(nodes) << std::endl;
  57.   return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement