Official

B - Subsegments with Small Sums Editorial by evima


To calculate \(f\) for a single interval, it is sufficient to perform a greedy algorithm that takes as much as possible from the left end.

To calculate \(f\) for all intervals, consider the behavior of the greedy algorithm starting from each \(l\).

For each \(i\), let \(p_i\) be the smallest \(j\) such that \(A_i + \cdots + A_j > S\) (if no such \(j\) exists, then set \(p_i = N+1\)).

Define \(dp[i] = \sum_{i \leq r} f(A[i,r])\). For convenience, let \(dp[N+1] = 0\).

We will determine \(dp[i]\) for \(i = N, N-1, \cdots, 1\) in this order.

Consider \(\sum_{i \leq r} f(A[i,r])\) by dividing it into cases where \(r < p_i\) and \(p_i \leq r\). For \(r < p_i\), it is clear that \(f(A[i,r]) = 1\). For \(p_i \leq r\), when considering the greedy algorithm mentioned above, we first take the interval \([i, p_i-1]\), and then start the greedy algorithm from \(p_i\). The result of starting from \(p_i\) is nothing other than \(dp[p_i]\). Summarizing the above, we find that \(dp[i] = dp[p_i] + (N+1-i)\).

Implementing the above operation as is, we can obtain a solution in \(O(N)\) or \(O(N \log N)\) time.

Sample Solution

posted:
last update: