Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <vector>
- // 0
- // 1 3 4
- // 2 5
- // 6 7 8
- // 9
- // 0 1 0 3 0 4 1 2 3 5 2 6 2 7 2 8
- struct TreeNode {
- int Parent = 0;
- int Depth = 0;
- std::vector<int> Children;
- };
- void CalcDepth(std::vector<TreeNode>& nodes, int a) {
- for (auto x : nodes[a].Children) {
- CalcDepth(nodes, x);
- nodes[a].Depth = std::max(nodes[a].Depth, nodes[x].Depth + 1);
- }
- }
- int FindMaxPath(std::vector<TreeNode>& nodes) {
- int result = 0;
- for (auto& node : nodes) {
- if (node.Children.size() <= 1)
- result = std::max(result, node.Depth);
- else {
- std::sort(node.Children.begin(), node.Children.end(), [&nodes](int l, int r) {
- return nodes[l].Depth > nodes[r].Depth;
- });
- auto first = node.Children.begin();
- result = std::max(result, nodes[*first].Depth + nodes[*(first + 1)].Depth + 2);
- }
- }
- return result;
- }
- int main() {
- int n = 0;
- std::cin >> n;
- // Вектор из n узлов.
- std::vector<TreeNode> nodes(n);
- for (int i = 1; i < n; ++i) {
- int a = 0, aa = 0;
- std::cin >> a >> aa;
- if (a > aa) std::swap(a, aa);
- nodes[a].Children.push_back(aa);
- nodes[aa].Parent = a;
- }
- CalcDepth(nodes, 0);
- std::cout << FindMaxPath(nodes) << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement