Cut one weighted edge of a tree and reattach it elsewhere with the same weight; find the maximum possible diameter.
Medium7TreeDFSGreedyNo attempts yetTime limit2sMemory limit512 MBA tree T has N vertices, numbered 0 through N−1.
Hongjun deletes one edge of T and then adds one edge. The added edge must have the same weight as the deleted edge, and the graph must still be a tree afterwards. He may add back exactly the edge he deleted.
Write a program that finds the largest diameter among the trees Hongjun can build.
The first line contains the number of vertices N. (2≤N≤2000)
Each of the next N−1 lines contains one edge as three integers from, to, and cost, meaning the edge joining vertex from and vertex to has weight cost. (0≤from,to≤N−1, from=to, 1≤cost≤109)
The given graph is always a tree.
Print the largest diameter among the trees Hongjun can build.
The tree in the first example has 4 vertices and 3 edges. Its original diameter is the path between vertex 2 and vertex 3, of length 8+4=12. Delete the edge between vertex 1 and vertex 0, then join vertex 3 and vertex 1 with an edge of weight 2. The diameter becomes the path between vertex 2 and vertex 1, of length 8+4+2=14.
In the second example, adding back the deleted edge is optimal.