先不考虑是否有前导
0
0
0的限制。
如果
l
>
1
e
10
l>1e10
l>1e10,相减之后含前导
0
0
0的答案自然会被抵消。
如果
l
=
=
1
e
10
l==1e10
l==1e10,
l
−
1
l-1
l−1就会少一位。这时候就抵消不了了。
1
e
10
1e10
1e10和
1
e
10
−
1
1e10-1
1e10−1统计出来答案的差不止为1。为什么呢?可以这样考虑:
1
e
10
1e10
1e10的比
1
e
10
−
1
1e10-1
1e10−1多了一位。把这两个数右对齐。那么
1
e
10
1e10
1e10多出来了最左边一位。
如果这一位填
1
1
1,就只有
1
e
10
1e10
1e10这一个符合。这是多出来的一个。(然而不止这一个)
如果这一位填
0
0
0,那么后面接着的两位填
0
0
0,满足了连续三个相同,之后就可以任意填了(8与4不同时出现)但是这时候看另一个数。如果它前面两位填
0
0
0,后面是不能随便填的,因为还没有满足连续三个,于是它们之间差的就不止一个了。但是其他情况都是可以一一对应的。于是 符合条件的数的个数之差为:小于等于9999999999的数中(可含前导0),前两位为0且不满足条件的数(但需满足8与4不同时出现)的个数。因为这些数在11位数里符合,在10位数里就不符合了。
解决办法1:特判一下 l = = 1 e 10 l==1e10 l==1e10。加1是加上 1 e 10 1e10 1e10本身这个数。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll oo=1e10;
int a[20],len;ll f[20][2][10][10][2][2],l,r;
inline ll dp(int pos,int ok,int prepre,int pre,int eight,int four,bool limit,ll ans=0){
if(eight&&four) return 0;
if(!pos) return ok;
if(~f[pos][ok][prepre][pre][eight][four] && !limit) return f[pos][ok][prepre][pre][eight][four];
int up=limit?a[pos]:9;
for(int i=0;i<=up;++i) ans+=dp(pos-1,ok||((prepre==pre)&&(prepre==i)),pre,i,(i==8)||eight,(i==4)||four,(i==up)&&limit);
if(!limit) f[pos][ok][prepre][pre][eight][four]=ans;
return ans;
}
inline ll solve(ll x,int pos=0){
memset(f,-1,sizeof(f));
for(len=0;x;x/=10) a[++len]=x%10;
return dp(len,0,-1,-1,0,0,true);
}
int main(){
cin>>l>>r;
if(l==oo) cout<<solve(r)-solve(l)+1;
else cout<<solve(r)-solve(l-1);
}
解决办法2:首位从1开始填。这样就不存在前导0了。然而当 l = = 1 e 10 l==1e10 l==1e10的时候, l − 1 l-1 l−1的贡献就是0了。小于 1 e 10 1e10 1e10的数都是不符合的。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll oo=1e10;
int a[20],len;ll f[20][2][10][10][2][2],l,r;
inline ll dp(int pos,int ok,int prepre,int pre,int eight,int four,bool limit,ll ans=0){
if(eight&&four) return 0;
if(!pos) return ok;
if(~f[pos][ok][prepre][pre][eight][four] && !limit) return f[pos][ok][prepre][pre][eight][four];
int up=limit?a[pos]:9;
for(int i=(len==pos);i<=up;++i) ans+=dp(pos-1,ok||((prepre==pre)&&(prepre==i)),pre,i,(i==8)||eight,(i==4)||four,(i==up)&&limit);
if(!limit) f[pos][ok][prepre][pre][eight][four]=ans;
return ans;
}
inline ll solve(ll x,int pos=0){
if(x<oo) return 0;
memset(f,-1,sizeof(f));
for(len=0;x;x/=10) a[++len]=x%10;
return dp(len,0,-1,-1,0,0,true);
}
int main(){cin>>l>>r;cout<<solve(r)-solve(l-1);}