題目鏈接
思路:
設爲構成的十進制數。
若構成的十進制數是p的倍數,則:
如果的話,是非零的,所以,即
那麼直接記錄一下後綴的十進制表示%p後的值出現次數就可以了。
即p=2或5的時候,直接跑個dp就好了。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
#define fi first
#define se second
#define pb push_back
int n,p;
char a[N];
LL vis[N];
LL f[N][10];
int main() {
ios::sync_with_stdio(false);
cin>>n>>p>>a+1;
if(p>=10){
int pre=0;
LL ans=0;vis[0]=1;
LL c=1;
for(int i=n;i>=1;i--,c=c*10%p){
pre=(pre+(a[i]-'0')*c)%p;
ans+=vis[pre];
vis[pre]++;
}
cout<<ans<<'\n';
}else{
LL ans=0;
for(int i=1;i<=n;i++){
for(int j=0;j<p;j++){
f[i][(j*10+a[i]-'0')%p]+=f[i-1][j];
}
f[i][(a[i]-'0')%p]++;
ans+=f[i][0];
}
cout<<ans<<'\n';
}
return 0;
}