http://acm.hdu.edu.cn/showproblem.php?pid=3555
数位DP,三维记录,dp[vis][fg][index],vis表示前面是否出现过49,fg表示前一位数是否为4,index为数字剩余长度。结果用__int64保存。
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define int64 __int64
#define ll long long
#define mod 1000000007
#define M 20
int num[M];
int64 dp[2][2][M];
int64 Dfs(int index , int vis , int fg , int lim)
{
if (!index)
{
if (vis)return 1;
return 0;
}
if (!lim && dp[vis][fg][index] != -1)return dp[vis][fg][index];
int i, up = lim ? num[index] : 9;
int64 ret = 0;
for (i = 0 ; i <= up ; i++)
{
ret += Dfs(index-1 , vis||(fg&&i==9) , i==4 , lim&&i==up);
}
if (!lim)dp[vis][fg][index] = ret;
return ret;
}
int64 Solve(int64 k)
{
int len = 0;
while (k)
{
num[++len] = k%10;
k /= 10;
}
return Dfs(len,0,0,1);
}
int main()
{
int t;
int64 n;
memset(dp , -1 , sizeof dp);
scanf("%d",&t);
while (t--)
{
scanf("%I64d",&n);
printf("%I64d\n",Solve(n));
}
return 0;
}