For distinct vertices , define
This function satisfies the triangle inequality.
Suppose the vertices occur from left to right in the order . Every consecutive coordinate gap is at least . Conversely, setting the consecutive gaps equal to these values satisfies every pairwise constraint by the triangle inequality. The problem is therefore the shortest Hamiltonian path problem in the metric .
Contract all edges of weight . The resulting graph is a tree whose edges all have weight . Let be the number of original vertices represented by a vertex of , and let be its degree in .
Expand every transition between different components into its path in . This gives a walk covering . If its first and last components are and , let be their path. Every edge on is traversed at least once, and every other edge at least twice.
Two extra traversals of an edge cost and add at most one usable visit at each endpoint. Each additional original vertex placed during the same visit also costs , so extra edge traversals cannot improve the answer. It is sufficient to traverse every edge on once and every other edge twice.
In such a walk, a component is visited times if it is an internal vertex of , and times otherwise. Original vertices exceeding this number cost one each because they must be placed consecutively within their component.
Define
Making an internal vertex of adds one to the cost exactly when . Call such a vertex marked. The answer for a path is
Thus, maximize the parenthesized benefit.
Root arbitrarily. Let be the maximum benefit of a path having as one endpoint and going into the subtree of . An arm through a child has value
Keeping the two largest child arms checks both paths ending at and paths passing through . Process an iterative DFS order in reverse to avoid recursion depth issues.
If has only one vertex, all pairwise distances are , so the answer is .
The time complexity is , and the space complexity is .
In subtask 1, if the tree diameter is , the answer is . In subtask 2, enumerate the starting vertex and traverse the contracted tree to evaluate every path benefit in time.