Number
链接:https://ac.nowcoder.com/acm/contest/884/K
problem
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
说明
‘600’, ‘0’, ‘0’, ‘00’ are multiples of 300. (Note that ‘0’ are counted twice because it appeared two times)
示例2
输入
123000321013200987000789
输出
55
题意
给一个数字组成的字符串,找出300倍数的的子串个数,包括0、00,即考虑前导0的情况(前导 0 就是说无用的 0 也算,例如 “ 000 ”,其中前两个0都是没有用的情况)
分析
要成为300的倍数,即即是3的倍数又是100的倍数,3的倍数则要加起来各个数的和是3的倍数,而要成为100的倍数,则至少有两个连续的0,当遇到两个连续的 0 的时候,考虑前面所有的数的和 %3 的结果的个数,将其加到总和( 计算子串,例如:13300,其中每一位的前缀和 mod 3 的结果都是1,所能截出来的子串为 300、3300,再加上00 )
代码
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int M=1e5+5;
char s[M];
int main()
{
while(~scanf("%s",s+1))
{
int len=strlen(s+1),sum=0,num[3]={0};
ll ans=0;
num[0]=1;
for(int i=1;i<=len;i++){
sum=(sum+s[i])%3;
if(s[i]=='0'&&s[i+1]=='0'){
ans+=num[sum]-1+1;
}
if(s[i]=='0') ans++;
num[sum]++;
}
printf("%lld\n",ans);
}
return 0;
}
//123000321013200987000789 55