6823 Counting substhreengs
Substrings are strings formed by choosing a subset of contiguous characters from a string. This is well
known. A little more obscure is the definition of substhreengs. A substhreeng is a substring which
complies to the following additional requirements:
It is non-empty, and composed entirely of base 10 digits.
Interpreted in base 10 (allowing extra leading zeros), the resulting integer is a multiple of 3.
For instance, the string “130a303” contains 9 substhreengs: the substhreeng ‘3’ three times, the
substhreengs ‘30’ and ‘0’ twice each, and the substhreengs ‘303’ and ‘03’ once each. The substring
‘30a3’ is not a substhreeng because it is not composed entirely of base 10 digits, while the substring
‘13’ is not a substhreeng because 13 is not a multiple of 3.
Notice that two substhreengs are considered different if they are different in length or start at a
different position, even if the selected characters are the same.
Given a string, you are asked to count the number of substhreengs it contains.
Input
The input contains several test cases; each test case is formatted as follows. A test case consists of a
single line that contains a non-empty string S of at most 106
characters. Each character of S is either
a digit or a lowercase letter.
Output
For each test case in the input, output a line with an integer representing the number of substhreengs
contained in S.
Sample Input
130a303
0000000000
icpc2014regional
Sample Output
9
55
2
题意:
求一个串中,十进制并且能够被三整除的子串有多少个
第一个样例:130a303
满足的子串有9个,30,3,0,3,0,3,30,03,303
代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <map>
#include<stack>
using namespace std;
#define ll long long
#define eps 0.001
#define PI acos(-1.0)
#define memset(a,b) memset(a,b,sizeof(a))
int main()
{
ll num[4]; //记录到当前位置时前面子串中和分别为012的个数
string s;
ll ans;
while(cin>>s)
{
ans=0;
memset(num,0);
int len=s.size();
ll a,b,c;
for(int i=0;i<len;i++)
{
int x=s[i]-'0';
if(x>=0&&x<=9)
{
int flag=x%3;
if(flag==0)
{
a=num[0]+1; //前面子串中余数为0的个数加上当前数字本身
b=num[1];
c=num[2];
}
else if(flag==1)
{
a=num[2];//当前数字为1时加上前面和为2的个数可以凑成和为3的
b=num[0]+1;//前面为0的加上当前这个数字本身
c=num[1];//前面为1的加上当前这个1和为2
}
else
{
a=num[1];
b=num[2];
c=num[0]+1;
}
}
else
{
a=0;
b=0;
c=0;
}
num[0]=a;
num[1]=b;
num[2]=c;
ans+=num[0];
}
printf("%lld\n",ans);
}
return 0;
}