题意简述
求l~r之间存在长度至少为2的回文子串的正整数的个数
题解思路
数位DP
注意到有偶数长度的回文串必有长度为2的回文串,有奇数长度的回文串必有长度为3的回文串
所以只需判断与前一位,前两位是否相等即可
代码
#include <cstdio>
#include <cstring>
#include <iostream>
typedef long long ll;
const int mod = 1000000007;
int cnt, x, llen;
int num[2000];
int dp[2000][11][11][2];
char l[2000], r[2000];
bool _f, f;
int dfs(int len, int p1, int p2, bool limit, bool flag, int s = 0)
{
if (len == 0) return (p1 ^ 10) && flag;
int& dp = ::dp[len][p1][p2][flag];
if (!limit && ~dp && (p1 ^ 10) && (p2 ^ 10)) return dp;
int mx = limit ? num[len] : 9;
for (register int i = 0; i <= mx; ++i)
{
_f = flag || i == p1 || i == p2;
x = p1 == 10 && i == 0 ? 10 : i;
s = ((ll)s + dfs(len - 1, x, p1, limit && (i == mx), _f)) % mod;
}
if (!limit && (p1 ^ 10) && (p2 ^ 10)) dp = s;
return s;
}
int solve(char x[])
{
cnt = strlen(x);
for (register int i = 0; i < cnt; ++i) num[i + 1] = x[cnt - i - 1] - '0';
return dfs(cnt, 10, 10, 1, 0);
}
int main()
{
memset(dp, -1, sizeof(dp));
std::ios::sync_with_stdio(0);
std::cin >> l >> r;
llen = strlen(l);
for (register int i = 0; i < llen; ++i)
{
if (i - 1 >= 0 && l[i] == l[i - 1]) {f = 1; break; }
if (i - 2 >= 0 && l[i] == l[i - 2]) {f = 1; break; }
}
printf("%d", (solve(r) - solve(l) + f + mod) % mod);
}