题意:长度为n,n<=1e5的string 合法字串为不含前缀0&&能被6整除,求string的合法字串个数
能被6整除 即既能被2和3整除 则该数末尾为偶数&&各位数之和被3整除
dp[i][m] 以i开头的子串,mod3为m && 以偶数结尾的个数
x=s[i], dp[i][(m+x)%3]=dp[i+1][m]+x%2==0?:x%3 i和i+1相连或者单独一个s[i]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+20;
char s[N];
ll dp[N][5];
int main()
{
while(scanf("%s",s+1)!=EOF)
{
ll ans=0;
int n=strlen(s+1);
memset(dp,0,sizeof(dp));
for(int i=n;i>=1;i--)
{
int x=s[i]-'0';
for(int m=0;m<3;m++)
{
dp[i][(m+x)%3]+=dp[i+1][m];
}
if(x%2==0)//单独一个si,ps:从第一个被赋值的dp值开始,保证了是以偶数结尾
dp[i][x%3]++;
if(s[i]=='0')
ans++;
else
ans+=dp[i][0];
}
cout<<ans<<endl;
}
return 0;
}
以下为官方solution
Solution #2
Let's iterate through all string and remember values of sum modulo 3 for all the prefixes, that are ending in even digit. We will save this values in array a[3]. After that iterate through all and find the number of valid strings starting in position :
- if , then only 1 string is valid starting in this digit
- in other case we need to find all the prefixes with position , that have same value of sum modulo 3, as - we can use precalculated array above for it.
Code by wild_hamster:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stdio.h>
#include <map>
#include <assert.h>
#define pdd pair<double,double>
#define pii pair<ll,ll>
#define MOD2 1000000009
#define INF ((ll)1e+18)
typedef long long ll;
typedef long double ld;
using namespace std;
ll i,j,n, flag,r,x,y,ans;
string s,t;
ll a[4];
void solveN()
{
cin >> s;
n = s.size();
for (i = 0; i < n; i++)
{
x = (x+s[i])%3;
if (s[i] % 2 == 0)
a[x]++;
}
x = 0;
for (i = 0; i < n; i++)
{
if (s[i] == '0')
ans++;
else
ans += a[x];
x = (x+s[i])%3;
if (s[i] % 2 == 0)
a[x]--;
}
cout << ans << endl;
}
int main() {
solveN();
return 0;
}