Official

E - Tree Distance Editorial by en_translator


Let \(A_{i,j} = A_{j,i}\) to define the distance for \(i > j\) too. Notice that by the constraints all edge weights are positive.

Consider actually constructing a conforming tree \(T\). Due to the properties that a tree must satisfy, \(T\) can be uniquely determined if it exists, and can be constructed by the following steps.

Regard vertex \(1\) as the root. Consider how we can identify, for each vertex \(i \ (i \ne 1)\), its parent \(p_i\) and the edge weight between the parent \(w_{i, p_i}\):

For any vertex \(i\), a vertex \(j\) is eligible as an ancestor of \(i\) if and only if \(A_{1,j} + A_{j,i} = A_{1,i}\). Let \(S_i\) be the set of vertices\(j \ (j \ne i)\) satisfying this condition.

Among the vertices in this set \(S_i\), only those satisfying \(\displaystyle p_i = \argmin_{j \in S_i} A_{i, j}\) is eligible as a parent of \(i\). The edge toward it has a weight \(w_{i, p_i} = A_{i,p_i}\).

If \(S_i\) is empty, there is no parent, so \(T\) cannot be constructed, and the answer is No. The answer is also No when there are multiple candidates of \(p_i\) (in which case we may just adopt an arbitrary tie-breaking, so that inconsistency is detected on the final verification).

By the steps above, one can obtain a candidate of tree \(T\) in \(O(N^2)\) time.

Finally, verify if the constructed tree actually satisfies the conditions. Perform a DFS (Depth-First Search) to check if the distances between all vertex pairs perfectly match with \(A\). The overall time complexity is \(O(N^2)\).

posted:
last update: