公式

E - Wheel Distance 解説 by en_translator 印刷ページ


Call vertex \((N+1)\) the center. We will define several notations.
Define the prefix sums \(P_0, P_1, \dots, P_N\) of \(A\) as:

\[P_0 = 0, P_1 = \sum_{j=1}^i A_i.\]

One can find \(P_0, P_1, \dots, P_N\) in \(\mathrm{O}(N)\) time.

Also, for \(1 \leq v \leq N\), let \(D_b\) be the shortest distance from the center to vertex \(v\).
\(D_1, D_2, \dots, D_N\) can be computed in a total of \(\mathrm{O}(N \log N)\) time by Dijkstra’s algorithm. (One can even solve it in \(\mathrm{O}(N)\); think of it if you are interested.)

The queries can be answered fast based on this information. Specifically, given \(S\) and \(T\), the answer is

\[\min(x, P_N - x, D_S + D_T)\]

where

\[x = \vert P_{S-1} - P_{T-1} \vert.\]

(Proof) We consider cases where an \(ST\) path passes or does not pass the center.
If the path passes the center, it is optimal to travel from vertex \(S\) to the center with the shortest distance, and then travel from the center to vertex \(T\) with the shortest distance. In this case, the total distance is \(D_S + D_T\).
If the path does not passes the center, it is optimal to traverse the circumference either clockwise or counterclockwise; one corresponds to \(x\), and the other to \(P_N - x\).
Hence, the answer is the minimum value of these three. (End of proof)

By this algorithm, the answer can be found in \(\mathrm{O}(N \log N)\) time, which is fast enough.

投稿日時:
最終更新: