Official

F - Add One Edge 3 Editorial by en_translator


First, find the diameter of \(G_1\) and \(G_2\), denoted by \(d_1\) and \(d_2\), respectively.

When an edge between vertices \(i\) and \(j\) is added to the graph, the diameter either remains \(\max(d_1,d_2)\) or becomes the path that contains the new edge.

The longest path containing the new edge consists of three parts: the path from vertex \(i\) to the furthest vertex from vertex \(i\) in \(G_1\), the added edge, and the path from vertex \(j\) to the furthest vertex from vertex \(j\) in \(G_2\).

Therefore, we calculate the distance to the furthest vertex from each vertex. Let \(A_{i}\) be that distance from vertex \(i\) in \(G_1\), and \(B_j\) be that distance from vertex \(j\) in \(G_2\). Then the diameter for given \(i\) and \(j\) is represented as \(\max(\max(d_1,d_2), A_i+B_j+1)\).

Caveat: we briefly describe how to find \(A\) and \(B\). The algorithm to find a diameter also yields its two endpoints. Denoting them by \(u\) and \(v\), \(A_i\) can be found as \(\max(\mathrm{dist}(u,i),\mathrm{dist}(v,i))\). (Brief proof: assuming that \(A_i\) is greater than \(\mathrm{dist}(u,i),\mathrm{dist}(v,i)\) contradicts with the definition of diameter.)

Now we consider how to find the desired sum.

When \(A\) and \(B\) are sorted in ascending order, the range of values \(j\) such that \(A_i+B_j+1 \geq \max(d_1,d_2)\) monotonically shrinks, so we can use the sliding window technique. One may also perform a binary search for each step. In any way, the sought sum can be evaluated fast enough.

posted:
last update: