int dig[20];//拆完的数
lint dp[20][10];//记忆化数组
lint dfs(int pos, int last, bool lim, bool lead/*这两个就是细节了*/) {
if(!pos) return 1;
if(!lead and !lim and dp[pos][last] != -1) return dp[pos][last];//上文所说的再利用
lint res=0; const int up = lim ? dig[pos] : 9;
for(int i = 0; i <= up; i ++)
if(abs(i - last) >= 2) {//题目要求
if(lead and !i) res+=dfs(pos-1, -100, lim and i==up, 1);
else res += dfs(pos-1, i, lim and i==up, 0);
}
return !lim and !lead ? dp[pos][last] = res : res;
}
注意到以上代码中有两个前面没有提到过的东西,lim 和 lead,我们分别来说。
$lead$ 用来判断前导零的存在,有着判断可否向下一位传递结果和可否利用之前记忆的结果的作用。前导零是一个数最前面的 $0$。如 $011$ 有前导零而 $11$ 没有。可以将有前导零的数看做不完整的数字,它前面还要有东西的。所以它的作用就显然了(吧)。
如果还不明白的话,希望代码会有帮助。
### 完整代码:
```cpp
// code by 樓影沫瞬_Hz17
#include <bits/extc++.h>
using namespace std;
using lint = long long;
int dig[20];
lint dp[20][10];
lint dfs(int pos, int last, bool lim, bool lead) {
if(!pos) return 1;
//已经搜到了第零位,说明返回后是第一位,故返回1
if(!lead and !lim and dp[pos][last] != -1) return dp[pos][last];
//前两个条件表示我要搜完整的区间,后一个表示我搜过这个区间
lint res=0; const int up = lim ? dig[pos] : 9;//有限制的话当然不能搜完所有了
for(int i = 0; i <= up; i ++)
if(abs(i - last) >= 2) {//题目条件
if(lead and !i) res += dfs(pos-1, -100/*意思是还没完呢,一串0*/, lim and i==up/*只有既到上界又有限制才能把限制下传*/, 1/*有前导0*/);
else res += dfs(pos-1, i/*last*/, lim and i==up, 0);//同理
}
return !lim and !lead ? dp[pos][last] = res : res;//记忆化
}
lint work(lint num) {
int t = 0;//位数
do dig[++t] = num % 10;//拆数
while(num /= 10);
return dfs(t, -100, 1, 1);//从上往下搜
}
int main(){
memset(dp, -1, sizeof dp);
lint A, B;
cin >> A >> B;
//简单的容斥
cout << work(B) - work(A-1) << endl;
return 0;
}
```