Solution - Prefix Sums + Math
Following the editorial, we build a prefix sum array on the existing array.
We know that subarray formed by is a good subarray iff .
Rearranging this equation leads to , so we build
a map (sum_dist) on values of for all valid .
Then, we iterate over all values of the map and check how many unordered pairs we can build with the number of values of that have the same value of .
Implementation
Time Complexity:
from collections import defaultdictfor _ in range(int(input())):arr_len = int(input())arr = [ord(i) - ord("0") for i in input()]pref_arr = [0] + arrfor 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!