Advertisement
smatskevich

Seminar2

Feb 20th, 2023
618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct Node {
  5.   int Parent = 0;
  6.   std::vector<int> Children;
  7.   int Height = 0;
  8. };
  9.  
  10. void DFS(int v, std::vector<Node>& tree) {
  11.   for (int u : tree[v].Children) {
  12.     DFS(u, tree);
  13.     tree[v].Height = std::max(tree[v].Height, tree[u].Height + 1);
  14.   }
  15. }
  16.  
  17. int Diametr(std::vector<Node>& tree) {
  18.   int result = 0;
  19.   for (int i = 0; i < tree.size(); ++i) {
  20.     if (tree[i].Children.empty()) continue;
  21.     if (tree[i].Children.size() == 1) {
  22.       result = std::max(result, tree[i].Height);
  23.     } else {
  24.       std::pair<int, int> best = {tree[tree[i].Children[0]].Height, tree[tree[i].Children[1]].Height};
  25.       if (best.first > best.second) std::swap(best.first, best.second);
  26.       for (int j = 2; j < tree[i].Children.size(); ++j) {
  27.         if (tree[tree[i].Children[j]].Height >= best.second) {
  28.           best.first = best.second;
  29.           best.second = tree[tree[i].Children[j]].Height;
  30.         } else if (tree[tree[i].Children[j]].Height >= best.first) {
  31.           best.first = tree[tree[i].Children[j]].Height;
  32.         }
  33.       }
  34.       result = std::max(result, best.first + best.second + 2);
  35.     }
  36.   }
  37.   return result;
  38. }
  39.  
  40. int main() {
  41.   int n = 0; std::cin >> n;
  42.   std::vector<Node> tree(n);
  43.   for (int i = 0; i < n - 1; ++i) {
  44.     int a, b; std::cin >> a >> b;
  45.     if (a > b) std::swap(a, b);
  46.     tree[b].Parent = a;
  47.     tree[a].Children.push_back(b);
  48.   }
  49.  
  50.   DFS(0, tree);
  51.  
  52.   for (int i = 0; i < n; ++i) {
  53.     std::cout << i << ": [Height=" << tree[i].Height << "], [Children=";
  54.     for (int& x : tree[i].Children) std::cout << x << ",";
  55.     std::cout << "]\n";
  56.   }
  57.  
  58.   std::cout << Diametr(tree);
  59.  
  60.   return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement