structNode { int first = 0; int second = 0; bool visited = false; vector<Node*> successors; };
classTree { private: Node* root;
inttraverse(Node* node, int& first){ node->visited = true; bool hasChild = false; int maxLen = 0, maxFir = 0, secFir = 0; for (int i = 0; i < node->successors.size(); i++) { if (node->successors[i]->visited == false) { hasChild = true; int fir = 0; maxLen = max(maxLen, traverse(node->successors[i], fir)); if (maxFir <= fir) { secFir = maxFir; maxFir = fir; } else secFir = max(secFir, fir); } } if (hasChild) { first = maxFir + 1; maxLen = max(maxLen, maxFir + secFir + 2); }
return maxLen; }
public: Tree(Node* node) { root = node; }
intlongestPath(){ int first = 0; returntraverse(root, first); } };
intmain(){ int N = 0; cin >> N; Node* nodes = new Node[N]; for (int i = 0; i < N - 1; i++) { int a = 0, b = 0; cin >> a >> b; nodes[a - 1].successors.push_back(nodes + b - 1); nodes[b - 1].successors.push_back(nodes + a - 1); } Tree tree = Tree(nodes); cout << tree.longestPath();