[AtCoder] Multiple of 2019

Posted lz87

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 560] Subarray Sum Equals K

[LeetCode 1371] Find the Longest Substring Containing Vowels in Even Counts

 

以上是关于[AtCoder] Multiple of 2019的主要内容,如果未能解决你的问题,请参考以下文章

Atcoder 084D - Small Multiple(最短路径+思维)

Mynavi Programming Contest 2021(AtCoder Beginner Contest 201)

Mynavi Programming Contest 2021(AtCoder Beginner Contest 201)

Mynavi Programming Contest 2021(AtCoder Beginner Contest 201)E - Xor Distances

gcc: multiple definition of [转]

AtCoder ARC 101 D Median of Medians(逆序对)