码迷,mamicode.com
首页 > 其他好文 > 详细

[AtCoder] Multiple of 2019

时间:2020-05-13 09:38:43      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:related   ++   class   ann   already   rom   ble   represent   number   

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

标签:related   ++   class   ann   already   rom   ble   represent   number   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!