Official Editorial (Python)

Solution - Prefix Sums + Math

Following the editorial, we build a prefix sum array pp on the existing array.

We know that subarray formed by [l,r)[l, r) is a good subarray iff rl=prplr-l=p_r-p_l. Rearranging this equation leads to prr=pllp_r-r=p_l-l, so we build a map (sum_dist) on values of piip_i-i for all valid ii.

Then, we iterate over all values of the map and check how many unordered pairs we can build with the number of values of ii that have the same value of piip_i-i.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log N)

from collections import defaultdict
for _ in range(int(input())):
arr_len = int(input())
arr = [ord(i) - ord("0") for i in input()]
pref_arr = [0] + arr
for i in range(1, len(pref_arr)):
pref_arr[i] += pref_arr[i - 1]

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!