公式

D - Iroha and Haiku (New ABC Edition) 解説 by en_translator


This problem can be solved with cumulative sums and binary search.

Compute the cumulative sums \(S_0=0,\ S_i=A_0+\ldots+A_{i-1}\) firsthand. Then you can find the sum of an arbitrary subsegment of \(A\) in an \(O(1)\) by \(S_R-S_L=A_L+A_{L+1}+\ldots+A_{R-1}\).

The given conditions can be rephrased in terms of cumulative sums as follows:

  • \(S_y-S_x=P\)
  • \(S_z-S_y=Q\)
  • \(S_w-S_z=R\)

Since \(A_i>0\) for all \(i\), \(S_i\) is monotonically increasing, so for a fixed \(x\), we can find \(y\) such that \(S_y-S_x=P\) i.e. such that \(S_y=S_x+P\) in an \(O(\log N)\) time using binary search. Since \(z\) and \(w\) can be found with binary search too, we can check the conditions for each fixed \(x\) in an \(O(\log N)\) time. By exhaustively searching over \(x\), we can solve this problem in a total of \(O(N\log N)\) time.

In the implementation, you can store \(S\) in a set so that you don’t need an explicit binary search.

Sample code (C++)

投稿日時:
最終更新: