[AtCoder] Multiple of 2019
Problem Link: Multiple of 2019
Key idea: For subarray S[i1, j] and S[i2, j] with i1 < i2, if the V[i1, j] % 2019 is the same with V[i2, k] % 2019, it means that V[i1, j] - V[i2, j] == V[i1, i2] must be a multiple of 2019.
1. Instead of using prefix subarray, we use suffix subarray here for easier math computation. From right to left, compute the current suffix S[i, N - 1] value V. Because the given input is up to 10^5 digits, we should use modular operation here: any numbers modular by 2019 fits inside an array of size 2019.
2. Then count how many V we already have in the modular map array. This is how many pairs we can have using the current digit as the leading digit toward the final answer.
3. update the current power, apply module 2019 on it as well.
4. update modular map array's V count by 1.
One important thing here is that modular map array value at index 0 must be initialized to 1. This represents an empty suffix array having value 0, contributing a modular result of 0 one time.
private static void solve(int q, FastScanner in, PrintWriter out) { for (int qq = 0; qq < q; qq++) { String s = in.next(); long ans = 0; int MOD = 2019; int[] cnt = new int[MOD]; cnt[0] = 1; int suffix = 0; int pow = 1; for(int i = s.length() - 1; i >= 0; i--) { suffix = (suffix + pow * (s.charAt(i) - '0')) % MOD; pow = pow * 10 % MOD; ans += cnt[suffix]; cnt[suffix]++; } out.println(ans); } out.close(); }
Related Problems
[LeetCode 525] Contiguous Array
[LeetCode 560] Subarray Sum Equals K
[LeetCode 1371] Find the Longest Substring Containing Vowels in Even Counts