Description
一个数是非回文数当且仅当不包含长度大于 111 的回文数。比如 162761627616276 是无回文数,而 172761727617276 因为含有 727727727 而不是。
求区间内有多少个非回文数。
Input
一行两个整数 LRL RLR(0≤L≤R≤10180 \le L \le R \le 10^{18}0≤L≤R≤1018)。
Output
非回文数数量。
123 321
-
Sample Input
153
-
Sample Output
HINT
对于 25%25\%25% 的测试数据,b−a≤100000b − a \le 100 000b−a≤100000.
对于所有测试数据,0≤L≤R≤10180 \le L \le R \le 10^{18}0≤L≤R≤1018.
翻译来自 abcdabcd987。
Source/Category
如果一个串里有长度大于1的回文串,那么里面必然有两个相邻或各一个字符相等的字符.
那么直接数位DP即可.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll dp[20][11][11][2]; int a[20];
ll dfs(int k, int pre, int prepre, bool lim, bool flag) { // k:当前位 pre:前一个数 prepre:前两个数 lim:是否限制 flag:前导零
if (k==-1) return 1LL; // 边界返回
if (dp[k][pre][prepre][lim]) return dp[k][pre][prepre][lim]; // 已到达,直接返回
ll res = 0; int len = (lim) ? a[k]+1 : 11;
for (int i=(flag)?2:1; i<len; ++i) {
if ((i!=pre) && (i!=prepre)) res += dfs(k-1, i, pre, ((lim)&&(i==a[k])), false);
}
return dp[k][pre][prepre][lim] = res; // 存储结果返回
}
ll quickpow(ll a, int b) {
ll res = 1LL;
while (b) {
if (b&1) res *= a;
a *= a; b >>= 1;
}
return res;
}
ll query(ll n) {
if (n==0LL) return 1LL;
if (n==-1LL) return 0LL;
memset(dp, 0, sizeof (dp)); int log10 = -1;
while (n>0LL) {
a[++log10] = int(n%10)+1; n /= 10;
}
ll res = dfs(log10, 0, 0, true, true); if (log10==0) ++res;
if (log10>0) res += query(quickpow(10LL, log10)-1LL); // 关于前导零的没有特盼,于是有了这一句
return res;
}
int main() {
ll a, b; scanf("%lld%lld", &a, &b);
printf("%lld", query(b)-query(a-1));
return 0;
}