2019牛客暑期多校训练营(第四场)K.number

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.

示例1

输入

600

输出

4

示例2

输入

123000321013200987000789

输出

55

典型的 DP ~
这题可以利用 300 的性质来优化算法,300既是 3 的倍数又是 100 的倍数,而 3 的倍数只需判断各位数字之和即可,100 的倍数只要有连续两个 0 即可(注意单个 0 也可以),那么只需要判断 3 的倍数,那么只需记录前缀和对 3 取模的个数累加即可,AC代码如下:

#include
using namespace std;
typedef long long ll;
char s[100005];
ll cnt[3]={
     0},ans=0;
int main()
{
     
    scanf("%s",s);
    int sum=0;
    cnt[0]=1;
    for(int i=0;s[i]!='\0';i++){
     
        if(s[i]=='0') ans++;
        if(s[i]=='0'&&s[i+1]=='0') ans+=cnt[sum];
        sum=(sum+s[i]-'0')%3;
        cnt[sum]++;
    }
    printf("%lld\n",ans);
}

你可能感兴趣的:(动态规划,思维,牛客)