#212-[数位DP]非回文数

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

LibreOJ 回文串 

如果一个串里有长度大于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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值