[题解]AT_abc158_e [ABC158E] Divisible Substring

· · 题解

更好的阅读体验

思路

首先发现一个事情,任意一个子串都可以由 s 的某一个后缀的后面删除一些字符得到。

因此假如 s 的某一个后缀的值为 x,那么我们可以减去后面的我们不用的数字 a,然后除以 10 的若干次幂得到,即 \frac{x - a}{10^n}。

于是得到:

\frac{x - a}{10^n} \equiv 0 \pmod p

可以推出:

x \equiv a \pmod p

因此考虑处理后缀模 p 的结果,同时用桶存起来即可。

注意到有可能 a 比 x 大的情况,因此需要把这种情况删掉;同时注意到当 p = 2/5 时,\frac{x - a}{10^n} \bmod p 不存在(因为 10 与 p 不互质了),需要特殊处理。

Code

#include <bits/stdc++.h>
#define re register
#define int long long

using namespace std;

const int N = 2e5 + 10;
int n,p,ans;
char s[N];
vector<int> v[N];

inline int read(){
    int r = 0,w = 1;
    char c = getchar();
    while (c < '0' || c > '9'){
        if (c == '-') w = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9'){
        r = (r << 3) + (r << 1) + (c ^ 48);
        c = getchar();
    }
    return r * w;
}

inline void solve1(){
    for (re int i = 1;i <= n;i++){
        if ((s[i] - '0') % p == 0) ans += i;
    }
}

inline void solve2(){
    for (re int i = n,x = 0,mul = 1;i;i--,mul = mul * 10 % p){
        x = (x + mul * (s[i] - '0')) % p;
        if (!x) ans++;
        v[x].push_back(i);
    }
    for (re int i = 0;i < p;i++) sort(v[i].begin(),v[i].end());
    for (re int i = n,x = 0,mul = 1;i;i--,mul = mul * 10 % p){
        x = (x + mul * (s[i] - '0')) % p;
        ans += (upper_bound(v[x].begin(),v[x].end(),i) - v[x].begin() - 1);
    }
}

signed main(){
    n = read(),p = read(),scanf("%s",s + 1);
    if (p == 2 || p == 5) solve1();
    else solve2(); 
    printf("%lld",ans);
    return 0;
}