题目传送门
数位dp.
#include<iostream> #include<cstdio> #include<cstring> #define mod 1000000007 using namespace std; string l,r; int a[1005],b[1005],f[1005][15][15][2][2][2]; inline long long solve1(int d,int pr,int prp,bool li,bool qd,bool s) { long long sum = 0; if(d == l.length() + 1) return s; if(f[d][pr][prp][li][qd][s] != -1) return f[d][pr][prp][li][qd][s]; int res = li ? a[d] : 9; for(int i = 0;i <= res; i++) sum = (sum + solve1(d + 1,(qd && i == 0) ? -1 : i,pr,li && (i == res),qd && (i == 0),s || (i == pr && pr != -1 || i == prp && pr != -1 && prp != -1)) % mod) % mod; f[d][pr][prp][li][qd][s] = sum; return sum; } inline long long solve2(int d,int pr,int prp,bool li,bool qd,bool s) { long long sum = 0; if(d == r.length() + 1) return s; if(f[d][pr][prp][li][qd][s] != -1) return f[d][pr][prp][li][qd][s]; int res = li ? b[d] : 9; for(int i = 0;i <= res; i++) sum = (sum + solve2(d + 1,(qd && i == 0) ? -1 : i,pr,li && (i == res),qd && (i == 0),s || (i == pr && pr != -1 || i == prp && pr != -1 && prp != -1)) % mod) % mod; f[d][pr][prp][li][qd][s] = sum; return sum; } int main() { cin >> l >> r; for(int i = 0;i < l.length(); i++) a[i+1] = l[i] - '0'; for(int i = 0;i < r.length(); i++) b[i+1] = r[i] - '0'; a[l.length()]--; memset(f,-1,sizeof(f)); long long ans1 = solve1(1,-1,-1,1,1,0) % mod; memset(f,-1,sizeof(f)); long long ans2 = solve2(1,-1,-1,1,1,0) % mod; printf("%d",(ans2 - ans1 + mod) % mod); return 0; }
#include<iostream> #include<cstdio> #include<cstring> #define mod 1000000007 using namespace std; int t,s[20],len; long long l,r,ans,ans1,f[20][2][15]; inline void fenjie(long long x) { len = 0; while(x) { s[++len] = x % 10; x /= 10; } } inline long long dfs(int d,int sum,bool li,int p) { if(d == 0) return sum % mod; if(f[d][li][p] != -1) return f[d][li][p]; long long ss = 0; int res = li ? s[d] : 9; for(int i = 0;i <= res; i++) ss = (ss + dfs(d - 1,sum + (i == p),li && (i == res),p) % mod) % mod; f[d][li][p] = ss % mod; return ss % mod; } inline void chushihua() { ans = ans1 = 0; len = 0; memset(f,-1,sizeof(f)); memset(s,0,sizeof(s)); } int main() { scanf("%d",&t); while(t--) { scanf("%lld%lld",&l,&r); chushihua(); fenjie(l - 1); for(int i = 1;i <= 9; i++) { memset(f,-1,sizeof(f)); ans = (ans + (dfs(len,0,1,i) % mod * i) % mod) % mod; } fenjie(r); for(int i = 1;i <= 9; i++) { memset(f,-1,sizeof(f)); ans1 = (ans1 + (dfs(len,0,1,i) % mod * i) % mod) % mod; } printf("%d ",(ans1 - ans + mod) % mod); } return 0; }
AC代码1是自己写的,代码比较复杂.
AC代码2是自己写后照着题解改的,代码比较简洁