首页 > 其他 > 详细

[AtCoder] Multiple of 2019

时间:2020-05-13 09:29:31      阅读:80      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/lz87/p/12866628.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!