http://acm.hdu.edu.cn/showproblem.php?pid=3555
数位dp(bfs版)
1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 6 long long bit[64]; 7 long long dp[64][2]; 8 9 long long dfs(long long len,long long is4,long long p) 10 { 11 if (!len) return 1; 12 if (!p&&dp[len][is4]>=0) return dp[len][is4]; 13 long long cut=0,i,mx=p ? bit[len] : 9; 14 for (i=0;i<=mx;i++) 15 { 16 if (is4&&i==9) continue; 17 cut+=dfs(len-1,i==4,p&&i==mx); 18 } 19 return p ? cut : dp[len][is4]=cut; 20 } 21 long long f(long long n) 22 { 23 long long len=0; 24 while (n) 25 { 26 bit[++len]=n%10; 27 n/=10; 28 } 29 memset(dp,-1,sizeof(dp)); 30 return dfs(len,0,1); 31 } 32 int main() 33 { 34 long long t,n; 35 cin>>t; 36 while (t--) 37 { 38 cin>>n; 39 cout<<n-f(n)+1<<endl; 40 } 41 return 0; 42 }
数位dp
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 long long dp[20][3]; 5 long long n; 6 void Init() 7 { 8 long long i; 9 memset(dp,0,sizeof(dp)); 10 dp[0][0]=1; 11 for (i=1;i<20;i++) 12 { 13 dp[i][0]=dp[i-1][0]*10-dp[i-1][1]; 14 dp[i][1]=dp[i-1][0]; 15 dp[i][2]=dp[i-1][2]*10+dp[i-1][1]; 16 } 17 } 18 long long ans() 19 { 20 long long sum=0,s[20],l=0,flag=0; 21 while (n) 22 { 23 s[++l]=n%10; 24 n/=10; 25 } 26 s[l+1]=0; 27 for (;l;l--) 28 { 29 sum+=dp[l-1][2]*s[l]; 30 if (flag) sum+=dp[l-1][0]*s[l]; 31 else if (s[l]>4) sum+=dp[l-1][1]; 32 if (s[l+1]==4 && s[l]==9) flag=1; 33 } 34 return sum; 35 } 36 int main() 37 { 38 long long t; 39 cin>>t; 40 while (t--) 41 { 42 cin>>n; 43 // for (int i=1;i<5;i++) 44 // cout<<dp[i][0]<<" "<<dp[i][1]<<" "<<dp[i][2]<<endl; 45 n+=1; 46 Init(); 47 cout<<ans()<<endl; 48 } 49 }