2019牛客暑期多校訓練營(第四場)- K - number

題目描述:

300iq loves numbers who are multiple of 300.
One day he got a string consisted of numbers. He wants to know how many substrings in the string are multiples of 300 when considered as decimal integers.
Note that leading and trailing zeros are allowed (both in original string and substrings you chose) and the same substring appearing in different places can be counted multiple times.
 
輸入描述:
 
A single line consisting a string consisted of characters '0' to '9'.
 
輸出描述:
 
The number of substrings that are multiples of 300 when considered as decimal integers.
 
樣例分析:
 
輸入:600
輸出:4
'600', '0', '0', '00' are multiples of 300. (Note that '0' are counted twice because it appeared two times)
 
題目大意:給定一個字符串,求出這個字符串有多少子串滿足其表示的數字%300等於0。給定的字符串長度不允許使用O(n^2)複雜度的方法,正解採用的是O(n)複雜度的算法。
 
附上代碼:
#pragma GCC optimize(3)
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<array>
#include<string>
#include<cstring>
#include<cmath>
#include<cassert>
#include<cstdlib>
#include<utility>
#include<iterator>
using namespace std;
typedef long long ll;
char s[100005];//字符串
int cn[3];//記錄%3後爲0,1,2的數量
int sum[100005],n;//sum爲%3前綴和
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);
    cin>>(s+1);
    n = strlen(s+1);
    for(int i = 1;i<=n;i++)
    {
        sum[i] = (sum[i-1]+(s[i]-'0'))%3;
    }//構造前i位的和%3
    ll ans = 0;
    for(int i = 1;i<=n;i++)
    {
        //該區間滿足末尾兩位是0且整個串是3的倍數
        if(s[i]=='0')
        {
            ans++;
            if(s[i-1]=='0')
            {
                ans+=cn[sum[i]];
            }
        }
        cn[sum[i-1]]++;
    }
    cout<<ans<<endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章